Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CreateView: How to create the resource before rendering the form
I have a model class for my resource, class Article(db.Model): title = models.CharField(_('title'), max_length=255, blank=False) slug = AutoSlugField(_('slug'), populate_from='title') description = models.TextField(_('description'), blank=True, null=True) content = RichTextUploadingField() Here's my form class class ArticleForm(ModelForm): class Meta: model = kb_models.Article And finally my CreateView, class CreateArticleView(generic.CreateView): form_class = ArticleForm model = Article def get_success_url(self): return "some_redirect_url" Right now I have configured my URLs like below, path('add/', CreateArticleView.as_view(), name='create_article') path('<slug:article>', ArticleDetailView.as_view(), name='article_detail'), path('<slug:article>/update', UpdateArticleView.as_view(), name='update_article') The current flow will render a form when I hit the add/ resource endpoint, and save the resource in the database only after I submit the form. After that, the article can be accessed using the slug generated from the title. What I want instead is to be able to create the Article resource before the resource is rendered, so that the add/ endpoint redirects to some add/unique-uuid endpoint, and even when the form is not submitted from the browser, this empty resource is preserved, and it can be accessed later on because of the unique-uuid. I thought of instantiating an object and redirecting that to UpdateView, but I am having difficulties in figuring out how to keep track of the unique-uuid and point both generated-uuid and slug … -
Django - LANGUAGE_CODE - 'en-IN' does not work, but 'hi-IN' works
Django version 2.2 and 3.0 Purpose: I would like to display numbers in India locale format. For e.g. 1000000 should be displayed as 10,00,000 Action To do this, I went to settings.py and made the following changes: LANGUAGE_CODE = 'IN' - date and time was displayed in Indonesian format but grouping of numbers were correct LANGUAGE_CODE = 'en-IN' - date and time was displayed properly but grouping of numbers were incorrect LANGUAGE_CODE = 'hi-IN' - date and time had Hindi language display but grouping of numbers were correct What I want LANGUAGE_CODE = 'en-IN' to display date and time properly and also do number grouping My settings.py file : LANGUAGE_CODE = 'en-IN' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = (3,2, 0) USE_TZ = True I had a look at Number Grouping which actually talked about this but I believe documentation is misleading. For starters they have put language code as en_IN which doesn't work. Let me know if any additional information needed. -
Get latitude and longitude after clicking on Geodjango Leaflet map
I have a form with a Geodjango Leaflet map on my page. What I want to achieve is that after clicking somewhere on the map, I get the latitude and longitude from that location, to than store that in my form. The code in the form already takes care of placing a marker on the map. I'm not able to find the location where I clicked. forms.py class PlacesForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( required=False, widget=LeafletWidget()) class Meta(): model = Places form.html var markers = []; var layerGroup = new L.layerGroup(); $.fn.setMap = function(map) { console.log(layerGroup); layerGroup.clearLayers(); //$(".leaflet-marker-icon").remove(); $(".leaflet-popup").remove(); if( $("#id_latitude").val() && $("#id_longitude").val() ) { map.setView([$("#id_latitude").val(), $("#id_longitude").val()], 18); markers = L.marker([$("#id_latitude").val(), $("#id_longitude").val()]).addTo(layerGroup); if( $("#id_radius").val() ) { L.circle([$("#id_latitude").val(), $("#id_longitude").val()], {radius: $("#id_radius").val()}).addTo(layerGroup); } layerGroup.addTo(map); } } $(document).ready(function() { // Store the variable to hold the map in scope var map; var markers; $(window).on('map:init', function(e) { map = e.originalEvent.detail.map; $.fn.setMap(map); }); $("#id_latitude").on("change", function () { $.fn.setMap(map); }); $("#id_longitude").on("change", function () { $.fn.setMap(map); }); $("#id_radius").on("change", function () { $.fn.setMap(map); }); $('#id_place-map').on("click", function(e) { //var lat = e.latlng; //var lng = e.latlng; console.log(e); }); }); </script> If I look in my console I can't find anything that I can use. I only see the … -
Django tournament
I have a problem with my model, i don't know how to create model called battle, because i want to choose two users from my database but i don't know how to create it class battle(models.Model): user1 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) user2 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) judge = models.ForeignKey(Judges, on_delete=models.DO_NOTHING) data = models.DateField(auto_now_add=False, auto_now=False) I'd appreciate any hint -
Copying dataframe column dict into Django JsonField
I have a table created with Django(3+) on a postgres database (10+). Class Cast(models.Models): profiles=JSONField(null=True) I am trying to copy a dataframe with a column full of python dict of the form {'test':'test'}. When I use the command: df.to_sql('cast',engine,if_exists='append') I get the following error: (psycopg2.ProgrammingError) can't adapt type 'dict' I tried replacing my dict by None and it worked well. I have correctly added 'django.contrib.postgres' in INSTALLED_APPS ( I don't know if this should be done before creating the database but I guess not) I must add that the postgres database is on a remote server, the django code is on my local computer and the code to copy the dataframe on a second remote server. -
Can I Delete migrations models django?
i am creating my site with django and MySQL (all are latest versions), my data base plan was change. now i want to edit my MySQL database. the project is still testing in face i don't need any data of the database. I'm new for python, Django with MySQL. please help with this. thank you -
How to create a google sign-in popup window that gets closed after login success in Django
I am creating a Django app that allows google sign-in (using python-social-auth). I want the google sign-in page to open in a new window. I am able to implement it with a javascript window.open() function. But after login, the app continues (successfully) on the created window. How do I get it to close itself and redirect the parent to the appropriate redirect_after_login_page? Is there any native way in Django to implement popup windows? -
Exception Value: 'str' object has no attribute '__name__' CreateView
Не получается создать экземпляр класса изза ошибки: Exception Value: 'str' object has no attribute 'name' До некоторго времени работало в норме, а сейчас перестало. Не могу понять в чем проблема. Заранее спасибр view.py class FoodCreateView(CreateView): fields = ('food_name','active_b','food_type_r','boxing_r','profile_pic_i','show_comments_b','User_Create_r') queryset = Food.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['test'] = self.request.user.id else: pass return context url.py path('food/create/',views.FoodCreateView.as_view(model="Food"),name='create'), Model.py class Food(models.Model): food_name = models.CharField(max_length = 25, verbose_name="Наименование еды") date_d = models.DateTimeField(auto_now=True, verbose_name="Время создания") desc_c = models.CharField(max_length = 256, verbose_name="Описание блюда") active_b = models.BooleanField(verbose_name="Активно?") food_type_r = models.ForeignKey(Food_Type_ref, models.DO_NOTHING, verbose_name="Тип Блюда", related_name='Food_type') boxing_r = models.ForeignKey(Boxing_ref, models.DO_NOTHING, verbose_name="Упаковка") moderated_b = models.BooleanField(verbose_name="Прошел модерацию", default=False) User_Create_r = models.ForeignKey(User, models.DO_NOTHING, verbose_name="Автор") views_n = models.SmallIntegerField(verbose_name="Просморы", default=0) profile_pic_i = models.ImageField(upload_to='profile_pics', blank=True, verbose_name="Фото еды") show_comments_b = models.BooleanField(verbose_name="Отображать комментарии") def __str__(self): return self.food_name def get_absolute_url(self): return reverse('dish_app:detail',kwargs = {'pk':self.pk}) -
cleaned_data is returning wrong/different value
I have been struggling with the Forms in Django. Able to get the value from the cleaned_data but it returns a totally different number. For example, I have 4 values to choose from (2,3,4,5). If I select 2, it will give cleaned_data.get(name_of_form_field) returns 5. And so on. class PopulationForm(forms.Form): districts = forms.ModelChoiceField(queryset=Population.objects.order_by('districtid').values_list('districtid',flat=True).distinct()) There are 4 options for a user to choose from: 2,3,4,5. If the user selects 2, it returns 5 and so on. I am not sure what's happening. Here is my views.py: if request.method == 'POST': form = PopulationForm(request.POST) if form.is_valid(): print(form.cleaned_data.get('districts')) return HttpResponse(form.cleaned_data.get('districts')) Here is my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Forms Tutorial</title> </head> <body> <h2>Django Forms Tutorial</h2> <form action="/display/" method="post"> {% csrf_token %} <table> {{form.as_table}} </table> <input type="submit" value="Submit" /> </form> </body> </html> -
Cannot resolve keyword 'pub_date_year'
I followed the documentation django enter link description here this my code model.py from django.db import models # Create your models here. class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): return self.full_name class Article (models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete = models.CASCADE) def __str__(self): return self.headline code urls.py from django.urls import path from . import views urlpatterns = [ path('article/<int:year>/', views.year_archive), ] code views.py from django.shortcuts import HttpResponse, render from .models import Article def year_archive (request,year): a_list = Article.objects.filter(pub_date_year = year) context = { 'year' : year, 'article_list' : a_list } return render(request, 'news/year_archive.html', context) and than year_archive.html {%block title%} Article For {{ year }} {%endblock%} {% block content %} <h1>Article For {{year}} </h1> {% for ar in article_list %} <p>{{ar.headline}} </p> <p>By{{ar.reporter.full_name}} </p> <p>Publsihed {{ar.pub_date}} </p> {% endfor %} {% endblock %} I want to ask when i input urls http: // localhost: 8000 / article / 2020 / error appears Cannot resolve the keyword 'pub_date_year' what should I fix -
django DetailView doesn't catch data from ManyToMany field
I have 3 models: first main "Stones" connect by ForeignKey with "Typs" and Many-to-Many with "Mentions". When I try to write a template for detail view for each "stone" with DetailView class, it shows data only from "Stones" and "Typs", not from 'Mentions" my models.py (necessary part) class StonesManager(models.Manager): def all_with_prefetch_mentions(self): qs = self.get_queryset() return qs.prefetch_related('mentions') class Stones(models.Model): title = models.CharField(max_length=30, verbose_name='Назва') place = models.TextField(verbose_name='Месцазнаходжанне') legend = models.TextField(null=True, blank=True, verbose_name='Легенда') typ = models.ForeignKey('Typ', null=True, on_delete=models.PROTECT, verbose_name='Тып') objects = StonesManager() class Typ(models.Model): name = models.CharField(max_length=20, db_index=True, verbose_name='Назва тыпу') def __str__(self): return self.name class StonesImage(models.Model): image = models.ImageField(upload_to=stones_directory_path_with_uuid) uploaded = models.DateTimeField(auto_now_add=True) stones = models.ForeignKey('Stones', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Mentions(models.Model): work = models.TextField(verbose_name='Праца') year = models.PositiveIntegerField(blank=True, null=True) sacral_objects = models.ManyToManyField(Stones, related_name='mentions', verbose_name='Сакральны аб\'ект') my views.py (necessary part) class StonesDetail(generic.DetailView): queryset = Stones.objects.all_with_prefetch_mentions() template_name = 'volumbf/stone_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_form'] = self.stones_image_form() return context def stones_image_form(self): if self.request.user.is_authenticated: return StonesImageForm() return None my template (necessary part) 1. All are shown in the right way <h2> {{ stones.title}} </h2> <p>{{ stones.legend }} </p> <p>{{ stones.place }}</p> <p>Typ: <a href="/volumbf/{{ stones.typ.pk }}/">{{ stones.typ.name }}</a></p> Isn't shown at all Mentions: {% for work in stones.mentions.work %} <p><a href="{% url 'work_detail' work.pk %}"> … -
Django : Best way to Query a M2M Field , and count occurences
class Edge(BaseInfo): source = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_source") target = models.ForeignKey('Node', on_delete=models.CASCADE,related_name="is_target") def __str__(self): return '%s' % (self.label) class Meta: unique_together = ('source','target','label','notes') class Node(BaseInfo): item_type_list = [('profile','Profile'), ('page','Page'), ('group','Group'), ('post','Post'), ('phone','Phone'), ('website','Website'), ('email','Email'), ('varia','Varia') ] item_type = models.CharField(max_length=200,choices=item_type_list,blank = True,null=True) firstname = models.CharField(max_length=200,blank = True, null=True) lastname = models.CharField(max_length=200,blank = True,null=True) identified = models.BooleanField(blank=True,null=True,default=False) username = models.CharField(max_length=200, blank=True, null=True) uid = models.CharField(max_length=200,blank=True,null=True) url = models.CharField(max_length=2000,blank=True,null=True) edges = models.ManyToManyField('self', through='Edge',blank = True) I have a Model Node (in this case a soc media profile - item_type) that has relations with other nodes (in this case a post). A profile can be the author of a post. An other profile can like or comment that post. Question : what is the most efficient way to get all the distinct profiles that liked or commented on anothes profile's post + the count of these likes /comments. print(Edge.objects.filter(Q(label="Liked")|Q(label="Commented"),q).values("source").annotate(c=Count('source'))) Gets me somewhere but i have the values then (id) and i want to pass the objects to my template rather then .get() all the profiles again... Result : Thanks in advance -
django rest framework accessing and editing nested model
i'm new to django rest framework, spent last ~2hours looking for the answer and still didn't find one. Let's say i've got 2 models class Person(models.Model): name = models.CharField(max_length=50) class Language(models.Model): person = models.ForeignKey( Person, related_name='prs', on_delete=models.CASCADE) name = models.CharField(max_length=50) i want to be able to access all persons languages like that -> person/{person_id}/language and to access and edit specific language like that -> person/{person_id}/language/{language_id} thanks in advance -
I can not start Django local server
I am learning Django during this lock-down. My app has been running properly , made some changes like adding models ,etc and hit runserver and got errors below: PS C:\Users\RK\RentalMgt\TenancyMgt> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\ProgramData\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Traceback (most … -
Django session issue while redirecting to other
I am developing the e-commerce website with Django, So after successful payment through Paytm payment gateway(Integration testing) I have a session issue in the local server, after redirecting from Paytm test integration portal to a payment success page (local server ), user session logout automatically while I am on the payment success page. Payment.html file {% extends 'shop/base.html' %} {% load static %} {% block title%} Paytm merchant payment page {% endblock %} {% block content %} {% csrf_token %} <h1>Redirecting you to the merchant....</h1> <h1>Please do not refresh your page....</h1> <form action="https://securegw-stage.paytm.in/order/process" method="post" name="paytm"> {{ form.as_p }} {% for key, value in param_dict.items %} <input type="hidden" name="{{key}}" value="{{value}}"> {% endfor %} </form> <script> document.paytm.submit() </script> {% endblock %} paymentstatus.html file {% extends 'shop/base.html' %} {% load static %} {% block title%}Shoppy hub{% endblock %} {% block content %} {% csrf_token %} <div class="container"> <div class="col my-4"> <h1>Payment status regarding your order Id : {{response.ORDERID}}</h1> {% if response.RESPCODE == '01' %} <h3>Amount paid:{{response.TXNAMOUNT}} </h3> <h3><img style="height:50px;"src="/static/img/success.png" >Your order has been received successfully</h3 > <h3>Thank you for your purchase! </h3> {% else %} <h2> <img style="height:50px;"src="/static/img/fail.jpg" >Your order has been failed</h2 > {% endif%} </div> </div> {% endblock %} {% block … -
Django 3.0.3 IntegrityError FOREIGN KEY constraint failed when making changes to db
I have two models in my database, an 'Account' model (which is a custom user model) and a 'Return' model. My database worked fine up to the point of adding the 'Return' model, which has a ForeignKey relationship with the 'User' model, which I suspect is causing the problem. (Each return belongs to an existing user. In the admin panel, the option box is populated with existing users so I thought this was working correctly?) Appreciate any help with this! Error: IntegrityError at /admin/returns/return/add/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/admin/returns/return/add/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Here is my Return app's models.py: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Return(models.Model): user = models.ForeignKey(User, related_name="returns", on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=True) last_edited = models.DateTimeField(null=True) TAX_YEAR_CHOICES = [ ('2019', '2019'), ('2020', '2020'), ('2021', '2021'), ] tax_year_ending = models.CharField( choices=TAX_YEAR_CHOICES, max_length=4, blank=False, null=False, ) RETURN_STATUS_CHOICES = [ ('1', 'In progress'), ('2', 'Completed, awaiting review'), ('3', 'Completed, under review'), ('4', 'Completed, awaiting client action'), ('5', 'Submitted to HMRC'), ] return_status = models.CharField( choices=RETURN_STATUS_CHOICES, max_length=1, default=1, blank=False, null=False, ) Here is the post request information from the … -
Django @register.simple_tag of custom tags and filter is not working in template
app/templatetags/custom.py from django import template register = template.Library() @register.simple_tag def add(value, args): return value + args template/index.html {% load custom %} {% with number=0 n=0 %} {% for n in range(50) %} {% if n|divisibleby:6 %} {{ number|add:"1" }} {{ number }} {% endif %} {% endfor %} {% endwith %} I read the official Django Template Tag I want an increment in number like number ++ or number +=1 but it's not working and the server is also working. Somehow I found that {% load custom %} is not working because add function defined is not working. How to solve this error please help !! -
Django: changing representation of a field in serializer
I have a field what displays an average score and depends on another model's field. I use SerializerMethodField in order to get needed value. It looks like this: class TitleSerializer(serializers.ModelSerializer): rating = serializers.SerializerMethodField() class Meta: fields = '__all__' model = Titles def get_rating(self, obj): rating = obj.reviews.all().aggregate(Avg('score')) return rating It works but doesn't return it in a way I need. Now I get data what looks like: "rating" : { "score__avg" : some_value } How can I change it to: "rating" : some_value Thanks in advance. -
How do I serve static files using uvicorn?
I followed a tutorial regarding websockets for django and it works, however, if I try to serve a javascript file, I get a 404. asgi.py looks like: import os from django.core.asgi import get_asgi_application from chat.chat import websocket_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auralias.settings') django_application = get_asgi_application() async def application(scope, receive, send): if scope['type'] == 'http': # Let Django handle HTTP requests await django_application(scope, receive, send) elif scope['type'] == 'websocket': # We'll handle Websocket connections here await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type {scope['type']}") The settings file has STATIC_URL = '/static/' STATIC_ROOT = 'auralias/static' And there are files in the auralias/static directory. The index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Group Chat</title> </head> <body> <h1>Group Chat</h1> <script src="{% static "chat/js/chat.js" %}"></script> </body> </html> But I'm getting INFO: 127.0.0.1:42822 - "GET /static/chat/js/chat.js HTTP/1.1" 404 Not Found In the output of uvicorn. If I run python manage.py 0.0.0.0:8000 then the file is found. How am I meant to serve static files via uvicorn? -
Pass Primary Key To Bootstrap Modal in Django
Hi I am trying to pass the primary key of an object to a bootstrap modal form. What I am finding is that one particular line of code is preventing the modal from even launching but I do not know why. I will highlight that below. So what am I missing? If I change the url in convert.html the modal launches, but I need to use the url I show below. base.html .... <div id="modal-div"></div> proforma_list.html {%for item in proformas %} <tr class="table-item"> ... <td> <a id="convert-modal" class="open-modal" data-url="{% url 'ConvertProformaView' item.pk %}">Convert</a> </td> <tr> {% endfor %} <script> ////////////////// CONVERT PROFORMA FORM /////////////////////// var modalDiv = $("#modal-div"); console.log(modalDiv) $("#convert-modal").click(function() { $.ajax({ url: $(this).attr("data-url"), success: function(data) { modalDiv.html(data); $("#myEdit").modal(); } }); }); </script> convert.html {% load crispy_forms_tags %} <div class="modal fade" id="myEdit" role="dialog"> <div class="modal-dialog"> <form class="well contact-form" method="POST" action="{% url 'ConvertShipmetView' %}"> <!---THIS URL CREATES THE PROBLEM, BUT I DONT KNOW WHY! IF I PUT A DIFFERENT URL HERE IT WORKS FINE---> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">New Shipment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{shipmentForm|crispy}} </div> <div class="modal-footer"> <button type="submit" class="btn btn-default">Submit</button> <button value="" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> … -
make Django `JSONField` stoke dictionary keys as integer
Is it any way to make Django JSONField store dictionary keys as integers? for example i have following dictionary in JSON {4: timezone.now().timestamp()} Key is 4 and it is integer. After this dictionary is saved in DB , key 4 turns to "4" : {"4": timezone.now().timestamp()} Is it any chance to prevent this behaviour somehow? Thank you. -
TypeError in as_view() in Django Restful Application
I have a basic Django app that I am copying in part from the Django Rest Framework docs. The issue I am having is that having implemented generic class based views I am getting a strange error. TypeError: as_view() takes 1 positional argument but 2 were given The stack trace points to my api/urls.py file and this line where I define url patterns: path('', include(router.urls)), The project is based out of api with a second app users. The only place as_view() is implemented is in users/urls.py as so: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from users import views urlpatterns = [ path('users/', views.UserList.as_view()), path('users/<int:pk>', views.UserDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) What arguments should be there or what have I configured wrong that is causing this issue? views.py from users.models import User from users.serializers import UserSerializer from rest_framework import generics class UserList(generics.ListCreateAPIView): """ List all users or create a new user """ queryset = User.objects.all() serializer_class = UserSerializer @classmethod def get_extra_actions(cls): return [] class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer api/urls.py from django.contrib import admin from django.urls import path, include from rest_framework import routers from users import views router = routers.DefaultRouter() router.register(r'users', views.UserList) router.register(r'users', views.UserDetail) urlpatterns = [ path('', … -
which docker image should i use as base for a production django project?
with Ubuntu 20.04 LTS recently published, which docker image should I use as a base image for my dockerfile? the image is intended to be used in production but I also want to use it for development. in the tutorials I watched they use python:3.*-alpine but they say it is not for production. -
Django creates an extra object on submit
I am trying to create an Answer object once the page is rendered, when the user provide his input, the Answer object should be updated with the new input and saved. I am able to do that but for some reason an extra object is created when the user clicks the submit button and that object is always None. I use AJAX to send data from the template. views.py def attention_view(request): participant = get_object_or_404(Participant, user=request.user) if request.method == 'POST': question_id = request.POST.get('assigned_question') question = get_object_or_404(Question, pk=question_id) answer = Answer.objects.get(participant=participant, question=question) if answer.answer is not None: #preventing participants from changing their answer HttpResponse('') else: answer.answer = selected_choice answer.save() attention_question = Question.objects.get(id=13) answer = Answer.objects.create(participant=participant, question=attention_question) seconds_left = int(answer.seconds_left) context = {'attention_question': attention_question, 'answer': answer} return render(request, 'study/AttentionCheck.html', context) what could be the cause of creating an extra object ? -
Which AWS service to use when i have different backend and frontend?
I have my backend written in django. I researched and understand that AWS EC2 or AWS lightsail are cost effective solutions for me. What I am confused is about frontend. Should I use the same instance or create a container and use Amazon Container services ? The concerns I have is flexible load of containers during multiple users coming to website, CORS/Same origin issues when deployed in same instance, security issues when deployed in same instance, cost effectiveness Please help how do you decide in this situation