Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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]: … -
Get all events of user
So currently I can login and store my refresh token(if need be I can also store the access token) in a db using Google OAuth2 while using python social auth. models.py: from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): refresh_token = models.CharField(max_length=255, default="") I have a url /calendar that needs to retrieve the Google calendar events of the currently logged user. I also have a regular login that if the user has a refresh token which means that he has linked his google account to his account. How would I use get_events to just give all of the events associated with that account. from googleapiclient.discovery import build def get_events(request): print(request.user.refresh_token) credentials = AccessTokenCredentials(get_access_token(request), scopes=SCOPES) service = build('calendar', 'v3', credentials=credentials) google_calendar_events = service.events().list(calendarId='primary', singleEvents=True, orderBy='startTime').execute() google_calendar_events = google_calendar_events.get('items', []) return google_calendar_events def get_access_token(request): social = request.user.social_auth.get(provider='google-oauth2') return social.extra_data['access_token'] views.py def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return redirect('home') else: messages.error(request,'User blocked') return redirect('login') else: messages.error(request,'username or password not correct') return redirect('login') else: form = AuthenticationForm() return render(request, 'registration/login.html',{'form':form}) -
Group by and filter by on a particular field for all data in Django ORM
I have following model: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) I have entered data like: >>> leo_tolstoy = Author.objects.create(name=”Leo Tolstoy”) >>> alexandre_dumas = Author.objects.create(name=”Alexandre Dumas”) >>> Book.objects.create(title=”War and Peace”, author=leo_tolstoy) >>> Book.objects.create(title=”Anna Karenina”, author=leo_tolstoy) >>> Book.objects.create(title=”Resurrection”, author=leo_tolstoy) >>> Book.objects.create(title=”The Three Musketeer”, author=alexandre_dumas) >>> Book.objects.create(title=”The Count of Monte Cristo”, author=alexandre_dumas) I want to print the author’s name and all the books he wrote. For all the authors we have in the database. Like this: Leo Tolstoy: “War and Peace”, “Anna Karenina”, “Resurrection” Alexandre Dumas: “The Three Musketeers”, “The Count of Monte Cristo” I want to find the best solution for it but cannot find much. Any sort of help will be appreciated, I'm quite new to this. -
why i get TemplateDoesNotExist at /accounts/login/?
I'm trying to set my authentication views in my locallibrary site and these are my codes : My projects urls.py file has these from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('catalog/', include('catalog.urls')), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ path(r'^accounts/', include('django.contrib.auth.urls')), re_path(r'^accounts/', include('django.contrib.auth.urls')), ] templates : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['./templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Pass data from JS to Python via Django
I want to send data from python to JS in Django. I successfully see the data in the response in the browser, but JS returns as . What would be the reason? trying to fetch information; def XXX(request): message_id=request.POST.get('messageid') return render(request, 'XX.html') sender; y = json.loads(response.text) ts = str(y["file"]["shares"]["public"]["XX"][0]["ts"]) return render (request, 'problemduyurusucreate.html', {'ts':ts}) JS; ... var test = "{{ ts }}"; $.ajax({ type: "POST", url: "{% url 'slack' %}", data: { "messageid": test, csrfmiddlewaretoken: '{{ csrf_token }}' } ... but I am displaying in my browser that I have successfully pulled the data -
Serialization of GeoJson with Django Rest (Different features in one collection)
How is it possible to serialize/desirialize a GeoJson with Django (GeoDjango or django-rest-gis) with multiple different type of features ( Points, Polygons, Lines) I got different models for each of the geo types, which are connected to a model named Route: class Marker(Model): route = ForeignKey(Route, on_delete=CASCADE) popup_html = TextField() point = PointField() class Meta(Model.Meta): pass class Polygon(Model): route = ForeignKey(Route, on_delete=CASCADE) polygon = PolygonField() class Meta(Model.Meta): pass class Route(Model): name = CharField(max_length=255) class Meta(Model.Meta): pass And my Serializer looks like this class RouteMarkerSerializer(GeoFeatureModelSerializer): class Meta: model = Marker geo_field = "point" class RoutePolygonSerializer(GeoFeatureModelSerializer): class Meta: model = Polygon geo_field = "polygon" And i want to get a output for the viewset something like this: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "Polygon", "coordinates": [ [ [ 8.88393, 51.038918 ], [ 9.039142, 51.085495 ], [ 9.100952, 50.945624 ], [ 8.88393, 51.038918 ] ] ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 9.066102, 51.024539 ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ 8.951007, 51.010103 ] } } ] } I dont get to figure it out, how to do this. If i'm serializing … -
Date sorting in Datatable in the format of mm/dd/yyyy
I used the Datatable plug-in in my Django project. My data is dynamic data from a working google sheet. The date format of the first column of my data is mm/dd/yyyy, which cannot be sorted properly by Datatable. I converted the date to other formats, but it still cannot be sorted properly by Datatable. I tried the following codes in my HTML file: <td data-sort='YYYYMMDD'>{{element.date}}</td> It can be sorted by the correct date sequence in this way. However, the sequence will be "fixed" and I cannot sort the date with a reverse sequence by clicking the "sorting" option -
Pass nested dictionary from views to template django
So, I'm new to Django and I'm trying to pass data from my view to a template. I've understood how to pass the classic dictionary but I now need to use a nested dictionary. For instance, I have a dictionary as below my_dictionary = {0: {'title': 'Beyond the Soul', 'id': '2Uy66My5oKcBEIW7DvVk3V'}, 1: {'title': 'The Groove Cartel Selection', 'id': '1pHtICGI68RmWEKnnP5wGr'}, 2: {'title': 'STMPD RCRDS TOP 50', 'id': '1OIzwJTbrOeZTHvUXf5yMg'}, 3: {'title': 'House Party by Axwell', 'id': '1tl4L77FJju5zp9bJC83u8'}} From my view I'm returning return render(request, 'show_playlist.html', my_dictionary ) but If I use {{ main_playlist[0] }} it gives Could not parse the remainder error Is there a way to access nested dictionary in templates? -
Django Forcing BigAutoField even though Default is set to AutoField
so I upgraded from django 3.1 to 3.2 and on two of my models when I make migrations it keeps forcing me to change the auto id to BigAutoField even though I have (and had) DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' in my settings file before I updated. operations = [ migrations.AlterField( model_name='device', name='id', field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ) What is strange is that it is only affecting a couple models, but the rest are fine and they all use AutoField as well. I am not against using BigAutoField but the migration fails because of foreignkey constraints. I have deleted the migrations in question and also scrubbed them from the applied migrations table in the database. How can I stop Django from forcing this migration? I am at a loss right now. -
django - React - Axios: Data not being saved in database
I am trying to create products through a react js component using axios post request. In django log i see an OPTION request geting a 200 status code, but data not being saved in the DB. when doing it through postman it is working fine, which makes me think the problem is in the axios request. Thanks in advanced. models.py class Product(models.Model): title = models.CharField(max_length=32) notes = models.TextField() picture = models.ImageField(upload_to='product_images', null=True, blank=True) amount = models.IntegerField(default=0) @receiver(post_save, sender='product.Transaction') def update_amount(sender, **kwargs): product = Product.objects.get(title=kwargs['instance'].product) if kwargs['instance'].transaction_type == 'IN': product.amount += kwargs['instance'].amount product.save() else: if product.amount - kwargs['instance'].amount > 0: product.amount = product.amount - kwargs['instance'].amount product.save() def __str__(self): return self.title views.py class ProductCreateView(generics.CreateAPIView): serializer_class = ProductSerilizer permission_classes = (permissions.IsAuthenticated,) queryset = Product.objects.all() serializers.py class ProductSerilizer(ModelSerializer): class Meta: model = Product fields = '__all__' settings.py ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'rest_framework', 'corsheaders', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DATETIME_FORMAT': '%d-%m-%Y', } CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_ALL_ORIGINS = True AddProducts.js import React, {useState} from 'react'; import axios from 'axios' import { useNavigate } from "react-router-dom"; function AddProduct() { const [medicineTitle, setMedicineTitle] = useState(''); … -
how to return status in Response in json using django
I am creating an app where I am calling an API but there are five conditions, but the issue is I dont want to return after each conditon rather I want 5 response varibles and return that variable afterward which ever ran, but i am getting error unhashable type: 'dict' res = Response() if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) else if: data = {} res = (data) return (res) but the issue when I add status along with each data inside the res, i am getting this above error, for now I am return five statements each with their own status, but this doesn't look, so is it possible to return status along with all those statements.