Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to fix error DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Please help resolving this env issue/error. I did found many posts about resolving that error but I still couldn't fix mine. I guess I am just unable to understand it in the right way. django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have just one app in my Django project, had created using django-admin startproject. The app is added to settings.py under INSTALLED_APPS, and all other settings are set to default by Django itself which i haven't modified. I have few def in views.py working on models/forms, and those are working well. I also have created a new folder (myscripts) in the project (next to the app-name folder), and in that myscripts folder i have my other py scripts (other than models/forms). Executing those scripts works, I am able to import those models/forms, it does some work and adds a new entry in django db sqlite3 correctly. Further, i want to add/update execution status to the db entry (for a given pk/id) after my other scripts finishes its work. To achieve that, I am trying a new py script which will import models to … -
Syntax Error when migrating django server
I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something. I tried asking the original developer but he is busy with other stuff so haven't gotten a reply but as I have to get the project going, I'll try asking here. The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the modules. The code used in this project can be found here: https://github.com/HumanDynamics/openbadge-server Also the main … -
TemplateDoesNotExists Django doesn't find existing template
I'm getting the following error: This is my project structure: urls.py code: from django.contrib import admin from django.urls import path from core import views as core_views from portfolio import views as portfolio_views from django.conf import settings urlpatterns = [ path('', core_views.home, name='home'), path('about-me/', core_views.about, name='about'), path('portfolio/', portfolio_views.portfolio, name='portfolio'), path('contact/', core_views.contact, name='contact'), path('admin/', admin.site.urls), ] /project/views.py code: from django.shortcuts import render # Create your views here. def portfolio(request): return render(request, 'portfolio/portfolio.html') There are no migrations to apply, and I already restarted the server. -
Django Project - Online / Offline - Github
I just startet developing with Django / Python. Please be indulgent with me as I am just starting to become a developer :) .. Here is my question. I am using a linux shared hoster with cpanel, actually I am developing on my notebook. Now I would like to know how to work offline and beeing able to push it online. I recently read that there is a way to do that with github. Is this possible and what would be recommendable. Also is there any website offering django projects/templates which can be used which for example also provide already a login area etc.? Many thanks in advanced for any answer. -
Populate media asset files using something like `collectstatic`
How can I use Django's collectstatic to populate “media” (model-managed) asset files? I have a Django app that is using the “media” files support – files managed and associated with Model fields – for assets like product images and icons for specific instances. These (for some fields) need to be populated when the application is deployed; this means collecting the files from various locations and providing them where the “media” storage expects to find them. The web app already successfully serves these “media” files once they are collected. The correct configurations are working. But every time the site is deployed, the media files need to be collected together from the app-model locations that make sense for development, into the central directory tree (MEDIA_ROOT) where the files storage expects them to be served from. This task is very closely implemented by the tool collectstatic, for deploying “static” files (files that are intended not to be associated specifically with any model, but with the site as a whole and served outside the context of model permissions). How can I make use of collectstatic (or its implementation) to collect “media” asset files for deployment? -
Assigning subjects to a student
i am working on a student managment system project and i have a student,subject ,term and class models and i want to assign the subject objects to the student according tom the current term and class class Subject(models.Model): """ Subject """ name = models.CharField(max_length=200) term = models.ForeignKey(AcademicTerm,on_delete=models.CASCADE,related_name="subject-term",null=True,blank=True) student_class = models.ForeignKey('StudentClass',on_delete=models.CASCADE,related_name="subject-class",null=True,blank=True) staff_id = models.ForeignKey(CustomUser,on_delete=models.CASCADE,null=True,blank=True) class AcademicTerm(models.Model): """ Academic Term """ name = models.CharField(max_length=20, unique=True) current = models.BooleanField(default=False, null=True) class StudentClass(models.Model): name = models.CharField(max_length=200, unique=True) term = models.ForeignKey(AcademicTerm,on_delete=models.CASCADE,null=True,blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile',null=True,blank=True) group = models.ForeignKey(Group,related_name='student_group',on_delete=models.CASCADE,null=True) teacher = models.ManyToManyField(Teacher,related_name="student_teacher", blank=True) parent = models.ForeignKey('Parent',related_name="parent_sons",on_delete=models.CASCADE,null=True,blank=True) current_class = models.ForeignKey(StudentClass, on_delete=models.SET_NULL, related_name="student_class", null=True) current_term = models.ForeignKey(AcademicTerm, on_delete=models.SET_NULL, related_name="student_term", null=True) session_year = models.ForeignKey(AcademicSession, on_delete=models.CASCADE, related_name="student_seccion", null=True) subjects = models.ManyToManyField(Subject,related_name="student_subject") def subjects(self): term = AcademicTerm.objects.get(current=True) subs = Subject.objects.select_related('term').filter(term=term,student_class=self.current_class) for sub in subs: self.subjects = sub def save(self,*args,**kwargs): self.subjects() session = AcademicSession.objects.get(current=True) self.session_year=session parent = Parent.objects.filter(nationalId=self.parent_NationalId) if parent: self.parent = parent.get() return super(Student,self).save(*args,**kwargs) is creating the subjects method and calling it in the save method wright? or what? -
can I get the name of admin who updated the record in django?
I am new to Django and I am trying to make an application and I am stuck with this. I would like to get the name of the admin who updated the record and add save it. is that possible. Please help. Thanks in advance. -
Render radio values using Django BoundField
Hi I want to return form radio values as a JSON from my view. I don't want the html tags, just raw data of radio values. This is my views.py code: def FormBotAPI(request): form = UserForm(request.POST or None) if request.method == 'POST': if form.is_valid(): instance = form.save() context = { 'form': form } for x in form.fields: data = { 'label_str': form[x].label, 'values': str(form[x]), } return JsonResponse(data, safe=False) forms.py: class UserForm(ModelForm): class Meta: model = User fields = '__all__' -
Using related models with conditional expression
Goal: use a related model attribute as a filter inside a conditional expression for an annotation. I'm currently adding some functionality to an old Django app, this app has some design issues and i have nothing to do with it. After some research I found conditional expressions, this is great and what I needed. However I'm not being able to make it. Let's have model A, model B and model C. class ModelA(models.Model): name=models.Charfield() reference=models.ForeignKey('app.ModelB') class ModelB(models.Model): name=models.Charfield() class ModelC(models.Model): name=models.Charfield() reference=models.ForeignKey('app.ModelB', related_name='some_reference') bool_field=models.BooleanField() And this is what I would like to do: ModelA.objects.all().annotate(some_field=When(Q(reference__some_reference__bool_field=True), then=F('reference_some_reference_name'))) This should work since it is being interpreted by python, but I get some Syntax Error from MySQL. What am i doing wrong? Is this even possible? This is what I'm getting: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN `ParametrosPreciosProveedor`.`already_iva` = 1 THEN `ParametrosPreciosProve' at line 1") 'ParametrosPreciosProveedor' is ModelC in this example and 'already_iva' is bool_field. -
Django upload FileField and ImageField in differnt servers
I want to make a system where user can upload document files and also images (both for different tasks) and i want to store the files in my own ftp server and images in s3 bucket. never saw a django approach like this, where FileField and ImageFields can be uploaded to different servers for example, let's say when user uploads a file the file gets uploaded to my ftp server FTP_USER = 'testuser'#os.environ['FTP_USER'] FTP_PASS = 'testpassword'#os.environ['FTP_PASS'] FTP_PORT = '21'#os.environ['FTP_PORT'] DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' FTP_STORAGE_LOCATION = 'ftp://' + FTP_USER + ':' + FTP_PASS + '@192.168.0.200:' + FTP_PORT # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static_my_proj"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn", "static_root") MEDIA_URL = 'ftp://192.168.0.200/' MEDIA_ROOT = 'ftp://192.168.0.200/'#os.path.join(BASE_DIR, "static_cdn", "media_root") but problem is images now goto ftp server also because of this DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage' yeah i know i can make different directories inside uploaded server root directory like this def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): # print(instance) #print(filename) new_filename = random.randint(1,3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "myapp/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename ) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) document = … -
Django URL template prepending last url in urls.py erroneously
As the title states, the {% url 'urlName' %} is evaluating to a url that includes extra information prepended. urls.py urlpatterns = [ path('admin/', admin.site.urls), path('logout', include('dashboard.urls')), path('signout/<int:id>/<int:payment>/', include('dashboard.urls')), path('shifts-in-range', include('dashboard.urls')), path('charts', include('dashboard.urls')), ] and in the appname/urls.py we have a very similar view: urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='index.html'), name='login'), path('signout/<int:id>/<int:payment>/',signout, name='signout'), path('shifts-in-range',shiftsInRange,name='shifts-in-range'), path('charts', charts, name='charts'), ] When using this statement: var signoutURL = "{% url 'signout' 0 2 %}"; it evaluates to the url chartssignout/0/2/ for some reason the last path in urls.py urlpatterns is being prepended to the evaluated url. switching the order of the urlpatterns makes it evaluate with the new last pattern as well. What is the cause of this and how can I prevent it from happening? it is also worth noting that when I hardcode the url signout/0/2/, it does not function correctly and redirects to the root "/". -
Reduce the headache on database when using ModelChoiceField
please I need your help how to reduce the database call when using ModelChoiceField a it requires queryset and I have to use it three times separately with a model that is recursively foreign key on itself, the code is below: ModelForm code in the init function self.fields['category'] = forms.ModelChoiceField(queryset=queryset) self.fields['sub_category'] = forms.ModelChoiceField(queryset=) self.fields['product_type'] = forms.ModelChoiceField(queryset=) the model class: class Category(ProjectBaseModel, AuditLogMixin): parent_id = models.ForeignKey('self', related_name='children', blank=True, null=True, on_delete=models.CASCADE,verbose_name=_('Parent')) what i tried to do is collect all ids of the desired categories in array and make only one filter queryset with them like the following: category = auction.category sub_category = category.parent_id product_type = sub_category.parent_id ids= [category.id,sub_category.id,product_type.id] queryset = Category.objects.filter(id__in=ids) but to proceed on that solution -
Django Class Based UpdateView does not make any changes/Update the model it is called on
I have just started learning Django and was trying to create a simple blog website, but for some reason, I am unable to update my blog though UpdateView. Every time I hit the submit button from the update blog page, it takes me back to the detail view page without making any changes. Apart from UpdateView, rest seems to work fine like CreateView, DeleteView, ListView. Here is the code for views.py- def Category_Count(): catagories = Post.objects.values('Categories__title').annotate(Count('Categories__title')) return categories def index(request): post = Post.objects.filter(featured=True).order_by('-date_added') latest=Post.objects.order_by('-date_added')[0:3] context={'object':post,'latest':latest} return render(request,'posts/index.html',context) def Search(request): q_set1 = Post.objects.all() q_set2 = User.objects.all() query = request.GET.get('q') if query: result = q_set1.filter( Q(title__icontains = query) | Q(Content__icontains = query) ).distinct() else: result = '' context={'result':result} return render(request, 'posts/Search.html',context) class BlogListView(ListView): model = Post template_name = 'posts/blog.html' ordering=['-date_added'] def get_context_data(self, *args, **kwargs): CatCount = Category_Count() context = super(BlogListView, self).get_context_data(*args, **kwargs) context['latest'] = Post.objects.order_by('-date_added')[0:3] context['Category_Count'] = CatCount return context class PostDetailView(DetailView): model = Post template_name = 'posts/post.html' context_object_name = 'obj' form = CommentForm def get_object(self): obj = super().get_object() if self.request.user.is_authenticated: PostView.objects.get_or_create(user=self.request.user,post=obj) return obj def get_context_data(self, *args, **kwargs): CatCount = Category_Count() context = super().get_context_data(*args, **kwargs) context['latest'] = Post.objects.order_by('-date_added')[0:3] context['Category_Count'] = CatCount context['form'] = self.form return context def post(self, request, *args, **kwargs): form … -
Django View Problem. Filtered Tickets Are Not Appearing
I'm currently working on a project in Django that is a "bug tracker" or "ticket tracker" as some might call it. The goal here is to create a post or "ticket" that details a bug in the website or software for a development team. Each "ticket" has general information like name, summary, etc. but also has a "category" for the software languages or bug type(Think like categories for a blog). Every ticket also has a "priority", that is developed in a similar way as to the categories, based on the severity of the bug that a reporter encounters. I have already developed a way to click on a category name and view a list of tickets within the same category. This is successful and it works great! Naturally, my next step in the process is to use that same method of implementing ticket priorities. My goal is to be able to click on a priority and see a filtered view of all "severe" tickets with that priority, just like how my categories are set up. Here is my problem: When I click on a priority (low, medium, high, & severe), it will take me to my ticket_priority.html template for that … -
Creating multiple model objects in a single form
I have a multiple choice personality quiz that I am building in Django. The questions are pre-existing in a database, and the template loops through to display them. I've separated the Question and Response models, and I don't want to use {{form.as_p}} at all in my template. My relevant models are as follows: class Question(models.Model): question_text = models.CharField(max_length=100) question_number = models.CharField(max_length=4, unique=True) def __str__(self): return f'{self.question_number}' class Response(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='response') value = models.FloatField(max_length=5, default='0.0', choices = CHOICES) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='response') As this is a personality quiz, I found it easier to get my desired results by separating the Questions and Responses. My template handling the form looks like this: {% for question in questions %} <form role="form" method="POST" autocomplete="off" class="responseForm"> {% csrf_token %} <div class="col "> <table style="border-radius: 21px;"> <p style="font-weight: 500;" class="question-text">{{ question.question_text }} </p> <tr class="bubbles"> <td class="bubble-text-left">Not interested&nbsp;</td> <td> <label class="container"> <input type="radio" name="value" value="0"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="25"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="50"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="75"> <span class="checkmark"></span> </label> </td> <td> <label class="container"> <input type="radio" name="value" value="100"> <span class="checkmark"></span> </label> … -
error when i migrate ValueError: Related model 'main.user' cannot be resolved
So i was creating a custom django user model with AbstractBaseUser and an custom account manager with BaseUserManager , here is my code in models.py class MyAccountManager(BaseUserManager): def create_user(self, email,password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=250, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True and this on my settings.py AUTH_USER_MODEL = 'main.User' and when i do "python3 manage.py migrate" this error appears: ValueError: Related model 'main.user' cannot be resolved -
Django JSignature Not Showing Signature Input
Hi I'm trying to include django jSignature into my project. I have followed all the necessary setup steps according to the pypi. My issue is that the jSignature input is not displaying in my template when it's rendered. I can see that I'm getting an error in the javascript, but I have NO CLUE how to fix that. I don't even have the particular js file saved locally on my computer. I can see why there is an error because something in the js file is not code, but I am only loading that script through {{form.media}} it is nowhere in my local directory. Here is my code and the error: ERROR sign.html <html> <head> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> {{form.media}} <form> {{form}} </form> </body> </html> models.py class Sign(models.Model): sign = JSignatureField() forms.py class SignForm(forms.ModelForm): class Meta: model = Sign urls.py url(r'sign/$', SignView, name='SignView'), views.py def SignView(request): if request.method=='POST': print('post') form = SignForm() context = { 'form': form, } return render(request, 'sign.html', context) fields=('sign',) -
Unit testing Django model with an image - Not quite understanding SimpleUploadedFile
I'm a testing noob and I'm trying to figure out how to write a test to confirm that a model form is valid and will generate a new instance of Post, which is a model that has an image field. I looked some other SO posts, and it looks like I should be using SimpleUploadedFile to mock the image field. I'm having a hard time understanding how SimpleUploadedFile works (haven't found any straightforward documentation for this application), and different SO posts use some different looking syntax. Am I supposed to point to a real file path to an actual image that is held somewhere in my Django app, or does this create a fake file to be used? tests.py class CreatePost(TestCase): def test_create_post(self): data = { "content": "This is a post, I'm testing it out" } files_data = { "image": SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg') } response = self.client.post("/new", data=data, files=files_data) self.assertEqual(Post.objects.count(),1) self.assertRedirects(response, 'index') models.py class Post(models.Model): content = models.CharField(max_length=260) timestamp = models.DateTimeField(auto_now_add=True) posted_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") liked_by = models.ManyToManyField(User, blank=True, related_name="liked_posts") image = models.ImageField(upload_to='uploads/', verbose_name='image') def __str__(self): return f"{self.posted_by} posted {self.content} at {self.timestamp}" def is_valid_post(self): return len(self.content) <= 260 and len(self.content) >= 0 class Post_form(ModelForm): class Meta: model = … -
Getting Django server to subscribe to another Django server with Channels WebSockets
I am trying to work out how I can get Django Server B(IOT device) to subscribe to Django Server A (cloud) using Channels WebSockets. This is so that I can pass data async between them. Server B will be on an IOT device and Server A will be cloud-based. I've been looking everywhere, but most of the online tutorials and documentation seems to be based on subscribing(client-side) with Javascript. Surely there must be a way to subscribe with Python! Most of the online tutorials seem to be for chat apps too. It would be great if someone could help please. I'm sure there are other people looking for this same answer too. Thank you :) -
how to use alertify js with django
hi i need to use alert message when some wants delete a post ask her/him to delete or cancel i tried this but this is a default alert browser <button onclick="return confirm('are you sure you want to delete {{obj.title}}')" class="bt mx-auto"><a href="{% url 'posts:post-detail' obj.id %}"><img src="{% static 'icons/delete.svg' %}" alt=""></a></button> i want to use this alert alertify.prompt("are you sure you want to delete ", "{{obj.title}}", function(evt, value ){ alertify.success('Ok: ' + value); }, function(){ alertify.error('Cancel'); }); but i'm not sure where should i put that script in the template ? i use it inside the button to delete replacing to confirm() but seems doesnt work thanks for helping .. -
How to do connection/ migrations between different MySQL databases and Different Django App's?
I am new to Django, would be great if you could help me or correct me. please let me know what mistakes i am making. can someone give me an example with at least 2 apps and 2 Databases. I have 3 apps cherry, apple and mango in my Django project. For every app there is "models_cherry.py, models_apple.py and models_mango.py". I have created 3 databases in MySQL workbench DBtable1, DBtable2 and DBtable3. Connection between Django project and MySQL is already done. When i fires following queries on windows PowerShell for migrations, **it should create tables in the databases. python manage.py makemigrations 2) python manage.py migrate** The above command create tables for only one model for one database. My Question is, i want to create tables for all the models for all respective databases. i.e. For classes in file models_cherry.py into database DBtable1, for classes in file models_apple.py into DBtable2 and for classes in models_mango.py into DBtable3? Here are some screenshots of settings.py and routers file: settings.py core_router.py man_router.py -
OSError: no library called "cairo" was found. django anaconda environment problem
File "", line 219, in call_with_frames_removed File "C:\Users\Mamun Khan\Desktop\Python Practice\my_django_stuff\myshop\orders\urls.py", line 2, in from . import views File "C:\Users\Mamun Khan\Desktop\Python Practice\my_django_stuff\myshop\orders\views.py", line 12, in import weasyprint File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint_init.py", line 375, in from .css import preprocess_stylesheet # noqa File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\css_init_.py", line 29, in from . import computed_values File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\css\computed_values.py", line 16, in from .. import text File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\weasyprint\text.py", line 18, in import cairocffi as cairo File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\cairocffi_init_.py", line 50, in ('libcairo.so', 'libcairo.2.dylib', 'libcairo-2.dll')) File "E:\AnacondaNew\envs\MydjangoEnv\lib\site-packages\cairocffi_init_.py", line 45, in dlopen raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found cannot load library 'C:\msys64\mingw32\bin\libcairo-2.dll': error 0xc1 cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0xc1 I follow every instruction also set the path, but i faced this problem again and again. Please help me to solve this issue. -
Django Model Not Saving All Data From Form
I currently have a Django form that saves data from a questionnaire against a user, where a user is stored as a Foreign Key from the Person model. I can successfully find the person from the Person class using get_object_or_404(), but when I try to save(commit=True), the data is not being saved in the database. See below for my code: # models.py class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254, primary_key=True) tel_number = models.CharField(max_length=13, blank=True) referral_code = models.UUIDField() class Meta: verbose_name_plural = 'People' def __str__(self): return str(self.referral_code) class Questionnaire(models.Model): user = models.ForeignKey(Person, related_name='questionnaire_person', on_delete=models.CASCADE) ... and some questionnaire questions here (CharFields and TextFields) ... # views.py def index_questionnaire(request): template = 'questionnaire.html' # load blank instance of template questionnaire = UserQuestionnaire() context = { "questionnaire": questionnaire } # if user has submitted something, check form is valid if request.method == 'POST': answers = UserQuestionnaire(data=request.POST) if answers.is_valid(): # submission is genuine so save as new entry to database # get user's unique referral ID from URL user_referral_id = request.GET.get('user') # check legit person try: answers.save(commit=False) answers.person = get_object_or_404(Person, referral_code=user_referral_id) print('user found: {}'.format(answers.person)) answers.save(commit=True) print('Questionnaire saved') except: print("user not found") return render( request, template, context ) #forms.py class UserQuestionnaire(forms.ModelForm): class … -
Iterate over ManyToMany field Django
I am having some problems with iterating over a ManyToMany field. I want to have a Post and Tag model, and have the Post model extend the Tag model in the form of a ManyToMany relation. Below are both my Tag and Post models. class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return f"{self.name}" class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = RichTextField() timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True,default="",max_length=1000) tag = models.ManyToManyField(Tag,related_name='tags',blank=True) # .... other non related functions However, when I am in the Django shell, I can't seem to loop over these tags, despite the object having tags associated to it. For example, I would do post1 = Post.objects.all()[0], and then post1.tag.name.all(), however it would give me an error saying "AttributeError: 'NoneType' object has no attribute 'all' Everything else I have tried failed. What can I fix to solve the issue? Thank you in advance -
Django App ASGI server developement mode error
I am trying to add async views to an existing Django app by updating the Django to 3.1. I tried uvicorn and daphne to run the django app, but getting the error below. But when I create a new Django app it runs fine. 2020-08-18 19:09:21,151 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2020-08-18 19:09:21,151 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2020-08-18 19:09:21,151 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2020-08-18 19:09:21,152 INFO Listening on TCP address 127.0.0.1:8000 2020-08-18 19:09:27,164 ERROR Exception inside application: request_started_handler() missing 1 required positional argument: 'environ' Traceback (most recent call last): File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/daphne/cli.py", line 30, in asgi await self.app(scope, receive, send) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 154, in __call__ await sync_to_async(signals.request_started.send, thread_sensitive=True)(sender=self.__class__, scope=scope) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/asgiref/sync.py", line 296, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/asgiref/sync.py", line 334, in thread_handler return func(*args, **kwargs) File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 177, in send return [ File "/Users/xxxxxx/virtualenvs/oath_tools/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 178, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) TypeError: request_started_handler() missing 1 required positional argument: 'environ' 127.0.0.1:58558 - - [18/Aug/2020:19:09:27] "GET /" 500 453