Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /cart/ Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<house_id>[0-9]+)/$']
Hi am trying to create an online house shopping site but when i to add the items(houses) to the cart i get the following error Internal Server Error: /cart/ Traceback (most recent call last): File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\myprojects\byarent\buyandrent\cart\views.py", line 31, in cart_detail return render(request, 'cart/detail.html', {'cart': cart}) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\user\myprojects\byarent\env\lib\site-packages\django\template\defaulttags.py", line 209, β¦ -
Request & Response >> Device sends HTTP request to web server
I was wondering if anyone has experience with working devices (on arduino) (as client send request, get response from web server). I will use Django as framework to send response. what would be your suggestions? device can only send integer with it is information(it is changeable regarding to the response from server). Is there any example of it? or anything would help me to work on this project? -
Implementation related questions regarding my Rest API
I am currently learning Django, specifically DRF to make an API that will be consumed by a web app client. The app is for a teacher who gives extracurricular classes in Mathematics and Science. Each student will register by paying a monthly fee for their subscription. They will subscribe seperately for Math and Physics, as some of them take only one of the subjects. Only the owner of this business and perhaps a close acquaintence of him will be admins. There are great tutorials and documentation on DRF, but my concern for this question is more in the line of API and backend design and how to tackle certain problems. I am wondering: 1.) How can I, after a user has already registered, deny them access to the website if they haven't payed their monthly fee? Their credentials are already in the database, so how do I check that in my API (specifically, how do I implement such a permission in DRF?) 2.) How can I change a user to an admin in a safe way? See, say the owner eventually decides to promote one of his acquaintances to admin, or the owner of the site changes and a new β¦ -
Keras sequential model in Django - preserve session?
I do not know how I can "preserve" the graph/session of my Keras model inside a Django app that runs as a server. I've build Keras sequential model DeepModel which works fine as a standalone Python module. But now I want to embed it in Django application where I defined the following handler for the model: # instantiated by Django app class DeepModelManager: def __init__(self, params): self.graph = tf.Graph() self.sess = tf.Session() K.set_session(self.sess) with self.sess.as_default(): self.instance = DeepModel(params) self.model = self.instance.build() optimizer = Adam() loss = "categorical_crossentropy" metrics = ["accuracy"] self.model.compile(loss=loss, optimizer=optimizer, metrics=metrics) def train(self): X = ... y = ... K.set_session(self.sess) with self.sess.as_default(): H = self.model.fit(X, y, epochs=20) The process works in the following way: first Django app awaits an init request from external client, then it instantiates DeepModelManager (as a views module variable) which instantiates/builds/compiles the Keras DeepModel then Django app awaits a train request which should trigger the above train function i.e. model fitting But whenever train method is run, I am constantly getting error ValueError: Tensor("training/Adam/Const:0", shape=(), dtype=float32) must be from the same graph as Tensor("sub:0", shape=(), dtype=float32). which I suspect is due to the fact that the TensorFlow session (or the graph) is somehow cleared β¦ -
Django ModelForm not saving
So, even though I see in my tran_form 'data' all of the fields I am trying to save have values, when I run obj = Form.save(commit=False) the object does NOT have the fields set. The way I am calling it, I do not have a pk, so it iis being initialized like tran_form = TranForm(request.POST) - that is, there is no instance being passed in. Anyone know what is going on here? Here is my model form: class TranForm(forms.ModelForm): class Meta: model=Transaction exclude=['origin','ach_entry'] def __init__(self, *args, **kwargs): account_instance = kwargs.pop('account_instance', None) super(TranForm, self).__init__(*args, **kwargs) if account_instance: self.fields['account'].queryset = Account.objects.filter(pk=account_instance.id) self.fields['account'].initial = account_instance self.fields['loan'].queryset = account_instance.loan_set.all() self.fields['share'].queryset = account_instance.share_set.all() post_dt = forms.DateTimeField(widget=forms.TextInput(attrs= { 'class': 'datepicker' })) account = forms.ModelChoiceField(empty_label='---------', required=False, queryset=Account.objects.all()[0:1])#queryset=instance.account_set.all(), initial={'name': 'ALASKA'}) loan = forms.ModelChoiceField(empty_label='---------', required=False, queryset=Loan.objects.all()[0:1])#queryset=Loan.objects.all(), initial={'name': 'ALASKA'}) share = forms.ModelChoiceField(empty_label='---------', required=False, queryset=Share.objects.all()[0:1]) -
DJANGO Different signal behavior in different contexts (really weird)
I have a custom signal and there is a classmethod which updates some objects where I need this signal to be disconnected so changes are not synced to pipedrive because this method is used only by a view for webhooks. @classmethod def backsync_all_stages(cls): s = sync_object.disconnect(sync_object_receiver) stages_json = PipeDriveWrapper.get_all_stages() if stages_json.get('success'): And there is a view which calls this method if request is POST: def post(self,request,*args,**kwargs): data = json.loads(request.body) model_alias = data['meta']['object'] Model = PipedriveSync.WEBHOOK_MODEL_MAP[model_alias] if Model == LeadStage: PipedriveSync.backsync_all_stages() ... The problem is that sometimes it disconnects the signal and sometimes it doesn't. When I call PipedriveSync.backsync_all_stages() inside shell_plus, it works correctly. But according to view - I see in debugger that in both cases, the method is called from the same view. I absolutely don't understand what is happening. So I invoke the webhook and set breakpoint under the disconnect command so you can see it returns True and traceback. So invoking the webhook and waiting... You can clearly see that the method is called from view and that signal wasn't disconnected (returned False). Meanwhile there was probably a couple of another posts since the webhook sends multiple requests. So I switch to Thread-8 in debugger. There I β¦ -
Django complex QuerySet ManyToManyField with other ManyToManyField
Sorry for this title, I wasn't sure how to name it properly. I'm having problem with getting queryset of ManyToManyField that is in relation with other ManyToManyField. So it's look like this, there is model Company that has ManyToManyField with Person and Person model got ManyToManyField with Position, because logic behind it is that 1 company can have many persons and 1 person can have few positions and can be employed by few companies (which is clear I think). I'm getting the queryset for Person in Company by this way {% for team in brand.team.all %} <p>{{ team.first_name }} {{ team.last_name }}</p> <img class="img-thumbnail" src="/media/{{ team.photo }}"> <p>{{ team.position }} </p> <p>{{ team.about }} </p> {% endfor %} And I'm getting what I want, comparing this to template looks like this but I'm not getting positions of person, only company.Position.None and I've no idea how to get this. From documentation so far I know that it works for single ManyToManyField but I couldn't find example similar to mine case and I'm not sure how I should get (person's position) Below are my files models.py from django.db import models ... TYPES = ( ('Startup', 'Startup'), ... ) CITIES = ( ('Warszawa', β¦ -
django-rest-framework and Django Parler's translation field
I've got model with translated fields. class Device(TranslatableModel): translations = TranslatedFields(name=models.CharField(max_length=100)) I made a serializer like: class DeviceSerializer(TranslatableModelSerializer): translations = TranslatedFieldsField(shared_model=Device) class Meta: model = Device fields = ('translations',) It gives me nice JSON like it should. { "count": 1, "next": null, "previous": null, "results": [ { "device": { "translations": { "en": { "name": "Sample Device" } } } } ] } Now i want to use it with django-rest-framework. In my template I've written script like: $('#devices').DataTable({ 'serverSide': true, 'ajax': 'api/devices/?format=datatables', 'columns': [ {'data':'device.translations.en'} It refuses to work with me. I am getting django.core.exceptions.FieldError: Unsupported lookup 'en' for AutoField or join on the field not permitted. If I am not appending .en to {'data'} it gives Object.object of course. -
ModuleNotFoundError: No module named 'django' ...................How can solve it
How I solve it..... PS F:\django_project\helloworld_proj> python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Passing keyword argument into formset that is extended from BaseFormSet
I've had to create a custom formset to validate the results of my formset. I've simplified the validation for the purpose of this example. forms.py class BaseUserServiceFormSet(BaseFormSet): def clean(self): for form in self.forms: user_title = form.cleaned_data['user_title'] if user_title == None: self.add_error('user_title', "Please enter a title for this service.") Within my views, I'm passing a queryset into the formset. views.py UserServiceFormSet = modelformset_factory(UserService, form=UserServiceForm, formset=BaseUserServiceFormSet, extra=1, max_num=4, can_delete=True) formset = UserServiceFormSet(request.POST or None, request.FILES or None, queryset=UserService.objects.filter(user=user, title__extra_service=1), prefix='first') When I open my page, I get the following error: __init__() got an unexpected keyword argument 'queryset' I've tried adding the following to my BaseUserServiceFormSet (in forms.py), but then I start to get a bunch of errors that refer to the default values that are initialized within the BaseFormSet (https://docs.djangoproject.com/en/2.1/_modules/django/forms/formsets/). In otherwords, with my code, I'm overwritting the default init of BaseFormSet, which breaks things. def __init__(self, *args, **kwargs): queryset = kwargs.pop('queryset') What change would I have to make in order to pass my queryset into my formset as a kwarg? Thank you! -
Referencing model attributes within form
I am hoping to edit multiple models at the same time on a singe page. Rather than using formsets, I got this to work with an array of forms that I loop through in the template in the view: {% extends 'app_base.html' %} {% block content %} <p>{{message}}</p> <form method="post">{% csrf_token %} {% for form in forms %}{{ form.as_p }}{% endfor %} <input type="submit" value="Submit" /> </form> {% endblock %} However, annoying, I cannot see what I am editing in the output as its just a bunch of text boxes without labels. As such, is there any way to access the model attributes alongside the form as I loop through like: {% for form in forms %}{{form.object.name}}: {{ form.as_p }}{% endfor %} -
Submitting a form with Ajax, is_valid method is ignored
In a form, I'm try to add some more data after form is submitted: def is_valid(self): # print('something') valid = super().is_valid() if valid: self.cleaned_data['ctp'] = self.ctp return valid I submit the form using Ajax, and it seems is_valid is never called. How can I add the value to the post after the form is cleaned/submitted. -
Django model design advice
I am currently learning Django, specifically DRF to make an API that will be consumed by a web app client. The app is for a teacher who gives extracurricular classes in Mathematics and Science. My basic idea is that there will be two types of User, a Student and a Teacher. Teachers will obviously have more access rights than Students. The problem is, a django User class has the is_admin attribute and, since only Teachers could possibly be admin of the site, I cannot create a single User class that has is_admin and user_type attribute. For instance, the User with is_admin=True and user_type=Student will be an invalid combination. My idea is to make my User class as an Abstract Base Class and then make two seperate classes, Student and Teacher, that inherit from it. This is also ideal in the sense that only Teachers can publish articles, which means the Student class just won't have that permission, but then I face another problem. All Users have a single Profile. The Profile will store a bio, an avatar image of the user, etc. But when setting up the OneToOneField relationship in Profile, the profile must have that relationship with Students and β¦ -
Can't disconnect signal (but disconnect returns True)
So I've created my own signal which syncs objects of different Models to server. The problem is that I can't disconnect this signal. I tried to specify sender too which is a common problem but without success. This disconnecting returns True sync_object = Signal(providing_args=['instance']) Then in models @receiver(sync_object) def sync_object_receiver(sender, instance, **kwargs): print(f'Syncing {instance}') instance.sync_with_pipedrive() There is another signal which invokes it @receiver(post_save, sender=LeadStage) def create_pdsync_and_sync_leadstage(instance, sender, created, **kwargs): pipedrivesync = getattr(instance, 'pipedrivesync', None) if not pipedrivesync: pipedrivesync = PipedriveSync.objects.create(content_object=instance) sync_object.send(instance=pipedrivesync) That's why I'm disconnecting the signal but it doesn't work and send_object_receiver is being called even if it's disconnected. The main function @classmethod def backsync_all_stages(cls): ss = sync_object.disconnect(sync_object_receiver,sender=LeadStage) s = sync_object.disconnect(sync_object_receiver) # s = True, ss = False ... stage = stagesync.content_object stage.name = name stage.order = int(order) stage.save() # HERE IT IS INVOKED except PipedriveSync.DoesNotExist: stage = LeadStage.objects.create(name=name, order=int(order)) stagesync = stage.pipedrivesync stagesync.pipedrive_id = pipedrive_id sync_object.connect(sync_object_receiver) As you can see I call sync_object.send(instance=pipedrivesync) inside post_save signal. I do not specify any sender which I don't do while disconnecting the signal so it should work - it shouldn't be invoked but it is. Do you know what's wrong? -
Django REST Image upload and user profile
Recently i am developing a mobile app (android) . For backend i am using Django REST. At first i created an user API . Which post user full name and email from google login. The main objective of my mobile app is solve user problem . Here user will upload photo from mobile app which will save under specified user already registered . Finally i want know that how can i post image in my django backend under a registered user . If someone figured out this , please post it. Help will be highly appreciated. -
Django directs all requests to child application instead of mainapp
Here is the tree of my project: βββ db.sqlite3 βββ kitchen_analytics β βββ settings.py β βββ static_html β βββ urls.py β βββ wsgi.py βββ manage.py βββ statistics101 β βββ admin.py β βββ apps.py β βββ computation_logic β β βββ dish_count.py β βββ migrations β βββ models_default.py β βββ models.py β βββ statsrouter.py β βββ templates β β βββ index.html β β βββ statistics101 β β βββ orders_list.html β βββ tests.py β βββ urls.py β βββ views.py βββ templates βββ index.html I am trying to add simple html index page, here is my urlpatterns config from kitchen_analytics/urls.py: urlpatterns = [ path('', TemplateView.as_view(template_name='index.html')), path('admin/', admin.site.urls), path('', include(statistics101.urls, namespace='statistics101')), ] When I go to http://127.0.0.1:8000/ I get template not found error. Django tries to go to statistics101 app and looks for index.html there. How do I fix this? Also for some reason I have to keep templates for statistics101 app in templates/statistics101 instead of just templates. How do I keep it in templates? -
Django file conversion from ZC file to png
I try to create a website that convert zc file to png I made the conversion code in python but I cannot figureout how I make the conversion happen in Django website. I also created a file upload in html but I want that file to convert in html website using python code. -
An error occurred while installing gitlab-pygments.rb kera 0.3.2
I have python 3.6,I want to install kera 0.3.2 but I get this error Collecting kera==0.3.2 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPS ConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)",)': /simple/kera/ Operation cancelled by user C:\Users\hp\AppData\Local\Programs\Python\Python36\Scripts>pip install kera==0.3.2 Collecting kera==0.3.2 Could not find a version that satisfies the requirement kera==0.3.2 (from versions: ) No matching distribution found for kera==0.3.2 -
Django - model mixin doesn't work as expected
In PipedriveSync model I use GenericForeignKey so any model can have PipedriveSync object related. class PipedriveSync(TimeStampedModel): ... content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') And I use GenericRelation to be able to reference backwards this object. For example user.pipedrivesyncs.all() Take a look at User class User(AbstractUser): pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync') Since I have to specify the same pipedrivesyncs for many models, I decided to create a mixin for that (there are couple of methods there too but it doesn't matter now). class PipedriveSyncRelatedMixin(): pipedrivesyncs = GenericRelation('pipedrive.PipedriveSync') And I use it this way class User(PipedriveSyncRelatedMixin,AbstractUser): pass The problem is that this Mixin doesn't work the way it works when I specify pipedrivesyncs manually. Case of specifying pipedrivesyncs manually: > u = User.objects.first() > u.pipedrivesyncs.first() > <PipedriveSync: PipedriveSync object (20)> Case when using Mixin > u = User.objects.first() > u.pipedrivesyncs.first() > AttributeError: 'GenericRelation' object has no attribute 'first' Where is the difference and can I use Mixin for this purpose? -
Unable to run formset validation using def clean()
I'm struggling to figure out how to apply formset validation to my formset. When I save the formset, the def clean method isn't run (i.e. 'In formset validation' is never printed to the console). Any thoughts as to why? forms.py class UserServiceForm (forms.ModelForm): active = forms.BooleanField(required=False) sale_expiry = forms.DateField(required=True) class Meta: model = UserService exclude = ('user',) class UserServiceFormSet(BaseFormSet): def clean(self): for form in self.forms: print('In formset validation') user_title = form.cleaned_data['user_title'] title = form.instance.title if user_title == None and title == None: self.add_error('user_title', "Please enter a title for this service.") views.py from accounts.forms import UserServiceForm, UserServiceFormSet from accounts.models import UserService def userservices(request): UserServiceFormSet = modelformset_factory(UserService, form=UserServiceForm) formset = UserServiceFormSet(request.POST or None, request.FILES or None, queryset=UserService.objects.filter(user=user), prefix='first') ... non-relevant bits of view... if request.method == 'POST': if formset.is_valid(): formset_instances = formset.save(commit=True) template My template contains {{ formset.non_form_errors }} {% csrf_token %} {{ formset.management_form }} field level error tags (eg. {{ form.active_service.errors }} Thanks! -
Can I put JS scripts above footer instead of below footer before </body> tag
I have a website which is built with django. Problem: we have >50 pages currently and exactly identical footer HTML code on each of those pages. I am getting tired of having to edit all those pages when adding a little change to the footer. Possible solution: inserting the footer directly in the django base page. Potential problems: if I insert the footer in the base page, all the individual JS scripts between the footer and the tag would be lost - clearly those scripts are page specific. So could I have the specific JS scripts BEFORE the footer? This would allow the footer to go in the base nice and easily, but I'm not sure I can do these. Would moving the scripts before the footer be wrong? Thanks -
Django model constraint for related objects
I have the following code for models: class Tag(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) class Activity(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, through='TagBinding') class TagBinding(models.Model): tag = models.ForeignKey(Tag) activity = models.ForeignKey(Activity) I want to write a database constraint on the TagBinding model using a new Django 2.2 syntax. This constraint should check that tag and activity fields of the TagBinding model have the same user. What I've tried to do: class TagBinding(models.Model): tag = models.ForeignKey(Tag) activity = models.ForeignKey(Activity) class Meta: constraints = [ models.CheckConstraint( name='user_equality', check=Q(tag__user=F('activity__user')), ) ] But this doesn't work because Django doesn't allow to use joins inside of the F function. Also Subquery with OuterRef didn't work for me because models that were referenced in a query were not registered. Is there any way I can implement this constraint using a new syntax without raw SQL? -
Server Error (500) when adding a blog post to django background
When I deployed django, I used nginx and uwsgi, and now I can log in to the homepage, but when I add an article from django-admin (ip:80/admin), I can't enter the edit page, and I see the server. Error (500), I don't know why, I will open the details of my article and I will not be able to modify the page. Please help me find out, what is the reason, thank you very much. this is my models.py: class HuoDong(models.Model): hdname = models.CharField('hdname',max_length = 200,null = False) hddescription = models.CharField('hddescription',max_length = 200,null = False, default = 'ζ΄»ε¨ζθΏ°') hdpicture = models.ImageField('picture',upload_to='static/images/',default = 'normal.jpg') hdblog = UEditorField(width=1000, height=1500, toolbars="full", imagePath="static/images/%%Y/%%m/", filePath="files/",upload_settings={"imageMaxSize":1204000},settings={},verbose_name='hdblog') hdtime = models.DateTimeField('time',auto_now_add = True) def __str__(self): return self.hdname And, I asked, after django deployment, I set DEBUG = False, this time I should go where to find the error message, I read uwsgi.log and nginx error.log, and did not find useful information uwsgi.log: [pid: 2281|app: 0|req: 124/472] 47.104.105.24 () {36 vars in 434 bytes} [Tue Mar 19 20:10:31 2019] GET / => generated 32201 bytes in 10 msecs (HTTP/1.1 200) 5 headers in 293 bytes (1 switches on core 1) [pid: 2342|app: 0|req: 106/473] 139.224.112.110 () {34 vars in β¦ -
Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag?
l'm a fresh user in Django and l am learning through Youtube videos. l did everything same but l got this block tag error. Here is my template name base.html <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> Another template name home.html {% extends "base.html" %} {% block content % } <h1>Hello , Welcome Home</h1> {% endblock %} views.py content : from django.shortcuts import render def home(request): context ={} template = "home.html" return render(request , template , context) I have tried several times but still i could not find where the errors are. Can anyone help me? Thank you. -
Cannot resolve keyword ' ' into field, but all looks ok
There are my models: class Renters(models.Model): org_prav_form = models.ForeignKey(Pravform, models.DO_NOTHING, blank=True, null=True) inn = models.CharField('inn',max_length=100, blank=True, null=True) name = models.CharField('orgname',max_length=150, blank=True, null=True) snameplp = models.CharField(max_length=100, blank=True, null=True) fnameplp = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True verbose_name = 'rent' verbose_name_plural = 'rents' class RentAddres(models.Model): renters_id = models.ForeignKey(Renters, models.DO_NOTHING, verbose_name='renter') subject = models.ForeignKey(SubjectRf, models.DO_NOTHING, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) street = models.CharField(max_length=50, blank=True, null=True) house = models.CharField(max_length=4, blank=True, null=True) housing = models.CharField(max_length=3, blank=True, null=True) Well, I wish define query in the views.py, which get renters__name,renters__inn from Renters model and rentaddres__city,rentaddres__street from RentAddres model. Next result of query exports to .csv file. My views.py: import django_excel as excel from django.db import models from django.http import HttpResponse from renter.models import * from classification_list.models import* import djqscsv def report(request): per = RentAddres.objects.values('pk', 'city', 'street','renters__name','renters__inn') return djqscsv.render_to_csv_response(per) page of associated url throws this: C annot resolve keyword 'renters'. Choices from.. What Is wrong with my code?