Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error with mongodbforms of django
Error: AttributeError at /admin/login/ 'MetaDict' object has no attribute 'pk' WHile submitting to log-in localhost:8000/admin -
JQuery and javascript code working in chrome but not in firefox
I want to expand my article when the read more link is clicked and collapse it by clicking the read less link. The errors I am getting in console include SyntaxError: expected expression, got < dispatch 3. add/q.handle I am including the necessary files here. $(document).ready(function() { var $el, $p, $ph, $ps, $up; $(".button1").on("click", function() { event.preventDefault(); $el = $(this); $p = $el.parent(); $up = $p.parent(); $ph = $up.find(".para"); $ps = $up.find(".rest-content"); if ($ps.is(":hidden")) { $p.load("all_articles.html .rest-content", function() { $ph.hide(), $el.html("(read-less)"), $ps.show(), console.log("It worked") }); } else { $ps.hide(), $ph.show(), $el.html("(read-more)") } }); }); <!-- indivisual_article.html --> <div id="posts"> <p><strong>{{article.title}}</strong></p> {% if article.create_user == user %} <span class="glyphicon glyphicon-remove remove-feed" title="{% trans 'Click to remove this feed' %}"></span> {% endif %} {% if article.post|length > 300 %} <p class="para">{{ article.post|truncatechars:300 }}</p> <p class="rest-content">{{ article.post}}</p> <p class="read-more"><a href="#" class="button1" >(read more)</a></p><br> {% else %} <p class="para">{{ article.post }}</p> <br> {% endif %} <!-- all_articles.html --> {% for article in all_articles %} <div class="infinite-item"> <ul id="posts_ul"> {% include 'articles/indivisual_article.html' with article=article %} </ul> </div> {% endfor %} // urls.py urlpatterns = [ url(r'^articles/$', views.all_articles, name='articles'), url(r'^write/$', views.article, name='write'), url(r'^like/$', views.like, name='like'), url(r'^articles/comment/(?P<post_id>\d+)/$', views.comment, name='art_comment'), url(r'^delete/(?P<post_id>\d+)/$',views.delete,name='delete'), url(r'^load_comments/$',views.load_comments,name='load_comments'), ] -
django-registration-redux and django-crispy-forms: submit button not responding
my registration_form.html is {% extends '../base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} <input type='submit' value="submit"> {% endblock %} the view is in a module in an existing app. its below: from registration.views import RegistrationView from . import forms class MyRegistrationView(RegistrationView): def get_form_class(self): return forms.LoginForm the url in the urls.py file is url(r'^accounts/register/$',MyRegistrationView.as_view()), when the page load, on filling it, when i click submit, it does not submit. pls what am i missing? -
Checking if value exist in database in Django
I have a category field category_name which is unique and I am validating the form value for that field after the form is submitted from django admin. admin.py - from django.core.exceptions import ValidationError class categoryAdmin(admin.ModelAdmin): list_display = ('category_name','module_name') def add_view(self, request, extra_content=None): self.form = CategoryUploadForm return super(categoryAdmin, self).add_view(request) def change_view(self, request, object_id, extra_content=None): self.form = CategoryManageForm return super(categoryAdmin, self).change_view(request, object_id) def save_model(self, request, obj, form, change): if not change: category_name, module_names = \ self.handle_uploaded_file(request.FILES['category_file']) else: category_name = request.POST['category_name'] module_names = request.POST['module_name'] if category_name and Category.objects.filter(category_name=category_name).exists(): raise forms.ValidationError('This category is already in the database. Please supply a different category.') return category_name The error is-- ValidationError at /admin/accounts/category/add/ ['This category is already in the database. Please supply a different category.'] Any help is highly appreciated. Thanks in advance. -
Sentry server not responding on Celery logs
I have a problem related with sending log messages to Sentry server while using Django and Celery async tasks. The log message shows in Sentry server when task is launching synchronous, for example: @celery.shared_task() def test_worker(): logger.warning('Logger works!') raise Exception('---Worker works!') $ from api.tasks import test_worker $ test_worker() When trying launch async task using: $ res = test_worker.delay() Sentry server does not contain log about logger. My settings.py is: RAVEN_CONFIG = { 'dsn': 'http://my_dsn', } SENTRY_AUTO_LOG_STACKS = True LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'DEBUG', 'handlers': ['sentry'], }, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s - %(message)s' }, 'verbose': { 'format': '%(asctime)s [%(levelname)s] %(module)s:%(funcName)s - %(message)s' }, }, 'handlers': { # logs directly to Sentry 'sentry': { 'level': 'DEBUG', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, # logs everything to the console 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'processing': { 'level': 'DEBUG', 'handlers': ['sentry'], 'propagate': False }, 'celery': { 'level': 'DEBUG', 'handlers': ['sentry'], 'propagate': False } }, } Where I made a mistake, or what I am doing wrong? Thanks in advance. -
Python compare a list of objects against a query set for two matching values?
I have created list of objects which holds my live VPN data. I also have VPN data store in a DB. I want to be able to compare the list of live Data objects against the DB, if data matches then do 'something' if an object is anyconnect the usernames will match against the DB, if an object is site to site, then the peer its will match against the BD I need to go through the list of objects and find the matches basically what I'm doing is comparing the live data against the DB data, if the live data is found in the DB I will update the DB record to say the service is 'Up' if it is not found, the service will be 'Down' can anyone point me in the right direction to achieve this? #!/usr/bin/env python from django_setup import setup setup() import re import ipaddress from netmiko import ConnectHandler from monitoring.models import ThirdPartyService from datetime import datetime class VPNData(object): def __init__(self, service_name='', username='', vpn_peer_ip='', duration='', data_transmit='', data_receive='', timestamp=''): self.service_name = service_name self.username = username self.vpn_peer_ip = vpn_peer_ip self.duration = duration self.data_transmit = data_transmit self.data_receive = data_receive self.timestamp = timestamp def __repr__(self): return '{} {}'.format(self.__class__.__name__, self.username) … -
identifying if pdf content is in the last page
knowing that <pdf:pagenumber /> gives the current page number, while <pdf:pagecount /> gives the total page count. I want to acquire these values and be able to compare it using django if/else like this {% ifequal "<pdf:pagenumber />" "<pdf:pagecount />" %} last page content {% endifequal %} how would I be able to compare these two? also tried <pdf:nexttemplate name="lastpage"/> but it's not appropriate to my dynamic setup if only there is "lasttemplate" though -
Django Rest Framework- how to put complex SQL query in views.py
I have some problem with put sql query in Django Rest views.py. views.py from rest_framework import generics from ..models import Stat from .serializers import StatSerializer class StatListView(generics.ListAPIView): queryset = Stat.objects.raw("SELECT parameter1, COUNT(*) FROM statistic_stat GROUP BY parameter1 order by count(*) desc LIMIT 10") serializer_class = StatSerializer serializers.py from rest_framework import serializers from ..models import Stat class StatSerializer(serializers.ModelSerializer): class Meta: model = Stat fields = ('parameter1', 'parameter2') When i run this code i get an error like: "get() returned more than one Stat -- it returned 122!" The same query works in another script (with the same database) and returns the result like this: [('something1', 56), ('something2', 32), ('something3', 21), ('something4', 19), ('something5', 10), ('something6', 8), ('something7', 4), ('something8', 3), ('something9', 2), ('something10', 1)] Any ideas or suggestions what is wrong ? Thank you in advance -
django deplot to heroku error : ETIMEDOUT, Application Error
I made a django project using channels. And I want to deploy it. Because my project uses channels, I need to set up ASGI based environment. I pushed my project and succeeded.So I got URL address. demo-multichat.herokuapp.com When you connect above url, Application error page is shown. And I faced another problem. In my local terminal, when I executed $ heroku run python manage.py migrate I got ETIMEDOUT error. please refer to below picture. Before migrate I stoped and started local redis server. But end up failing migrate. how can I resolve these issues? I want to migrate and eventually connect my web service. My Development Environment : Ubuntu 16.04 / 64bit / My laptop is connected to university wireless network(WIFI) and it is my project github link. myproj -
Change Django required form field to False
I am trying to change the required of a form field to 'False' depending on the input of another field. form: class MyNewForm(forms.Form): def __init__(self, *args, **kwargs): self.users = kwargs.pop('users', None) super(MyNewForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField( max_length=60, required=True, label="Name *:", widget=forms.TextInput( attrs={'class' : 'form-control', 'placeholder': 'Name'}) ) def clean_this_other_field(self): # change required field name = self.fields['name'] print name.required name.required=False print name.required results of print: True False So the field required is changing to 'False' but when the form page reloads it reverts back to 'True' Any suggestions? -
Django manage.py test can't see urls.py, although runserver can
I got a django project, with the following directory structure: BaseDir | manage.py | configDir \ | settings.py , urls.py, wsgi.py |mainApp \ |urls.py , views, models etc. | tests \ |urlTest.py (In case the above is not clear, there's a django config dir and a mainApp dir, the mainApp has it's own urls.py and the tests dir, all directories are python modules with an init.py) if I run manage.py runserver I get the expected application running as it should on the django server. however running manage.py test i get the following django.urls.exceptions.NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. The test is the following: [...] class TestSth(BaseTest): def setUp(self): [some db setup such as users etc] def test_get(self): pprint.pprint(reverse('index')) config/urls.py is: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^mainApp/', include('mainApp.urls')), ] mainApp/urls.py is: from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views app_name = 'app' urlpatterns = [ #/app/ url(r'^$', views.IndexView.as_view(), name='index'), [...] Can someone suggest what I'm doing wrong? This doesn't make much sense -
Implentation of a Django Query
In my project, I have two tables A & B. Table A has two attributes x,y and the values are in the form x= 'p,q,r,s' y = 'l,m,n' Table B has similar attributes x,y. Now I want to implement a django query that query table B with 75% match. -
starttls() is giving me a SMTPServerDisconnect Error, when trying to send emails via django/python
Follow is my code from the python manage.py shell and the error that appears. I am testing this because django send_mail was giving me the same error so I tried to reproduce it in the shell >>> import smtplib >>> server = smtplib.SMTP('smtp.gmail.com', 587) >>> server.set_debuglevel(1) >>> server.ehlo() send: 'ehlo PKL-FKHAN-LT.mgc.mentorg.com\r\n' reply: '250-smtp.gmail.com at your service, [58.27.158.222]\r\n' reply: '250-SIZE 35882577\r\n' reply: '250-8BITMIME\r\n' reply: '250-STARTTLS\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-PIPELINING\r\n' reply: '250-CHUNKING\r\n' reply: '250 SMTPUTF8\r\n' reply: retcode (250); Msg: smtp.gmail.com at your service, [58.27.158.222] SIZE 35882577 8BITMIME STARTTLS ENHANCEDSTATUSCODES PIPELINING CHUNKING SMTPUTF8 (250, 'smtp.gmail.com at your service, [58.27.158.222]\nSIZE 35882577\n8BITMIME\ nSTARTTLS\nENHANCEDSTATUSCODES\nPIPELINING\nCHUNKING\nSMTPUTF8') >>> server.starttls() send: 'STARTTLS\r\n' Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python27\lib\smtplib.py", line 645, in starttls (resp, reply) = self.docmd("STARTTLS") File "C:\Python27\lib\smtplib.py", line 394, in docmd return self.getreply() File "C:\Python27\lib\smtplib.py", line 365, in getreply + str(e)) SMTPServerDisconnected: Connection unexpectedly closed: [Errno 10054] An existin g connection was forcibly closed by the remote host I looked at all the questions and most problems arise after this step, so I must be missing something very basic here. -
Django 1.10 custom User 'is_superuser' clashes with the field 'is_superuser' from model
I write a custom user class - CustomUser in models.py, mainly followed here import re from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core.mail import send_mail from django.core import validators from django.contrib.auth.models import (AbstractUser, PermissionsMixin, UserManager) class CustomUser(AbstractUser, PermissionsMixin): """ custom user, reference below example https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py """ username = models.CharField(_('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbers and ' '@/./+/-/_ characters'), validators=[validators.RegexValidator( re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid') ]) email = models.EmailField(_('email address'), max_length=254) create_time = models.DateTimeField(auto_now_add=True) active = models.BooleanField() # if we can retrieval it from outside objects = UserManager() USERNAME_FIELD = 'username' class Meta: verbose_name = _('user') verbose_name_plural = _('users') def email_user(self, subject, message, from_email=None): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email]) def __str__(self): return self.username Then I registered it in admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser # Register your models here. class CustomUserAdmin(UserAdmin): model = CustomUser admin.site.register(CustomUser, CustomUserAdmin) But when I run python manage.py createsuperuser to create a superuser, I got the following error: ERRORS: myapp.CustomUser.is_superuser: (models.E006) The field 'is_superuser' clash es with the field 'is_superuser' from model 'myapp.customuser'. -
Using one app function attribute into another app function
I need help For example , i have two app in my project ,Blog and Post . In Blog app i have a function with name Promo as def Promo(): global x x= 10 y= 20 c= x + y return c In second app Post , i have Code function and i want use x in this function def Code(): d = x + 10 return d But error occurred something like that : global name 'x' is not defined How can i use x value into Code function that located in Post app in same project ? -
Django-cms can't display menu correctly
I create some pages, but my menu can't display correctly. My main page I don't know the problem is in the css or in the module importing error. As the django-cms tutorial descript, the correct page is as follows:correct page Do I description my question clearly? Thanks all visit this problem. -
FormView in edit form | Django dont see object pk?
I have CBV with View which works perfect. I am trying to rewrite this code with FormView. Is my FormView code correct? I need someone who can analyze that code and say where is my mistakes. I would be grateful for any help. Right now get method works. I can open edit form and see currect data. The problem is when I try to submit edit form after changes. It seems like form_valid method not correct. Next below you can see error. CBV with View: class ArticleEditView(View): def post(self, request, pk, *args, **kwargs): data = dict() article = Article.objects.get(pk=pk) article_edit_form = ArticleForm( request.POST, request.FILES, instance=article ) if article_edit_form.is_valid(): article_edit_form.save() data['form_is_valid'] = True context = { 'articles': Article.objects.all() } data['html_articles'] = render_to_string( 'article/articles.html', context ) else: data['form_is_valid'] = False return JsonResponse(data) def get(self, request, pk, *args, **kwargs): data = dict() article = Article.objects.get(pk=pk) article_edit_form = ArticleForm(instance=article) context = { 'article': article, 'article_edit_form': article_edit_form } data['html_article_edit_form'] = render_to_string( 'article/edit_article.html', context, request=request ) return JsonResponse(data) CBV with FormView: class ArticleEditView(FormView): template_name = 'article/edit_article.html' form_class = ArticleForm def get(self, request, pk): data = dict() context = { 'article': Article.objects.get(pk=pk), 'article_edit_form': ArticleForm(instance=Article.objects.get(pk=pk)) } data['html_article_edit_form'] = render_to_string( 'article/edit_article.html', context, request=request ) return JsonResponse(data) def form_valid(self, form): … -
Unable to fetch django view data in react component
I have just created simple django view as: def index(request): name = "Dude" return render(request, 'inventory/index.html', {'user':json.dumps(name)}) Now i need to just get "user" in reactjs. My index.js is: class App extends React.Component { render() { return ( <div> <h1>{ user }</h1> </div>); } } ReactDOM.render(<App />, document.getElementById('react-app')); In which "react-app" is Id of element in my django html template. Now, please help me, i am not getting what i need to do as i am new in reactjs. Thank You. -
Serializer object has no attribute '_writable_fields'
I have started writing an app in django with mongodb (my first time). But I'm getting this error related to my DRF-mongoengine serializer. The error reads: AttributeError: 'UserSerializer' object has no attribute '_writable_fields' Full Traceback is as follows: Traceback (most recent call last): web_1 | File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view web_1 | return view_func(*args, **kwargs) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 85, in view web_1 | return self.dispatch(request, *args, **kwargs) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 407, in dispatch web_1 | response = self.handle_exception(exc) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 404, in dispatch web_1 | response = handler(request, *args, **kwargs) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 20, in create web_1 | serializer.is_valid(raise_exception=True) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 186, in is_valid web_1 | self._validated_data = self.run_validation(self.initial_data) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 364, in run_validation web_1 | value = self.to_internal_value(data) web_1 | File "/usr/local/lib/python2.7/site-packages/rest_framework_mongoengine/serializers.py", line 197, in to_internal_value web_1 | for field in self._writable_fields: web_1 | AttributeError: 'UserSerializer' object has no attribute '_writable_fields' This seems to be some problem with the DRF-mongoengine version because when I was using 3.3.0, I had an error about no no attribute named "get_field_names". To … -
Django Create Form issue
I have a simple issue that I do not really know how t solve. I am using the Create form using model_form.html. The thing my html is within a template folder in that way : App_name>templates>model_form.html The thing is that django is looking in App_name>model_form.html not including the template folder. I get that error message : raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: website/project_form.html views.py: from django.shortcuts import render from django.views import generic from django.views.generic import TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .forms import InviteForm from invitations.models import Invitation from .models import project class ProjectCreate(CreateView): model = project fields = ['project_name'] url.py: from django.conf.urls import url from website import views app_name = 'website' urlpatterns = [ url(r'^candidateIndex/$', views.CandidateIndex.as_view(), name='candidate_index'), url(r'^HRIndex/$', views.create_invite, name='HR_index'), url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='ProjectDetails'), url(r'^project/add/$',views.ProjectCreate.as_view(), name='addproject') ] my HtML: {% extends 'base.html' %} {% block body %} <div class="jumbotron"> <h1>Welcome to SoftScores.com</h1> <h2>Team analytics platfom</h2> <h3>Welcome to {{User.username}}, it is your Page</h3> </div> <div class="container"> <div class=""> Create a new project :<a href="{% url 'website:addproject' %}"><span class="glyphicon glyphicon-plus"></span></a> </div> <p> <a class="btn btn-primary" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Create a new team </a> </p> <div class="collapse" id="collapseExample"> <div class="card card-body"> In order to create a new team please invite new members. … -
Django: How to force the loop in template to display a field only once
I'm trying to force the 'name' field in a model to display only once in a for loop in a django template. Here's my Models: class add_engineering_course(models.Model): name = models.CharField(max_length=50, default='Computer Engineering') def __str__(self): return self.name class add_engineering_course_information(models.Model): name = models.ForeignKey(add_engineering_course) university = models.ForeignKey(engineeringUni) campus = models.CharField(max_length=20, default='Campus') fees = models.IntegerField() def __str__(self): return self.name.name def university_a(self): return self.university def campus_a(self): return self.campus def fees_a(self): return str(self.fees) My Views: def abc_list(request): abc_listing = add_engineering_course_information.objects.order_by('id') return render(request, 'theproject/testing.html', {'abc_listing': abc_listing}) My Template: {% for x in abc_listing %} {{ x.name }}<br> Unviserity: {{ x.university_a }}<br> Campus: {{ x.campus_a }}<br> Fees: {{ x.fees_a }}<br><br><br> {% endfor %} The above code results in this (image). As you can see in the image, the name x.name is appearing multiple times (depending upon the entry). example: Network Engineering is appearing two times because there are two different universities added into its category. What I want is this (image). The x.name should only appear once and the rest of the things (university, campus, fees) should display as normal (multiple times depending upon how many are there). -
How can I rediredct the views with different user groups in django
This is the view which was written for my django project. if user is not None: if user.is_active: auth_login(request, user) return HttpResponseRedirect('/home/') else: messages.error(self.request, _("User is not Active")) return HttpResponseRedirect('/') else: messages.error(self.request, _("User Does not Exist")) return HttpResponseRedirect(settings.LOGIN_URL) Suppose there is 3 groups of users customer,admin and super admin. How can I redirect the views to different html for each of the user groups? Thank You -
How to save in AngularJS using set and $http.post
I have a website that takes API from Django and retrieves the data and visualizes in HTML. Now I want to save it each time I enter a website, so even if I refresh the page or close the server it won't disappear, but will be introduced to the table. This is my code for using the API to retrieve data: angular .module('inspinia') .controller('ListWebsiteCtrl', ['$scope', '$http', function ($scope, $http) { $scope.set = function (new_url) { $scope.data = new_url; $http.post("http://127.0.0.1:8000/api/website/" + this.get_url.url).success(function (data) { $scope.websites = data.websites; }); }; }]); This is my HTML: <form ng-controller="ListWebsiteCtrl"> <input title="get_url.url" ng-model="get_url.url"> <button ng-click="set(get_url.url)">INSERT WEBSITE</button> <table class="table"> <tr> <th>ID</th> <th>URL</th> <th>Status</th> </tr> <tr> <th>{{ websites.id }}</th> <th>{{ websites.url }}</th> <th>{{ websites.status }}</th> </tr> </table> </form> What is the most efficient way to do it? -
How can I add new data to exsist model?
I wanna parse excel& make dictionary and connect the model(User) which has same user_id of dictionary.I parsed excel and got lists(rows2) like ['1', 'Bob', 'America', '', '', 0.0]I wanna added this list data to User model. views.py is #coding:utf-8 from django.shortcuts import render import xlrd from .models import User book = xlrd.open_workbook('../data/excel1.xlsx') sheet = book.sheet_by_index(1) def build_employee(employee): if employee == 'leader': return 'l' if employee == 'manager': return 'm' if employee == 'others': return 'o' for row_index in range(sheet.nrows): rows = sheet.row_values(row_index) is_man = rows[4] != "" emp = build_employee(rows[5]) user = User(user_id=rows[1], name_id=rows[2], name=rows[3], age=rows[4],man=is_man,employee=emp) user.save() book2 = xlrd.open_workbook('../data/excel2.xlsx') sheet2 = book2.sheet_by_index(0) headers = sheet2.row_values(0) large_item = None data_dict = {} for row_index in range(sheet2.nrows): rows2 = sheet2.row_values(row_index) large_item = rows2[1] or large_item What should I write after this last code? models.py is down vote favorite I made area data model in models.py. #coding:utf-8 from django.db import models class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey(Area) country = models.CharField(max_length=50, choices=TYPE_CHOICES) a = models.CharField(max_length=10, choices=TYPE_CHOICES) b = models.CharField(max_length=10, choices=TYPE_CHOICES) c = models.CharField(max_length=10, choices=TYPE_CHOICES) I wanna put rows2[2] in country,rows2[3] in a,rows2[4] in b,rows2[5] in c. -
How to access foreign key of a model in a for loop
Trying to access a foreign key attribute, but I'm getting an error. Here's my code: for inbox in user_inbox: for i in inbox.post_set.all: print(i) Error: AttributeError: 'Inbox' object has no attribute 'post_set' models class Inbox(models.Model): ... text = models.CharField(max_length=200) post = models.ForeignKey(Post, blank=True, null=True) class Post(models.Model): ... title = models.TextField(max_length=95) Any idea what the right way to access the foreign key is?