python,django,validation,django-models,django-orm
https://docs.djangoproject.com/en/1.8/ref/validators/#how-validators-are-run See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on...
python,django,email,django-models
This is pure python code for sending emails using SMTP Lib from threading import Thread import requests import time import smtplib def email_sender(input_message, email_to, client): ''' function to send email ''' to = email_to gmail_user = 'email of sender account' gmail_pwd = 'password of sender account' smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo()...
django,django-models,django-admin
This is what you should have in admins.py: from django.contrib import admin from models import Author, Book class BookInline(admin.StackedInline): model = Book class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline ] admin.site.register(Author, AuthorAdmin) admin.site.register(Book) You probably forgot to include 'AuthorAdmin' in this line: admin.site.register(Author, AuthorAdmin) ...
python,django,csv,django-models
This line seem to work for me: with open(TICKERS, encoding='utf-8', errors='ignore') as f: ...
python,django,django-models,django-admin
Easy school_name = "your school name" Students_in_school = Student.objects.filter(grade__school__name = school_name) Sorry I wrote this on Bus...
django,django-models,foreign-keys,django-admin
Update The code I posted earlier was wrong! I didn't read your models too carefully. Sorry about that. If you want to create CharacterSeries and CharacterUniverse while you create/edit the Character, you could do this: from django.contrib import admin from .models import Character, CharacterUniverse, CharacterSeries # No need to define...
In don't understand what you mean by "Prefix the PK ID field with j1_, followed by a unique ID in base 36"... But anyway: of course you can use whatever field type (including your own custem field type) you want as primary key - you just have to specify it...
django,django-models,django-admin
Try: when_first_upload = models.DateTimeField(default=datetime.datetime.now) You need the callable itself, not the result returned by it....
The reason the ForeignKey cannot reference an abstract model directly is that individual models that inherit from the abstract model actually have their own tables in the database. Foreign keys are simply integers referencing the id from the related table, so ambiguity would be created if a foreign key was...
You say that "each project can assign multiple contractors" but that not how your model works - it allows a single contractor per project: class Project(models.Model): contractor=models.ForeignKey(Contractor, null=True) ForeignKey if for one to many relationships - here a Project has zero or one Contractor and a Contractor has zero, one...
django,django-models,django-views
The best way is to first try the example in the documentation. If you do not have the patience to read through the documentation, here is an example of something you can try....
python,django,django-models,constraints
You're referring to choices. Example from the docs: from django.db import models class Student(models.Model): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' YEAR_IN_SCHOOL_CHOICES = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) year_in_school = models.CharField(max_length=2, choices=YEAR_IN_SCHOOL_CHOICES, default=FRESHMAN) ...
django,django-models,django-forms,django-templates,django-views
Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.
django,django-models,django-queryset,django-orm,django-1.8
This way seems to work correctly: bars = Bar.objects .prefetch_related('foo_bar') .annotate(sum_foo=Sum( Case( When(Q(foo_bar__is_deleted=False) | Q(foo_bar__is_deleted=None), then='foo_bar__amount'), default=Value(0), output_field=IntegerField() ) ), ) ...
python,django,django-models,django-rest-framework
When you have unique_together set on a model, the serializer will automatically generate a UniqueTogetherValidator that is used to check their uniqueness. You can confirm this by looking at the output of the serializer, and introspecting what Django REST framework automatically generates: print(repr(DeviceContractSerializer())) You can then alter the validators that...
django,django-models,many-to-many,manytomanyfield
I think you just need this: # assuming you have a contributor Registration.objects.filter(contributor=your_contributor_object) ...
python,django,python-2.7,django-models,django-forms
Use raise ValidationError instead of raise ValueError: def clean(self): email = self.cleaned_data["email"] try: User._default_manager.get(email=email) except User.DoesNotExist: return self.cleaned_data raise ValidationError({'email':'Email already registered. Login to continue or use another email.'}) ...
python,html,django,forms,django-models
The problem has to do with the src root on pycharm and the lack of import in the file views.py and urls.py.
python,django,python-3.x,django-models,virtualenv
This should have thrown an error on your Ubuntu install as well. You need to change line 3 of projectName/main/admin.py to: from .models import ContactLink, ContactPost, Personnel, \ WorkCategory, Service, Skill, Work, Customer Notice the added dot . in the from .models part. The import should be relative (assuming all...
Why not just do: class MyModel(models.Model): a = models.IntegerField(default=0) b = models.IntegerField(default=0) c = models.IntegerField(default=0) @property def x(self): return self.a + self.b @property def y(self): return self.x + self.c @property def z(self): return self.x + self.y ...
python,django,django-models,override
The same logic would look like this: from django.db import models from django.db import transaction class MyModel(models.Model): # model definition def save(self, *args, **kwargs): transaction.set_autocommit(False) try: super(MyModel, self).save(*args, **kwargs) foo() # do_other_things except: transaction.rollback() raise else: transaction.commit() finally: transaction.set_autocommit(True) However, this would be equivalent to using the atomic() decorator: from...
django,django-models,django-cms
In your plugin you should access object fields via the instance argument to render, not self.model. Like this: from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin from django.utils.translation import ugettext_lazy as _ from links_plugin.models import Section, SectionConfig class LinksPlugin(CMSPluginBase): name = _("Links Tree Plugin") model =...
jquery,django,django-models,django-forms,django-views
I eventually found a way of solving this. The overarching problem was that I was trying to add information to my Person Model which was not 'generated/originated' from my forms.py / models.py in the traditional way but rather was being 'generated' on the page from my jQuery script. I knew...
django,django-models,django-orm
You are filtering all events with user_id=1 and exclude everything which has events with user_id = 1 which results in an empty queryset. Try this: qs = SchedulerEvent.objects.filter(user_id=<user_id>).exclude(schedulereventreceipt__event__user_id=<user_id>) which excludes all the corresponding SchedulerEventReceipt which has the current user as the user_id...
python,django,django-models,django-admin
There's nowhere to save is_active to, since you haven't assigned a database field to it. You should change the is_active in your model to: is_active = models.BooleanField(default=False) ...
python,django,django-models,django-templates,django-views
You haven't said what you have tried to do to solve this, why you think it's "way overly complicated", or why it's causing you frustration. The thing to understand is that a view is entirely responsible for a page, ie the view creates the entire response when a URL is...
It would be like this s = Subjects.objects.get(name="No.2") q = Question.objects.get(subject=s,ques="no.23") a = Answer.objects.get(question=q,ans2="some answer?") ...
ordered_tasks = TaskItem.objects.order_by('-created_date') The order_by() method is used to order a queryset. It takes one argument, the attribute by which the queryset will be ordered. Prefixing this key with a - sorts in reverse order....
python,django,django-models,django-forms
After fiddling around I got an working solution. Wtowers proposal is not working. Why? Read that one: http://stackoverflow.com/a/13336492/2153744 So we have to handle everything on our own. forms.py # helper class: returning full_name instead of username class UserModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class ProjectForm(forms.ModelForm): manager = UserModelChoiceField(queryset=User.objects.all(), label='Manager', required=True)...
django,django-models,django-admin,django-authentication,django-custom-user
Try doing this might help def create_user(self,email, password=None,**kwargs): OR check these links might help you what you want. link1 link2...
You could have a model VideoComponent with a position field as well as foreign keys to VideoClipModel and ImageModel. Then a Video model would have a many to many field to VideoComponent. class Video(models.Model): components = models.ManyToManyField('VideoComponent') class VideoComponent(models.Model): image = models.ForeignKey('ImageModel') video_clip = models.ForeignKey('VideoClipModel ') position = models.IntegerField() class...
python,django,django-models,django-admin,django-custom-user
REQUIRED_FIELD = ['username'] Should change to: REQUIRED_FIELDS = ['username'] ...
python,django,django-models,django-1.8
You can implement the common models in common_application's models.py file as an abstract model, by adding the following to the model's class: class Meta: abstract = True Then, in other applications you can import your common models like so: from common_application.models import Model_1, Model_2, Model_3 And then instantiate model classes...
python,django,django-models,django-views
pk = request.GET.get('pk') does not raise an exception. It gives you None instead, if pk isn't in GET. So your first case never executes. Try with: @ajax @login_required def search_dist(request): pk = request.GET.get('pk', None) if pk is None: dist_list = request.user.distributors.all() starts_with = request.GET.get('query') if starts_with: dist_list = request.user.distributors.filter( surname__istartswith=starts_with)...
django,postgresql,django-models,database-migration
No fields at all are being migrated when you run manage.py makemigrations <app>, as that command only creates a new migration in your <app>/migrations/ directory. It's only when you run manage.py migrate that changes are written to the database. If you are not getting the expected results, have a look...
python,django,django-models,django-templates,django-template-filters
random.choice does not guarantee to produce non-repeating items. import random random_camps = random.sample(current_campaigns, amount) is the way to go here. Update If you're worried about the speed, this question addresses quick random row selection in postgres....
django,django-models,django-forms
Lot's of Changes needed to your code. I'm posting a working version so that you can try. Put profile.html file as bkmks/templates/bkmks/profile.html Get it working. Customize later. profile.html <form id="taskitem_form" method="post" action=""> {% csrf_token %} {{form}} <input type="submit" name="submit" value="Add Task" class ="btn btn-primary" /> </form> model as it is....
django,django-models,django-queryset
You should reverse the foreign key relationship: class HeartRate(models.Model): timestamp = models.DateTimeField('Date and time recorded') heartrate = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, related_name='heartrates') class Exercise(models.Model): start_timestamp = models.DateTimeField('Starting time') finishing_timestamp = models.DateTimeField('Finishing time') To get all of the heartrates of an exercise: heartrates = my_exercise.heartrates.all() ...
python,django,python-3.x,django-models
You shouldn't use this method to set your default value, rather than override the save method of the model and use it there. For example: class User(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, default=uuid.uuid1) def make_slug(self): return self.first_name + self.last_name[0] def save(self, *args, **kwargs): self.slug =...
django,rest,django-models,django-rest-framework,imagefield
As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...
python,database,django-models,schema-migration
Migrating a model between apps. The short answer is, don't do it!! But that answer rarely works in the real world of living projects and production databases. Therefore, I have created a sample GitHub repo to demonstrate this rather complicated process. I am using MySQL. (No, those aren't my real...
python,django,django-models,django-views
You could use a method like this: class DailyObj(models.Model): ... def total_crores(self): return self.Total_Rec / 10000000 It won't be stored in the database, but will be accessible in the template with something like this: {{ daily_obj.total_crores }} Or, in keeping with your query, something like this (assuming that top10records gets...
python,django,sorting,django-models
You can set the ordering and many other options for a model through the use of the meta class. So for your example: class Address(models.Model): address = models.CharField(max_length=20) ... class Meta: ordering = ['address'] This will order Address models in your queryset after they have been queried from the database....
I usually set to 1. In this case already existed records will be assigned to the first user. If you want you can later reassign these records in the next data migration....
python,django,django-models,django-forms,modelform
Try using: return render(request, 'prueba.html', ctx) instead of return render_to_response('prueba.html',ctx,context_instance=RequestContext(request)) Also, don't foreget to import render as follows: from django.shortcuts import render ...
python,django,postgresql,django-models,django-1.8
When in debug-mode you could use the django.db.backends logger. https://docs.djangoproject.com/en/1.8/topics/logging/#django-db-backends In production I would use loggers for PostGres itself, because saving these queries from within a Django process will (probably) have major impact on your performance....
django-models,django-rest-framework
First you can split the education field value by using split. Then you can serialize it accordingly. class CustomModel: def __init__(self, year,course,college,description): self.year = year self.course = course self.description = description self.college = college class CustomSerializer(NonNullSerializer): year = serializers.IntegerField() course = serializers.CharField() description = serializers.CharField() college = serializers.CharField() Add this...
Upgrade Django Rest Framework as well as Django. Support for the Django 1.8 alpha was added in 3.0.4, and at the time of writing, the latest version is 3.1.3....
python,django,forms,django-models,django-forms
Answering my own question. I am a newbie and hence took a lot of time and effort to figure this our. I was simply missing this in my views: if form.is_valid(): #do something, add user ot DB return render(request, 'mudramantri/index.html', {'registered': True}) else: return render(request, 'mudramantri/index.html', {'form': form}) Since, I...
I would solve it with an additional argument to save, as opposed to attaching to pre_save: import django.db.models class Entry(models.Model): color=models.CharField(max_length="50") def save(self,create_children=True,**kwargs): if create_children and not self.pk: result = super(Entry,self).save(**kwargs) Entry(color=self.color).save(create_children=False) Entry(color=self.color).save(create_children=False) else: result = super(Entry,self).save(**kwargs) return result You want to make sure you call super(Entry,self).save(**kwargs) before you...
python,django,django-models,django-aggregation
Just discovered that Django 1.8 has new conditional expressions feature, so now we can do like this: events = Event.objects.all().annotate(paid_participants=models.Sum( models.Case( models.When(participant__is_paid=True, then=1), default=0, output_field=models.IntegerField() ))) ...
django,django-models,django-middleware
You are trying to match a foreign key to a string, you need to provide the model ProductPart.objects.values().filter(part=v) Note: the values isn't necessary either ProductPart.objects.filter(part=v) From the documentation for Values a QuerySet subclass that returns dictionaries when used as an iterable, rather than model-instance objects. In other words, you are...
django,django-models,one-to-many
I'm not really clear on how you assign messages to tasks. However, if you need the ability to have multiple elements on each side of a relationship, you should use a ManyToManyField, not a ForeignKey. Depending on what you are actually doing, you should be able to validate the correct...
You are interested in the unique_together model meta option: Sets of field names that, taken together, must be unique. class Comment(models.Model): news = models.ForeignKey(Post) user = models.ForeignKey(User) # ... class Meta: unique_together = ('news', 'user') Your user field can then be simply a ForeignKey....
python,html,django,django-models,django-forms
You're not passing the form to the template if the request is a GET. There's really no need to distinguish between the GET and POST in this case when creating the form instance. You can simply instantiate your form as such: form = BlockForm(request.POST or None) and drop the instantiation...
django,django-models,django-forms
Submitting data to a model form does not cause it to be saved automatically. If you want save data from a model form to the database, you need to call its save() method. You could do this in the wizard's done() method. def done(self, form_list, **kwargs): # I don't know...
clients is an installed app, so you should be able to change that line to: from clients.models import Client ...
django,django-models,django-rest-framework,django-serializer
As per the comments implementing the put method closer to the reference implementation in the docs should fix the issue. def put(self, request, pk, format=None): device = self.get_object(pk) serializer = DeviceSerializer(device, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Saving instances has a bit more information on creating, updating...
There is no way around it, you need to save one of the objects twice anyway. This is because, at the database level, you need to save an object to get its ID. There is no way to tell a sql database "save those 2 objects and assign the ids...
django,django-models,django-admin
I don't have enough reputation to add a comment, so I'll write here, even if this is not a real answer. It looks there's an open ticket on this topic: lookup_allowed fails to consider dynamic list_filter You can use two different workarounds to quickly solve this problem until it will...
There's no need for anything so complex or inefficient. You can follow the relationships in a single query: teams = Team.objects.filter(memberships__user=user) ...
Hope the following helps: for i, record in enumerate(qs): record.value = i ...
django,django-models,django-views,django-rest-framework
As of Django REST framework 3.1, it is not possible to submit multiple values using form data. This is because there is no standardized way of sending lists of data with associations, which is required for handling a ListSerializer. There are plans to implement HTML JSON forms support, which would...
python,django,django-models,django-admin
Figured it out (w the help of AbhiP!) Python int typecasting was the main culprit. Stupid problem to have! Below is what worked, and allowed me to not save the calculated field (but display it and make it act like a field in the model): @property def yield_num(self): if self.starts...
python,django,join,django-models,django-queryset
from datetime import date def add_years(d, years): try: return d.replace(year = d.year + years) except ValueError: return d + (date(d.year + years, 1, 1) - date(d.year, 1, 1)) today = datetime.date.today() ago18 = add_years(today, -18) ago25 = add_years(today, -25) # < 18 User.objects.filter(profile__birthdate__gt=ago18) # 18 <= and < 25 User.objects.filter(profile__birthdate__lte=ago18,...
Since you're using ModelForm, why not let Django handle saving the whole model? from django.shortcuts import redirect form = AudioFileForm(request.POST) if form.is_valid(): form.cleaned_data['uploader'] = request.user //view requires login form.save() return redirect(success_url) If you're using Django >=1.7, upload_to field is no longer required. However, I consider it a good practice. https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.FileField.upload_to...
The reverse relation can be used to query related items, but you can't use it to set the object as you are trying. You need to create the params, then update the related object. params = Params.objects.create(name="Test") object_cat.params = params object_cat.save() ...
sql,django,django-models,django-templates
Candidate.objects.filter( Q(Q(languagelevel__language__id__in=(1, 2, 3)) & Q(languagelevel__language__level__gte=1)) | Q(Q(languagelevel__language__id__in=(4, 5)) & Q(languagelevel__language__level__gte=3)) | Q(Q(languagelevel__language__id=6) & Q(languagelevel__language__level__gte=2)) )).values('id').annotate(total=Count('id')) values will only return the id of each candidate with a calculated total as total. If you want to get all of the fields (not only id), you can remove .values('id') as: Candidate.objects.filter(...
Encountered this when upgrading to 1.8 and migrating from MySQL to Postgres. I can't explain why the error occurs, but I was able to get around it by manually adding the column: Delete all migrations Delete records from django_migrations Manually add name column: ALTER TABLE django_content_type ADD COLUMN name character...
If you don't care about your migrations, and the data, just delete the content of the migrations folder and create them again: rm -f yourapp/migrations/* touch yourapp/migrations/__init__.py ./manage.py makemigrations ...
The approach with the ManyToMany field looks good enough. If you were to create another model to hold this manually you would need to add logic to avoid duplication (maybe other things too). Also, with the ManyToMany you end up with users that have contacts...you can for example do this:...
From docs: The field on the related object that the relation is to. By default, Django uses the primary key of the related object. As we know PK is unique. Try setting order_number as unique in WorldEaseConsignee model: class WorldEaseConsignee(models.Model): order_number = models.IntegerField( null=False, blank=False, unique=True ) Also, set to_field...
django,django-models,error-handling,django-rest-framework,django-serializer
Field-level validation is called before serializer-level validation. So model User having username as unique=True, the field-level validation will raise exception because of username being already present. DRF's UniqueValidator does this work of raising exception when a field is not unique. As per DRF source code, class UniqueValidator: """ Validator that...
python,django,database,postgresql,django-models
Try explicitly specifying the id field and marking it as the primary key: class UserProfile(models.Model): id = models.BigIntegerField(primary_key = True) user = models.OneToOneField(User) avatar = models.ImageField(blank=True, upload_to=get_image_path, default='/static/image/avatar/male.png') age = models.IntegerField(default=4, validators=[MinValueValidator(3), MaxValueValidator(99)]) Django should automatically create a sequence for this field. It may be that the User foreign key...
django,django-models,django-migrations
The problem is that you are calling datetime.now() in the default parameter of the definition. That means that the default changes each time you start Django, so the system thinks you need a new migration. You should wrap that calculation into a lambda function, which will be called as necessary:...
python,django,django-models,django-rest-framework,django-serializer
You can use the information on this link. python manage.py inspectdb > models.py https://docs.djangoproject.com/en/1.7/howto/legacy-databases/ It depends on your database, but I've worked with it and is good....
There doesn't really seem to be any good reason to pre-calculate the field here. Multiplying one existing value by another is a simple operation, and there's no benefit to be gained by calculating it on save. There would only be some benefit if the value to be calculated involved a...
Because you're using update, which does the update directly in the database, whereas auto_now is done in Python. This would work: for commment in Comment.objects.filter(...): comment.text="some new text" comment.save() Obviously, this is less efficient than doing it in one go in the db. If you really need that, then you'd...
NOT NULL is a tool to enforce data integrity if that column must never be empty, which is always a good thing. It's better to error out hard and early, than to discover later on that something went wrong and you're left with inconsistent or missing data. Data integrity is...
It should be categories__id__in (double underscore). See Django documentation: QuerySet API reference. UPDATE: If with a comma separated list of ids you mean a comma separated string of ids, then you should: cat_ids = self.request.QUERY_PARAMS.get('cat_ids', None).split(',') ...
python,django,python-2.7,redirect,django-models
Inside your login view, just do this: def login(request): """ Check for login and store the result in login_successful """ path = request.GET.get("next") if login_successful: if path: return HttpResponseRedirect(path) else: return HttpResponseRedirect(your_earlier_path) ...
oracle,django-models,oracle-sqldeveloper
The biggest problem you have is all the application code which references VENDOR_NAME in the dependent tables. Not just using it to join to the parent table, but also relying on it to display the name without joining to VENDOR. So, although having a natural key as a foreign key...
django,django-models,django-templates
{{ object.pub_date|date:"D d M Y" }} {{ object.pub_date|time:"H:i" }} all options explained: documentation...
You start with the model whose objects you want to get, Level4, then follow the relationships with the double-underscore syntax. Level4.objects.filter(level3__level2__level1=my_level1_object) ...
here it says the Generic Foreign Key can be a char: ...For example, if you want to allow generic relations to models with either IntegerField or CharField primary key fields, you can use CharField for the “object_id” field on your model since integers can be coerced to strings by get_db_prep_value()......
python,django-models,geolocation,input-sanitization
There are many, usually provided by mapping or GIS vendors. For example the Google geocoding service accepts a string and returns a ranked set of locations in a standard format: https://developers.google.com/maps/documentation/geocoding/?csw=1#Geocoding Yahoo has one too: https://developer.yahoo.com/boss/geo/#overview like I said, there are many, many. They are usually free for light usage,...
ForeignKey field is translated into ModelChoiceField inside a Django ModelForm. If you inspect that class you will notice that this type of field has an queryset attribute required. By default Django provides the full set of objects. You can override this inside your form __init__ method by providing the parent...
django,django-models,django-rest-framework
If you are using djangorestframework you will need to override to_representation function in your serializer http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior should be something like this def to_representation(self, obj) serialized_data = super(SerializerClassName, self).to_representation(obj) serialized_data["2or4"] = serialized_data["twoOrFour"] //Remove the old field name del serialized_data["twoOrFour"] return serialized_data This code should work where...
If I understands right, class MyList(models.Model): user = ForeignKey(User) list_name = CharField(...) .... def list_items(self): return self.mylistitems_set.all() class MyListItem(models.Model): mylist = ForeignKey(MyList) item_name = ..... .... A user may create as many lists an he/she wants and may add any number of items to a specific list. So logic is...
python,django,python-3.x,django-models,django-1.8
primary_key implies unique=True. So, as the warning says, you should probably be using a OneToOneField.
Your get_model_b_by_currency is returning a queryset rather than a single instance. Every time you slice a queryset, you get a new instance. Instead, either return an instance from get_model_b_by_currency - for instance by using get() instead of filter() - or slice it once, allocate it to a variable, and modify...
django,django-models,django-tables2
Well you can use this plugin here: https://github.com/Alir3z4/django-crequest Use it like this: def render_eventResponse(self, record): from crequest.middleware import CrequestMiddleware current_request = CrequestMiddleware.get_request() user = current_request.user responseObject=record.getResponseFromUser(user) if not responseObject: return '' else: return responseObject.getResponseText ...
I think it might be sufficient to handle this like it is documented here. # myapp/models.py class User(models.Model): user = models.ForeignKey( USER, related_name="%(app_label)s_%(class)s_related" ) class Meta: abstract = True class TestModel(User): title = models.CharField(max_length=80) This way the related name would dynamically become myapp_testmodel_related. Of course you can tweak the name...
python,django,python-3.x,inheritance,django-models
I suspect the problem is that you are inheriting from auth_models.User. This is multi-table inheritance and isn't really appropriate for this situation. See the django docs here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#extending-django-s-default-user Which basically say if you want to store profile data in a separate table there is no need to extend auth_models.User. Just...
Just to clarify a thing, using get() in this situation isn't right, quoting get() docs : If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly Alternatively with what Wtower mentioned,you can also use:...