Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django receives multiple posts from the browser, Does the browser cache POSTs?
During developement it happens like this: if I am working on a piece of code to receive a POST request; Django will serve up an error page because the code is buggy. Then I fix a syntax error, refresh, a different error, fix that, repeat the process say 8 times. But on the 8th time the code works, and then Django receives and stores 8 Post entries, not just the last one! A similar behavior happens in production very occasionally. I am not sure if it is the browser caching the POSTs, then sending them all through at the same time or Django? I wrote javascript code to disable the submit button once clicked. I also check for duplicate entries (within a 5 seconds window) before saving, but it only works if one manually submits twice in quick succession, not if it auto sends a bunch of POSTs at the same time. These both are "hacks" that don't address the root cause. Any clue on how to debug or ways to attempt to solve/debug the issue? -
NameError at/ name 'Product' is not defined
I've been working on this ecommerce website and its been working perfectly but today when I ran the server it's showed me " NameError at/ name 'Product' is not defined" I've looked Into the code several times and didn't spot any error Models.py Class Product(models.Model): "" "" def __str__(self) self.name Views.py From .models import * def ShowProducts(request): items= Product.objects.all() context = {'items':items} return render(request, 'home.html', context=context) urls.py from . import views urlspatterns=[ Path ('', views.ShowProducts, name ='showproducts') ] My greatest surprise is , when I change the line, 'item= Product.objects.all()' to 'items= ()' in views.py,. It deplays the website correctly although without any product in it, please what should I do -
Joinging Query Django
class PopSummary(models.Model): available_pop = models.PositiveIntegerField(default=0) email = models.EmailField( verbose_name="email address", max_length=255, unique=True, default='' ) requested_pop = models.PositiveIntegerField(default=0) approved_pop = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) approve = models.BooleanField(default=False) popuser = models.ForeignKey(RequestPop, on_delete=models.CASCADE,related_name='popuser',null=True) def __str__(self): return "{}-{}".format(self.email,self.available_pop) Another Table: class RequestPop(models.Model): request_pop = models.PositiveIntegerField(default=0) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE,unique=False,null=True) created_at = models.DateTimeField(auto_now_add=True) available_pop = models.PositiveIntegerField(default=0) def __str__(self): return "{}-{}".format(self.user,self.request_pop) I want to make the query in inner join or other way so that: select all from RequestPop where PopSummary.approve=True I run the follwing query. queryset = RequestPop.objects.filter(popuser__approve=True).all() but it seems to be incorrect. So what should be the solution for it please. -
How to undo a path command in cmd
I am learning django and was trying to run a webapp but I mistakenly pasted "path('admin/', admin.sites.urls)" (without double quotes) and it ran automatically. Now none of the python commands are working, and I can't come out of my virtual environment. How can I revert this? Here is the command -
Django view exception logs with INFO level, not ERROR
views.py def error(request): logger.error('logger.error - test error') raise Exception('raise Exception - test error') 1st logging settings: # 1 LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'ERROR', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'ERROR' }, }, 'root': { 'handlers': ['syslog'], 'level': 'ERROR' } } 1st logs (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info <*NO log!> sudo tail /var/log/my_proj/django/syslog.error 2022-02-15T09:49:43.019832+05:00 my_proj-stage-main1 django ERROR apps.demo.views 180029 140050762920576 logger.error - test error 2nd logging settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, # True in dictConfig default 'formatters': { 'syslog': { 'format': 'django %(levelname)s %(name)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'syslog': { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'formatter': 'syslog', 'facility': 'local1', 'address': '/dev/log' }, }, 'loggers': { 'django': { 'handlers': ['syslog'], 'level': 'INFO', 'propagate': True, }, '': { 'handlers': ['syslog'], 'level': 'INFO' }, }, 'root': { 'handlers': ['syslog'], 'level': 'INFO' } } 2nd log (2 files in django dir) sudo tail /var/log/my_proj/django/syslog.info 2022-02-15T10:00:37.377018+05:00 my_proj-stage-main1 django INFO django.request 185769 140536088752768 OK: /ru/demo/error#012Traceback … -
list indices must be integers or slices, not dict in django
I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict payload: [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] views.py: @api_view(['POST']) def SaveUserResponse(request): for ran in request.data: auditorid = request.data[ran].get('AuditorId') ticketid = request.data[ran].get('TicketId') qid = request.data[ran].get('QId') answer = request.data[ran].get('Answer') sid = '0' TicketType = request.data[ran].get('TicketType') TypeSelected = request.data[ran].get('TypeSelected') agents = request.data[ran].get('Agents') supervisor = request.data[ran].get('Supervisor') Comments = request.data[ran].get('Comments') action = request.data[ran].get('Action') subfunction = request.data[ran].get('AuditSubFunction') region = request.data[ran].get('AuditRegion') cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) -
Is it possible to use complex logic in DRF ViewSet Permission Classes?
In the app I'm working on, I'd like it so that to create a task for a committee, you must be a member of the committee, the head of the committee, or an admin user, but you must also be authenticated. I understand this can be done with a few OR operators, but in the case that I need something more complex, I was hoping I could use nested lists of permission classes as such: permission_classes = [ IsAuthenticated & [ IsCommitteeHead | IsCommitteeMember | IsAdminUser ] ] Will this syntax work properly, or does rest_framework not understand this? -
Ubuntu Apache taking long time to respond and getting This site can’t be reached
Hi Guys I am trying to route my domain to server 139.5X.X.XXX Following is My DNS record Details in Hostinger :- Type Name Priority Content IP-V4 TTL A www 0 139.5X.X.XXX 600 A @ 0 139.5X.X.XXX 14400 Now I am seeing default apache page while browsing the domain (Server serving default apache page (Digital Ocean Ubuntu Droplet)) . But after configuring a Django service to domain it taking too long to respond and ending up with "This Site can't be Reached" following is the conf file which I am using <VirtualHost *:80> ServerName tellie.in ServerAlias www.tellie.in Redirect permanent / https://tellie.in/ RewriteEngine on RewriteCond %{SERVER_NAME} =tellie.in [OR] RewriteCond %{SERVER_NAME} =www.tellie.in RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> <VirtualHost *:443> ServerAdmin admin@tellie.in ServerName tellie.in ServerAlias www.tellie.in DocumentRoot /home/srv/telli ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/srv/telli/telli/static <Directory /home/srv/telli/telli/static> Options FollowSymLinks AllowOverride None Require all granted </Directory> Alias /media /home/srv/telli/telli/media <Directory /home/srv/telli/telli/media> Options FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/srv/telli/telli/telli> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess telli python-path=/home/srv/telli/telli python-home=/home/srv/telli/venv WSGIProcessGroup telli WSGIScriptAlias / /home/srv/telli/telli/telli/wsgi.py Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/tellie.in/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/tellie.in/privkey.pem </VirtualHost> Is there anything wrong that could cause the problem I am facing -
Django Subquery many values
class Category(models.Model): name = models.CharField(max_length=100) date = models.DateTimeField(auto_now=True) class Hero(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) I want Categoty model name, data, id In cookbook , I wrote the code as above. hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) It seems that only one value can be entered in hero_qs.values('name') Is it possible to get name, data, id with one annotate? -
Using ffmpeg to edit images in python
I have to use ffmpeg library in django. I have already installed ffmpeg using : pip install ffmpeg-python The following tasks are to be performed : Take an image as input which in the form of a url (eg : https://imgd.aeplcdn.com/0x0/cw/ec/30146/MercedesBenz-CClass-Right-Rear-Three-Quarter-136699.jpg?wm=0) this is an input image for me Process the image using ffmpeg to : a. remove its background b. crop 30px from bottom c. resize image size to 550 by 300 Return the processed image in form of a url. And the entire code is to be incorporated in working python(django) code. How to write this piece of code so that the above mentioned functions are performed? -
Is it possible to use Form Mixin with ListView and submit multiple values with one button?
Is it possible to use a list view in order to implement a quiz style layout? I am attempting to build a quiz app that takes a list view and ask a question after each instance of a class. The problem I am having is I cant figure out how to have my form submit and send all of my values at once in a post method. class GameListView(FormMixin,ListView): form_class = AnswerForm model = Game def get_success_url(self): return reverse('gameAPP:gameList') def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): answer = form.cleaned_data['answer'] return super().form_valid(form) #Models class Game(models.Model): player = models.ForeignKey('auth.User', on_delete=models.CASCADE) question = models.CharField(max_length=1000) correctAnswer = models.CharField(max_length=1000) def answer_onion(self): print(True) Answer.answer = True #Answer.answer.save() def answer_other(self): print(False) Answer.answer = False #Answer.answer.save() class Answer(models.Model): question = models.ForeignKey('gameAPP.Game', on_delete=models.CASCADE, related_name="games") answer = models.BooleanField(null=True) #form class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ('answer', ) #my view: {% for g in game_list %} <h1>question: {{ g.question }}</h1> <h3>correct answer: {{g.correctAnswer }} </h3> {{form}} {% endfor %} <button type="submit">Submit</button> -
How can I customize filtering in DJango Admin?
admin.py class authUserMenu(admin.ModelAdmin): list_display = ["__str__", "user_id", "menu_id","is_active"] class Meta: Model = AuthUserMenu admin.site.register(AuthUserMenu, authUserMenu) models.py class AuthUserMenu(models.Model): # USER VS MENU relation user = models.ForeignKey(AuthUser,on_delete=models.DO_NOTHING,blank=True, null=True) menu = models.ForeignKey(Menu,on_delete=models.DO_NOTHING,blank=True, null=True) is_active = models.BooleanField(default=False) class Meta: db_table = 'auth_user_menu' ordering = ['user','menu','is_active'] def __str__(self): # return self.id return str([self.user.username,'>>>>>>', self.menu.menu_name]) In my Django admin panel When filtering with username should only show some menus under some condition... How can I achieve this? Suppose here for the username 4 menu is showing. But it should show 2 menu. This may obtain by db querying. -
What is the efficient way: run the same function on Server-Side or on Client-Side
I am currently coding a web application using Django (4.0) with Django REST Framework for Server-Side Python scripts and NextJS for Client-Side Javascript. I have a function implemented in Python that helps to upload an image to IPFS and returns an image URI in order to display the image on the web page. Besides that, I have also a Javascript code that does exactly the same but on the Client-Side. What's the efficient way as for the speed and energy consumption to run that function: whether on Client-Side in the browser with JS or better to do this on the Server-Side and return the value through HTTP with DRF? Note: Client and server are on the same network. -
Is possible paginate multiple arrays with templateView in different contexts?
I am working on a view with 2 tabs, in each tab a different list should be displayed. Here's an example of views.py file. '''python3 class IndexView(LoginRequiredMixin, TemplateView): template_name = 'index.html' login_url = reverse_lazy('login') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.today() start_week = today - timedelta(today.weekday()) end_week = start_week + timedelta(7) context['dayli_expirations'] = Member.objects.filter( expiration_date__day=today.day, expiration_date__month=today.month, expiration_date__year=today.year ) context['weekly_expirations'] = Member.objects.filter(expiration_date__range=[start_week, end_week]) return context ''' -
Django orm Subquery model object
Cookbook link Cookbook said that if you do the above, you can bring the value. hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) I want the object of the Hero model. -
SQL cleaning function in python
So I have a message field on a form and I want to save the message into a database column named help_desk_message. I know that Django already tries to handle sql injection for you but I want to do a bit more. I want to clean my help_desk_message in my Views.py before saving it to the database by sending it to a function. so I would pass my message into a function sql_message_cleaner(help_desk_message). I need help with the function that cleans out the sql injection. I tried writing it but it failed. I need the function in Python -
Django explanation of HyperLinkedSerializer URL Lookups
I am relatively new to Django Rest Framework and have just spent an hour figuring out how HyperlinkedSerializer class matches URLs. This unfortunately left me more confused than anything. I am using DRF nested routers and the definition for both serializers and routers is below # serializers.py class RecordingFolderSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RecordingFolder fields = [...] # urls.py from rest_framework_nested import routers from my_app import views # ... router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) # Somehow fixes the error shown below: router.register('folders', views.RecordingFolderViewSet) # WHY DOES THIS FIX MY ISSUE! recording_router = routers.NestedSimpleRouter(router, r'users', lookup='user') # Original version which caused the error before I added the folder view to the base router recording_router.register('folders', views.RecordingFolderViewSet, basename='user-folders') urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(router.urls)), path(r'', include(recording_router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] Not having the line that attaches the folder to the base router produces this error when I try and go to users/id/folders/folder_id: Could not resolve URL for hyperlinked relationship using view name "recordingfolder-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. My questions are twofold: First, if I have one specific view on users, such as users/id/profile … -
no such file libmariadb.3.dylib error when importing MySQLdb on mac M1
I migrated my data to M1 Monterey MacOS from intel macmini. I was happy to use django and mariadb until I installed a package using homebrew. I installed homebrew and installed vim with it, and then my django-mariadb connection suddenly stopped working. I found out that the error was caused in python3.7/site-packages/MySQLdb/init.py in 18th line in my venv. try: from MySQLdb.release import version_info from . import _mysql # this line causes the problem assert version_info == _mysql.version_info except Exception: raise ImportError( "this is MySQLdb version {}, but _mysql is version {!r}\n_mysql: {!r}".format( version_info, _mysql.version_info, _mysql.__file__ ) ) And the stacktrace goes Traceback (most recent call last): File "/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 0x0002): Library not loaded: /usr/local/opt/mariadb/lib/libmariadb.3.dylib Referenced from: /Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: tried: '/usr/local/opt/mariadb/lib/libmariadb.3.dylib' (no such file), '/usr/lib/libmariadb.3.dylib' (no such file) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/gwanghyeongim/Documents/revhat/basecamp/.venv/basecamp/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined I had written a post about _mysql not defined some time ago, and I fixed the problem by exporting a path in my ~/.zshrc. But this time I googled … -
How to apply for loop in Django's views.py
[research/models.py] RECRUITING_CHOICES = [ ('Recruiting', 'Recruiting'), ('Not yet recruiting', 'Not yet recruiting'), ('Completed', 'Completed'), ('Holding', 'Holding'), ] RECRUITING_CHOICES_INV = {val: val for val, _ in RECRUITING_CHOICES} class Research(models.Model): is_deleted = models.BooleanField(default=False) is_recruiting = models.CharField(choices=RECRUITING_CHOICES, null=True, max_length=50) research_name = models.CharField(max_length=2000, null=True) teacher= models.CharField(max_length=2000, null=True) I'm using Django, and I'm trying to create a list for generating apexchart (graph) in views.py using a class model 'Research'. I am trying to add each of the 4 values of the is_recruiting field to filtering , but adding Recruiting and Not yet Recruiting just takes multiple lines and makes the code look inefficient. Is there a workaround using the for statement? [research/views.py] counts = Research.objects.values('teacher') \ .annotate(A=Count('id', filter=Q(type='A')), B=Count('id', filter=Q(type='B')), C=Count('id', filter=Q(type='C')), D=Count('id', filter=Q(type='D')), E=Count('id', filter=Q(type='E')), F=Count('id', filter=Q(type='F')), r_A=Count('id', filter=Q(type='A', **is_recruiting='Recruiting'**)), r_B=Count('id', filter=Q(type='B', **is_recruiting='Recruiting'**)), r_C=Count('id', filter=Q(type='C', **is_recruiting='Recruiting'**)), r_D=Count('id', filter=Q(type='D', **is_recruiting='Recruiting'**)), r_E=Count('id', filter=Q(type='E', **is_recruiting='Recruiting'**)), r_F=Count('id', filter=Q(type='F', **is_recruiting='Recruiting'**)), N_A=Count('id', filter=Q(type='A', **is_recruiting='Not yet recruiting'**)), N_B=Count('id', filter=Q(type='B', **is_recruiting='Not yet recruiting'**)), N_C=Count('id', filter=Q(type='C', **is_recruiting='Not yet recruiting'**)), N_D=Count('id', filter=Q(type='D', **is_recruiting='Not yet recruiting'**)), N_E=Count('id', filter=Q(type='E', **is_recruiting='Not yet recruiting'**)), N_F=Count('id', filter=Q(type='F', **is_recruiting='Not yet recruiting'**))) \ .values('teacher', 'A', 'B', 'C', 'D', 'E', 'F', 'r_A', 'r_B', 'r_C', 'r_D', 'r_E', 'r_F', 'N_A', 'N_B', 'N_C', 'N_D', 'N_E', 'N_F') -
Django AbstractModel Inheritance and migrations
Want to clarify my understanding of Django abstract model inheritance and migrations since I've had difficulty finding clear documentation on this. Say I've got a package pckg.app.models defining an AbstractModel: class AbstractObj(models.Model): name = CharField(max_length=100) class Meta: verbose_name = _("Obj") abstract = True def __str__(self): return str(self.label) It is possible to change the name field via inheritance? Or could that package be imported so the 'name' field can be migrated and changed? In my app's models.py, if I import and subclass it: from pckg.app.models import Obj Class NewObj(Obj): name = CharField(max_length=200) def __str__(self): return self.label this would create a migration such as: from __future__ import unicode_literals from django.db import migrations, models from forms_builder.forms import fields import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('foo', 'bar'), ] operations = [ migrations.CreateModel( name='NewObj', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=200)), ], ), ] but this won't work because NewObj is an instance of Obj, not Obj: django.core.exceptions.FieldError: Local field 'name' in class 'NewObj' clashes with field of the same name from base class 'Obj' is there a way to migrate or change AbstractObj without defining it within my Django app and creating the dedicated … -
Django - How to get self.id instance when creating new object
I am working with two classes, when i save the first one it will automatic create the other one, the field called "transaction" should be filled by self.id. But i get this error message: NOT NULL constraint failed: portfolios_portfoliotoken.transaction_id this is the code that i am using: PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl+last.total_today_brl, order_value=self.total_cost_brl) More details is possible to see below: class Transaction(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(("Date"), default=date.today) portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) total_cost_brl = models.FloatField(editable=False) ... def save(self, *args, **kwargs): self.share_cost_brl = round(self.share_cost_brl, 2) self.total_cost_brl = round(self.shares_amount * self.share_cost_brl, 2) ... PortfolioToken.objects.create(transaction=self.id, portfolio=self.portfolio, date=self.date, total_today_brl=self.total_cost_brl+last.total_today_brl, order_value=self.total_cost_brl) super(Transaction, self).save(*args, **kwargs) class PortfolioToken(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) total_today_brl = models.FloatField() order_value = models.FloatField() date = models.DateField(("Date"), default=date.today) ... -
How can I add a mimetype?
I am building a web app that allows users to upload files. I wanted to restrict the mimetype so users can only upload audio files. However, the site cannot accept .amr files. How can I add amr files? ''' if form.is_valid(): #validate file file = request.FILES['file'] valid_mime_types = ['audio/AMR','audio/amr-wb+','audio/mpeg','video/mp4','audio/AMR-WB','audio/amr','Audio/Amr',] file_mime_type = magic.from_buffer(file.read(1024), mime=True) if file_mime_type not in valid_mime_types: raise ValidationError('Unsupported file type.') valid_file_extensions = ['.amr','.mp4','.AMR','.mp3'] ext = os.path.splitext(file.name)[1] if ext.lower() not in valid_file_extensions: raise ValidationError('Unacceptable file extension.') #save the file instance = MyModel(upload=request.FILES['file']) instance.save() return HttpResponseRedirect('/somewhere/') ''' Other file types work fine, but this isn't working. -
How to add choice field in UserCreationForm
I am trying to ask (with the forms.Select maybe) whether the user is a Korean student or an international student when the user is registering. I have tried other answers to similar questions but did not work well. Maybe it is because of the User class definition. How do I add it? This is how my User class is defined: from .models import User Choices = (('I', "International"), ('K', "Korean")) User.add_to_class('scheduleData',models.ManyToManyField(UserSelect, blank=True)) User.add_to_class('lang',models.CharField(max_length=2, default="EN")) User.add_to_class('you_are',models.CharField(max_length=1, choices=Choices, default=False)) And this is how my NewUserForm is defined: (It shows "You are:" with nothing on the right side in the page) class NewUserForm(UserCreationForm): Choices = (('I', "International"), ('K', "Korean")) widgets = {"you_are": forms.CharField(widget=forms.Select(choices=Choices), max_length=2)} class Meta: model = User fields = ("username", "password1", "password2", "you_are") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) if commit: if user.you_are == "K": user.lang = "KR" user.save() return user Thank you in advance. -
How to specify a template for a Snippet in a StreamField when using SnippetChooserBlock
I want to use a snippet in a StreamField: @register_snippet class Advert(models.Model): url = models.URLField(null=True, blank=True) text = models.CharField(max_length=255) def __str__(self): return self.text class MyPage(Page): body = StreamField([('Snippet', SnippetChooserBlock( target_model='web.Advert')]) my_page.html: {% for block in page.body %} {% include_block block %} {% endfor %} However, when rendering the Advert it renders only the str representation of self.text. How can I specify a template layout for the snippet block, e.g. like a StructBlock? There is no documentation for SnippetChooserBlock. -
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. Heroku
I am trying to set up my Django project on Heroku. It's my first time doing so. When deploying it succeeds but when opening up the view I get this message: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. (full traceback below). I am using Heroku Postgres and Heroku Redis add-ons. What am I doing wrong? Procfile release: python manage.py migrate web: daphne test_cs.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channels --settings=test_cs.settings -v2 runtime.txt python-3.10.2 asgy.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import main.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_cs.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( main.routing.websocket_urlpatterns ) ) }) Full traceback 2022-02-14T22:14:52.566118+00:00 heroku[release.1702]: State changed from starting to up 2022-02-14T22:14:55.258559+00:00 app[release.1702]: Operations to perform: 2022-02-14T22:14:55.258595+00:00 app[release.1702]: Apply all migrations: admin, auth, contenttypes, main, sessions, social_django 2022-02-14T22:14:55.283487+00:00 app[release.1702]: Running migrations: 2022-02-14T22:14:55.283489+00:00 app[release.1702]: No migrations to apply. 2022-02-14T22:14:55.877375+00:00 heroku[release.1702]: Process exited with status 0 2022-02-14T22:14:55.963114+00:00 heroku[release.1702]: State changed from up to complete 2022-02-14T22:14:59.550199+00:00 heroku[web.1]: State changed from crashed to starting 2022-02-14T22:15:05.339497+00:00 heroku[web.1]: Starting process with command `daphne test_cs.asgi:application --port 47797 --bind 0.0.0.0 -v2` 2022-02-14T22:15:06.845859+00:00 app[web.1]: Traceback (most recent call last): 2022-02-14T22:15:06.845875+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2022-02-14T22:15:06.845948+00:00 app[web.1]: …