Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request.POST returns an empty dict
code skips the whole if block directly goes to the last else. I am using django.forms to get input from the user. the same thing happens when the method is set to GET. I tried the same with normal HTML forms the same result. But the weird fact it earlier It was working properly in the initial stages of the project while I was experimenting with my views and models this start causing the error in my project as I cannot get the user input. views.py def output(request): print(request.POST) # returns empty dict if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): url = form.cleaned_data['input_url'] print(url) return render(request, 'classifier/output.html', {'url':url}) else: print(form.errors()) else: print("error") error = "Oops" return render(request, 'classifier/output.html',{'url':error}) -
IntegrityError at /update_order/ duplicate key value violates unique constraint "app_order_pkey".DETAIL: Key (id)=(54) already exists
I am getting the above error . This is my updateorder view: def updateorder(request): data = json.loads(request.body) orderid = data['orderid'] status = data['status'] order, created=Order.objects.update_or_create(id=orderid, status=status) return JsonResponse('Status was updated',safe=False) and this is my js: var updateBtns = document.getElementsByClassName('update-status') for (i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var orderid=this.dataset.orderid var updatestatus = document.getElementById(orderid); var status = updatestatus.options[updatestatus.selectedIndex].value; updateOrderStatus(orderid,status) }) } function updateOrderStatus(orderid,status){ console.log('User is logged In , sending data....') var url = "/update_order/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'orderid':orderid,'status':status}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:',data) location.reload() }) } What I am wanting to do is that I have a admin page for my website where i see all orders and I am wanting to from that page change the status of the order. This is my selectbox for reference: <select name="dstatus" id="{{ord.id}}" class="updatestatus"> <option value="Preparing" id="Preparing" >Processing</option> <option value="Out For Delivery" id="Out For Delivery">Out For Delivery</option> <option value="Delivered" id="Delivered">Delivered</option> <option value="Cancelled" id="Cancelled">Cancelled</option> </select> <button data-orderid={{ord.id}} class="btnabc btnabc-outline-cottgin update-status">update</button> and this is my order mode: class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) status = ( ("Preparing", "Preparing"), ("Delivered", "Delivered"), ("Out For Delivery", "Out For Delivery"), ("Cancelled","Cancelled") ) status=models.CharField(max_length=20,blank=True,null=True,choices=status) So my aim is that whenever from my page I change the status of order It changes … -
How do i add small number like 1/4 in the input text of html?
I'm a beginner in django Web Development,i am doing a project for a tailoring shop . my client want me to put measurement with fraction value like 1/2 with condition that the measurement should be bigger than the fraction value, is like 45 1/2 . Measurement value 45 want to be bigger and 1/2 as smaller I tried changing the font size but both will be get changed HELP me to solve this problem enter image description here -
Django Rest Framework Syntax issues [closed]
Hi I've written this code and I'm learning Django + Django Rest Framework DEFAULT_RENDERER_CLASSES = [ 'rest_framework.renderers.JSONRenderer', ], if DEBUG: DEFAULT_RENDERER_CLASSES += [ 'rest_framework.renderers.BrowsableAPIRenderer' ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication' ], 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES, } and when I try to run it it says there is a type error with this error DEFAULT_RENDERER_CLASSES += [ TypeError: can only concatenate tuple (not "list") to tuple I've tried doing a list, and doing = instead however, I cannot find a solution. Any tips? -
Django get_query_set ValueError
I'm trying to create a ListView in django for Post categories. So for each post i'm including a link which sends you to a page containing all posts with the same category. I'm using get_queryset on my PostCategoryListView in order to filter them but it shows me the error Field 'id' expected a number but got 'technology' My models: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Category(models.Model): type = models.CharField(max_length = 20) image = models.ImageField(default = 'default.jpg', upload_to = 'category_pics') def __str__(self): return self.type class Post(models.Model): title = models.CharField(max_length = 30) content = models.TextField() date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete = models.CASCADE) category = models.ForeignKey(Category, on_delete = models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) My views.py : class PostCategoryListView(ListView): model = Post template_name = 'blog/category_posts.html' context_object_name = 'posts' def get_queryset(self): kategoria = get_object_or_404(Post , category = self.kwargs.get('category')) return Post.objects.filter(category = kategoria) My anchor tag in htmt: <a href="{% url 'post-category' post.category %}"><h2>{{ post.category }}</h2></a> My urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', PostListView.as_view() , name='blog-home'), path('post/<str:username>/', UserPostListView.as_view(), name = 'user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name = 'post-detail'), path('post/new/', PostCreateView.as_view(), name = 'post-new'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name = 'user-posts'), path('category/<str:category>/', PostCategoryListView.as_view(), … -
how can i do payment setup in django using strip
hi i will create a blog website... when user upload post than they select subscription plan and post will created depends on subscription plan(like one month plan etc..) suggest me how can i do this using strip -
How do I add phone number field to django UserCreationForm?
I want to add PhoneNumberField so I can use take phone number of user at time registration. I already have UserCreationForm model which is used by CreateUserForm to create a new User. However by default it does not phone number field. I tried adding it by adding phone variable in forms.py but it does not work giving the error below. forms.py class CreateUserForm(UserCreationForm): phone=PhoneNumberField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'phone'] models.py class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) phone=PhoneNumberField(default=None) def create_profile(sender, **kwargs): if kwargs['created']: user_profile=CustomerReg.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) This is Error I get when I run python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 368, in execute self.check() File "D:\djangoL2G\venvP\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "D:\djangoL2G\venvP\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "D:\djangoL2G\venvP\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "D:\djangoL2G\venvP\lib\site-packages\django\utils\functional.py", line … -
Receiving values of a column of django table once
I have these entries in my database: name salary height Ema 2.3 1.70 Sarah 3 1.68 Emily 2.3 1.82 Jane 3 1.73 My model is: #models.py class information(models.Model): name= models.CharField(max_length=100, default='No_name') salary= models.DecimalField(max_digits=4, decimal_places=2, null=True) height= models.DecimalField(max_digits=4, decimal_places=2, null=True) How can I retrieve all possible salaries? I want to receive s= [2.3, 3] as the result. If I try I= information.objects.all() and then s= I.salary, I will receive s=[2.3, 3, 2.3, 3] as the result, but I want to have each value once in s. -
Benefits of using django-channels instead of not using it
I am working on a chat application, and I am wondering what are the benefits of for example using django-channels instead of making the chat in "raw" django? Thank you in advance. -
How to get week number of a month in django orm?
I am trying to get the week of the month, for example "March (week 1 (days 1 to 7), week 2 (days 8 to 15), week 3 (days 16 to 23), week 4 (days 24 to 31)) "I have tried this: data['month'] = list(Records.objects.annotate(month=Month('date'), week=YearWeek('date')).filter(month=8).values("date", "week").annotate(month_sum=Sum('tot')).order_by()) class Month(Func): function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = IntegerField() class YearWeek(Func): function = 'EXTRACT' template = '%(function)s(WEEK from %(expressions)s)' output_field = IntegerField() -
from python crash course web app django project
[enter image description here][1] I am trying to do the web app project and attempting to print topic ids but it prints only Object(number) and I am pretty sure it has to do something with django admin [1]: https://i.stack.imgur.com/1WkEr.png -
Django REST framework Access data from a ForeignKey of a OneToOneField
I'm trying to access data from serializer of DRF. I have some model like this class Visit(models.Model): LogInTime = models.DateTimeField(null=True) LogOutTime = models.DateTimeField(null=True) IsLogOut = models.NullBooleanField(null=True) Description = models.CharField(max_length=300, def __str__(self): return self.Description class Person(models.Model): Visit = models.OneToOneField( visit, on_delete=models.CASCADE) def __str__(self): return self.visit.Description class EmployeeTypePerson(models.Model): Person = models.ForeignKey( Person, on_delete=models.CASCADE) Employee = models.ForeignKey( 'Employee', on_delete=models.CASCADE) class VisitorTypePerson(models.Model): Person = models.ForeignKey( Person, on_delete=models.CASCADE) Visitor = models.ForeignKey( 'Visitor', on_delete=models.CASCADE) VisitingTo = models.ForeignKey( 'Employee', on_delete=None, null=True) Now i want to update all data By serializer As like ----- Visit > Person > EmployeeTypePerson / VisitorTypePerson NOTE : EmployeeTypePerson & VisitorTypePerson both have ForeignKey And i need to update those -
How to make one to many relationship that uses many diffrent models in Django?
I'm writing one of first Django apps and I have recipe model like this: class Recipe(models.Model): name = models.CharField(max_length=64) and also many other models for steps in recipe: class BaseStep(models.Model): recipe = models.ForeignKey('recipe.Recipe', on_delete=models.CASCADE) class TextStep(BaseStep): text = models.CharField(max_lengh=4096) class ListStep(BaseStep): list_elements = models.CharField(max_length=2048) class TimerStep(BaseStep): time = models.PositiveIntegerField() above models are simplified, what makes them pointless but I need them this way. I know that normally I would specify ForeignKey in BaseStep so that I have some reference, like this: recipe = models.ForeignKey('recipe.Recipe', related_name='steps', on_delete=models.CASCADE) but this simply doesn't work, because it's inherited by child models, with is not OK because related_name needs to be unique. In the end I need to have field steps in Recipe that will return array or queryset of all the steps. I know that Proxy Models can do something like that but using it here is stupid. Now that I'm thinking, is making a @property function in Recipe, that will query all steps and return python array out of them class a good idea? I need to serialize it in the end, for rest endpoint. -
Django Annotate Getting full list of Users and add flag. Removing users that appear as duplicate
Been stuck on this for a good few hours now, I'm sure its something simple im missing. I want to get full list of Users, but with 'participant' flag added if they are in Project.participants(m2m). That part works! Model: class Project(TimeStampedModel, Slugify): ... participants = models.ManyToManyField(User, blank=True, related_name='%(app_label)s_%(class)s_participants') ... User.objects. .queryset.annotate( participant=Case( When( projects_project_participants__in=project_id, then=Value(project_id)) , output_field=IntegerField() ) ) .order_by('id') I can get the right results if I filter out the rest. But I want to keep full queryset with both true and false. The issue is, if a User is part of 5 groups for instance, then I have both True and False records in data set. (i have 2 results as i have set distinct, but left with a true and false version from different projects). Any ideas of best approach or a simple filter I am missing. -
{{ form.media }} adds jquery.min.js between different servers
I have 2 servers and 2 different interpretations of {{ form.media }} <link href="/static/admin/css/vendor/select2/select2.min.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet"> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.min.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/vendor/select2/select2.full.min.js"></script> <script type="text/javascript" src="/static/admin/js/vendor/select2/i18n/en.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> The difference is just one line: <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.min.js"></script> If this one is activated, the select / change of the select2 dropdown doesn't work anymore. If this is commented, it works again. I checked the pip freeze and they have the same packages versions: Django==2.2 django-autocomplete-light==3.3.4 How is that possible that this line get added? -
Nginx can not proxy pass to Django docker container
I'm running my Django app in docker-compose and I'm exposing port 8000. I have Nginx installed in the VM without docker and I want it to forward requets to my Django app, I tried to use host network in my docker-compose and create an external network but nothing worked and I'm always getting 502 Bad gateway this my nginx.conf: events { worker_connections 4096; ## Default: 1024 } http{ include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf server { listen 80; location /static/ { autoindex on; alias /var/lib/docker/volumes/app1_django-static; } location /media/ { autoindex on; alias /var/lib/docker/volumes/app1_django-media; } location / { proxy_pass http://localhost:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } #For favicon location /favicon.ico { alias /code/assets/favicon.ico; } # Error pages error_page 404 /404.html; location = /404.html { root /code/templates/; } } } and this is my docker-compose file: version: "3.2" services: web: network_mode: host image: nggyapp/newsapp:1.0.2 restart: always ports: - "8000:8000" volumes: - type: volume source: django-static target: /code/static - type: volume source: django-media target: /code/media environment: - "DEBUG_MODE=False" - "DB_HOST=.." - "DB_PORT=5432" - "DB_NAME=db" - "DB_USERNAME=.." - "DB_PASSWORD=.." volumes: django-static: django-media: -
Can Django return empty form fields one by one?
I want my Django view to return empty Form fields one by one. The form is a ModelForm inheriting from a single Model. I haven't tried anything because I don't know how can I make it to return one field instead of all. I might modify fields of ModelForm Meta class. -
Filter on related model annotated field with django & postgresql
A have model A and model B, model B has fields a = ForeignKey(A) and birth_date = DateField(). So my goal is to filter A by age which needs to be calculated from model B birth_date. For example I want to find all A where related B has age more than 20. How can It be done? -
Django REST: one PUT request to populate two models
I have two models with exact same fields in them: person log Essentially, on a PUT request to person, I would like to also make a POST-like behavior to log. How would I do that? -
Django: Update Comment section with new comments on a page with Multiple Posts
I am currently working on a post-comment system where a "Society" has many users, and these users can post their posts and others can comment. The functionality of the Society, users and everything is done. However, I am trying to understand how to create a page where I can display every single post, and their respective comment sections, while creating forms on the same page that allow them to post new comments. Essentially, it is like a post-detail view and its comment section, but for every post on a single page. I would also like to do so with AJAX, to prevent having to reload the whole page. Currently, I am looping over a form to create multiple occurrences of it, and I set auto_id to false in my view so that I do not need to worry about unique id's for the multiple Comment forms. I would really appreciate significant help in understanding how to create a page (like in a Facebook group) where users can post their Posts and their Comments all in the same page rather than having to go to a CreateView. I would post code, but this doesn't seem like too complicated of a model … -
How to process subdomain with another CMS with django?
I got a site on Django 1.9, for example domain name mysite.com. At the moment need to deploy forum on subdomain (forum.mysite.com). And this forum should be with phpBB platform. I try to use django-hosts. hosts.py: from django_hosts import patterns, host host_patterns = patterns('path.to', host(r'forum', 'forum.urls', name='forum'), ) But in fact I doesn't have forum.urls file. And now when I try to get access to the forum.mysite.com - server return me mainpage (markdown without static files). I have misunderstanding what should I do to subdomain work correctly. Can somebody give advice what should I do or where need to focus? -
Django - Update a foreing key relation
I'm having problems with a basic usage on Django (my first time). I'm writing an arcade manager, having Games and Cores(Emulators), that means I have a core field in games. This is the model file : class Core(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=255) bios = models.CharField(max_length=255, default="") def __str__(self): return 'Core {}'.format(self.pk) class Game(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=255) description = models.TextField() logo = models.FileField(blank=True, null=True, upload_to="games/logos/") is_archived = models.BooleanField(default=False) core = models.ForeignKey(Core, on_delete=models.PROTECT, related_name="games", default=1) def __str__(self): return self.name This is the views (maybe not interesting): class CoreViewSet(viewsets.ModelViewSet): serializer_class = CoreSerializer queryset = Core.objects.all() permission_classes = [IsAuthenticated] class GameViewSet(viewsets.ModelViewSet): serializer_class = GameSerializer queryset = Game.objects.filter(is_archived=False) permission_classes = [IsAuthenticated] And this is the serializers: class CoreSerializer(serializers.ModelSerializer): class Meta: model = Core fields = '__all__' class GameSerializer(serializers.ModelSerializer): nb_terminals = serializers.ReadOnlyField() total_donations = serializers.ReadOnlyField() core = CoreSerializer(many=False, read_only=False) class Meta: model = Game fields = '__all__' For the moment I can create, change and remove cores from the database but modifying a game's core (foreing key) is impossible and I dont know why. I will only change if I use core = serializers.PrimaryKeyRelatedField(queryset=Core.objects.all(), many=False) But then the core is only an id and not a serialized object, not what i … -
How to make whole div clickable and put a dynamic url in Django template?
I am trying to display a post (like a tweet in twitter) and when I display it I want the whole div to be clickable. So this works. Website is working the way I wanted with this code; <div onclick='location.href="{% url 'post' post.id %}";' style="cursor: pointer;"> <a href="#"> some other links </a> <a href="#"> some other links </a> </div> But it gives me some warnings in the terminal (VScode), each of the error is showing the same thing (div onclick line ) but strangely giving different errors. And I don't use javascript for this part of the code. I tried different syntax like changing " " to ''. but it doesn't solve the problem. Also in the code, it shows the line with red color as below, if it helps to figure what the problem is. Any advice would be appreciated. Thanks in advance. -
overriding update() method in ModelViewSet vs. overiding update() method in serializer
I am looking at code examples and I see both an update() method for serializers and for ViewSets. What is the difference between the two ? When should I override the update() method in the ViewSet and when should I override it in the Serializer ? -
MY class based detail view is not returning the template properly
In my article_details.html page I have written {{post.title}} but my the page is not showing the specific title. My app name is post and the model name is BlogPost. this is my views.py: from django.shortcuts import render from .models import * from .forms import * from django.views.generic import ListView,CreateView from django.views.generic.detail import DetailView def home(request): return render(request,'post/home.html') class HomeView(ListView): model = BlogPost template_name = "post/home2.html" class ArticleDetailView(DetailView): model = BlogPost template_name = "post/article_details.html" class AddPostView(CreateView): model = BlogPost template_name = "post/add_post.html" fields = '__all__' this is my urls.py from post import views from django.urls import path from .views import HomeView,ArticleDetailView,AddPostView app_name = 'post' urlpatterns = [ path('',views.home,name="home"), path('home2/',HomeView.as_view(),name = "home2"), path('article/<int:pk>',ArticleDetailView.as_view(),name = "article-details"), path('add_post/',AddPostView.as_view(),name="add_post"), ] this is my list page: post/home2.html <ul> {%for post in object_list %} <li><a href="{%url 'post:article-details' post.pk %}">{{post.title}}</a>-{{post.author}}<br/> {{post.body}}</li> {%endfor%} </ul> and this is my detail page:article_details.html: <h1>{{post.title}}</h1> <small>by:{{post.author}}</small><br/> <hr> <br/> <p>{{post.body}}</p> enter code here