Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Gunicorn service on DigitalOcean starting a Django project
I have the following systemd file at /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/serverapp ExecStart=gunicorn --name=avesoft --bind unix:/home/serverapp/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py WebApp.wsgi:application Restart=always SyslogIdentifier=gunicorn User=root Group=www-data [Install] WantedBy=multi-user.target When I manually change the directory to /home/serverapp and run gunicorn --name=avesoft --bind unix:/home/serverapp/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py WebApp.wsgi:application everything works fine and Nginx connects to my Django app through Gunicorn. But by rebooting the server, I get Bad Gateway error that seems Gunicorn has not started working. I don't get what is the reason behind my service file not working. -
With Django Factory Boy, how do I generate a factory for a foreign key?
I'm using Django 3 with Factory Boy 2.12.0. I have the following models. Notice the second depends on the first ... class ContactMethod(models.Model): class ContactTypes(models.TextChoices): EMAIL = 'EMAIL', _('Email') PHONE = 'PHONE', _('Phone') type = models.CharField( null=False, max_length=5, choices=ContactTypes.choices, ) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) class Meta: unique_together = ('phone', 'email',) class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I want to create a factory to generate the Coop model, so I tried the below (included contact method factories as well) ... class PhoneContactMethodFactory(factory.DjangoModelFactory): """ Define Contact Method Factory for a phone number """ class Meta: model = ContactMethod type = ContactMethod.ContactTypes.EMAIL phone = "8005551234" class EmailContactMethodFactory(factory.DjangoModelFactory): """ Define Contact Method Factory for emails """ class Meta: model = ContactMethod type = ContactMethod.ContactTypes.EMAIL email = "test@example.com" class CoopFactory(factory.DjangoModelFactory): """ Define Coop Factory """ class Meta: model = Coop name = "test model" enabled = True phone = PhoneContactMethodFactory() email = EmailContactMethodFactory() web_site = "http://www.hello.com" @factory.post_generation def addresses(self, create, extracted, **kwargs): if not create: # Simple build, do nothing. return if extracted: # A … -
Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response - Django
I am using Django with Django rest framework to host my api's (localhost:8000), and use vue js running on node js server (localhost:8080) to call the apis to view it. when I try to use vue axios to call a rest api I get this response: Access to XMLHttpRequest at 'http://localhost:8000/api/getJobs' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. My Django setting.py is (I installed cors headers / allow all origins) but no luck, here is my code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app_dashboard', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True //My rest api in view and also associate a url for it in urls.py @api_view(['GET']) def get_jobs(request): #... code goes here return HttpResponse(json_obj, content_type="application/json" ) Any solution? Note: I already seen a lot of post like this cors enable in Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response but didn't work! -
Difference between django vs django 2.2?
I noticed on a Youtube Channel, CodingEntreprenuers, that he has tutorials for django. On his github, there are just "tryDjango" and "tryDjango2.2". I was wondering what differences that they have and I'd like to get recommendations from you gurus to choose which version is better for me^^ My Skill Level: Python: Intermediate C: Intermediate-ish, probably a beginner, it's an ancient language Linux: Been on it for about 1 year, a bit familiar with terminal Trying to make the best out of quarantine, help. Keep Safe -
why is my code overriding my base.html navbar?
So, I am creating a profile page and the JS script I need is overriding my base.html navbar. How can can I get it to not do that? Basically it's moving my navbar to the left only on this specific page. I am not sure how I can keep the navbar intact without taking the JS script entirely away. profile.html {% extends "dating_app/base.html" %} <title>Profile</title> <!DOCTYPE html> {% block head %} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> </head> {% endblock %} {% block content %} <title>Profile</title> <div class="container"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading"> <h4 style="color:#CB2603 " >My Profile</h4></div> <div class="panel-body"> <div class="col-md-4 col-xs-12 col-sm-6 col-lg-4"> <img alt="User Pic" src="{{ profile.photo.url }}" id="profile-image1" class="img-circle img-responsive"> </div> <div class="col-md-8 col-xs-12 col-sm-6 col-lg-8" > <div class="container" > <h2>{{ profile }}</h2> </div> <hr> <ul class="container details" > <h3 >About me</h3> <p><span style="width:50px;margin:50px"></span>{{ profile.description }}</p> </ul> <hr> {% if user.id == profile.id %} <p><a style="color:#CB2603 " href="{% url 'dating_app:update_account' profile.id %}">edit profile</a></p> {% endif %} </div> </div> </div> </div> {% endblock content %} base.html {% load bootstrap4 %} {% load static %} {% load unread_messages_counter %} <!-- Navbar is located in this file --> <!doctype html> <html lang="en"> <head> <!-- … -
my UpdateView in CBV for formset not saving the form
i want to update my formset , but it wont be updated , only the parent fields will be updated if you could do something with my issue let me know please , i will appreciate your helps .. this is my UpdateView class MyUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = MyModel form_class = MyModelForm template_name = 'template/template.html' def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyUpdateInlineFormSet(self.request.POST,instance=self.object) data['formset'].full_clean() else: data['formset'] = MyUpdateInlineFormSet(instance=self.object) return data def form_valid(self,form): self.object = form.save() context = self.get_context_data() formset = context['formset'] with transaction.atomic(): if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('my_app:invoice',kwargs={'pk':self.object.pk}) and this is my inlineformset MyUpdateInlineFormSet= inlineformset_factory( MyModel,MyChild,form=MyChildForm,fields=( some fields ),extra=1) i much appreciate your helps ... -
Ensure 2 choice fields on a record are not equal in Django
I have a model with 2 CharFields selected from nearly the same list of choices. They are the same except for the 2nd inclination having a "None" option. class Pawn(models.Model): primary_inclination = models.CharField(max_length=30, choices=PRIMARY_INCLINATION_CHOICES) secondary_inclination= models.CharField(max_length=30, choices=SECONDARY_INCLINATION_CHOICES) I want to ensure the same value can not be selected for both fields. For example, if my choices are selected from A, B, C, then A and B is fine, but A and A is not. It is ok for another Pawn to also have A and B. Some things I've looked into: Specifying unique fields in Meta, but this makes the inclinations only selectable by 1 Pawn unique_together, no other pawn can have the same values for the two fields -
What is the best way to allow change permissions depending of some conditions in django rest framework?
I am building an api with Django rest framework and I am using ModelViewSet with a CustomObjectPermissions and it is working fine for any user with the right permission but I want know how can I allow any user to update his own profile? I mean this user can not update other users but if the user id is the current user id he can update some columns. This user does not have any django permission, he have just access to the app.Finally, I want to use this with DjangoObjectPermissions. Views.py here I want to allow any user update his own profile from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import status, permissions, generics, viewsets from rest_framework.response import Response from rest_framework.views import APIView from .serializers import MyTokenObtainPairSerializer, UserSerializer from .models import User from authentication.permisssions import CustomObjectPermissions class ObtainTokenPairView(TokenObtainPairView): permission_classes = (permissions.AllowAny,) serializer_class = MyTokenObtainPairSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ permission_classes = (CustomObjectPermissions,) queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer permissions.py from rest_framework import permissions class CustomObjectPermissions(permissions.DjangoObjectPermissions): """ Similar to `DjangoObjectPermissions`, but adding 'view' permissions. """ perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } -
Why isn't Django connecting to SQL Server 2019?
Please see below screenshots as to existing configuration (password hidden due to security reasons). Databases Screenshot 1 Python Packages The error that is returned when I attempt to run the server is either SQL Server v15 is not supported or Django 3.0 is not supported. Does anyone have the same issue and a clean-cut solution for resolution? -
'RelatedManager' object is not iterable -> add all() -> 'list' object has no attribute 'all'
Sorry if my wording is weird; I'm not overly familiar with Django Models. I want our API's list of category Tags, which is an instance of our TagCollection model: categories, new = TagCollection.objects.get_or_create(name="Category") I want to then loop over these Tags, held in the tag_set attribute of TagCollection: for category in categories.tag_set: This gave me the error TypeError: 'RelatedManager' object is not iterable. I looked it up, and as this thread mentioned (as well as many others), I needed to add .all() in order to iterate. So I tried that: for category in categories.tag_set.all(): And received the error AttributeError: 'list' object has no attribute 'all'. What gives? I thought it was a RelatedManager? Any help would be greatly appreciated. -
Django automatically run redis server
So I have a Django app that has a live chat build using channels. I am using Redis for the channels layer and every time I want to run the app I have to run the Redis server first. How can I make it so the Redis server runs together with the Django app? And if I host the app how will this work - like how would I run Redis server if I host it on Heroku for example? Thanks in advance! -
Extracting charts of xlsx using python
I want to extract the charts in an xlsx file and save them as an image using python. I know how to do that by win32com.client and importing Dispatch. But I am asking this to implement by django and I am working on a Linux based server, the method based on win32com.client doesn't work. Could anyone guide me how can I do that? -
Django: How to return a clean list from db for charts.js?
I would like to update charts.js with info from my database. To do that in my view i have this: def processCharts(request): process = ProcessInfo.objects.values_list('process_name') process_list = list(process) context = {'process_list' : process_list, } return render(request, 'process/charts.html', context) i would like to retrive a list i can put into charts.js and that looks like this labels: ['Option1', 'Option2', 'Option3', 'Option4', 'Option5', 'Option6', 'Option7'], When i render process_list on charts.js i get a messy list like the one below: labels: [(&#x27;Accounts Recivabel&#x27;,), (&#x27;dsas aasdasds&#x27;,), (&#x27;Test user 2&#x27;,), (&#x27;Accounts Recivabel&#x27;,), (&#x27;Test user 2&#x27;,), (&#x27;Accounts Recivabel&#x27;,), (&#x27;Test user 2&#x27;,), (&#x27;Test user 2&#x27;,), (&#x27;Recivabel&#x27;,), (&#x27;Accounts Recivabel&#x27;,), (&#x27;Accounts Recivabel&#x27;,), (&#x27;Cash app v 123&#x27;,), (&#x27;Recruiting&#x27;,), (&#x27;Accounts Recivabel&#x27;,)], How can i clean my querryset or the objects from the database to get a clean list for charts.js ? -
How to create a comment-creation page related to a single blog-style post in Django
I am trying to create a comment creation page related to a single post on a blog-style site using Django. The home page has a list of posts, each with a "comment" button. Ideally this "comment" button would then take you to a page that would have the original post listed at the top with the comment creation form underneath it. I've been trying to figure out a way to access the data I'm looking for using primary keys but am not sure how to tie everything together. Here are the 2 models I am trying to access (Post and Comment): class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=128) content = models.TextField() image = models.ImageField(upload_to='post_pics', blank=True) date_posted = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_created = models.DateTimeField(default=timezone.now) And the urls.py: from django.urls import path from .views import PostCreateView, PostListView, VehicleListView, CommentCreateView from . import views urlpatterns = [ path('', PostListView.as_view(), name='home'), path('comment/new/<int:pk>', CommentCreateView.as_view(), name='comment-create'), ] This is my current HTML for the home page (currently adds the post id to the end of the HTML on linked "comment-create" page): {% for post in posts %} … -
CORS Allow not working - Django and Vuejs [duplicate]
I am using Django with Django rest framework to host my api's (localhost:8000), and use vue js running on node js server (localhost:8080) to call the apis to view it. when I try to use vue axios to call a rest api I get this response: Access to XMLHttpRequest at 'http://localhost:8000/api/getJobs' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. My Django setting.py is (I installed cors headers / allow all origins) but no luck, here is my code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app_dashboard', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True Any solution? -
Django admin page ManyToManyField displays all rows from database
I have the following models: class OrderItem(models.Model): item = models.ForeignKey(FoodDish, on_delete=models.CASCADE, blank=True, null=True) quantity = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.name}" def get_total_item_price(self): return self.quantity * self.item.price class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) order_date = models.DateTimeField(blank=True, null=True) ordered = models.BooleanField(default=False) total_price = models.FloatField(blank=True, default=0.0) def __str__(self): return f"{self.user.username} ordered on {self.order_date}" Inside the administration page I want to see the items related to a certain order. When entering the page for a certain order however, the field that contains the ManyToManyField displays all the OrderItems in the database (with the entries that are related to the current order highlighted). Why does the datafield in the administration page display all those entries? -
How to selectively specify a django model field value when creating different model objects?
I have the following models in my django app: from django.db import models class Parent(models.Model): my_attribute = models.CharField(max_length=255, blank=True) my_attribute2 = models.CharField(max_length=255, blank=True) class Child(Parent): tracking = models.CharField(max_length=255, blank=True) Then I have another file where I am trying to make instances of these two models. What I intend to do is invoke the create method, based on a parameter, something like this: from .models import * class BaseObjectCreator: model = Parent def createModelObject(trackingEnabled=False): instance = self.model.objects.create( my_attribute = 'value1', my_attribute = 'value2', tracking = 'value3' if trackingEnabled ) class ChildObjectCreator: model = Child def createModelObject(trackingEnabled=True): super().createModelObject(trackingEnabled) But this is not working and throwing error for this line tracking = 'value3' if trackingEnabled. I need something like this for refactoring a large code which involves models like the ones defined above. Can you suggest the correct strategy? -
Django Channels 2: How Many Users Is In The Specific Room
I am using django-channels>=2.0.0 and I want to find how many users in "room1". I don't know how to find total connections. -
Add CSRF in Fetch JS for Django
I have the following JS code in my django template: fetch("http://127.0.0.1:8000/api/endpoint", { method: "POST", body: $("#form").serializeArray(), }).then(function(data) { }); In the api/endpoint, I just get: Forbidden (CSRF token missing or incorrect.): /api/endpoint How do I add the csrf token in the fetch? -
Django or Asp.Net Core? That is the problem
As a medium level .Net programmer, due to implementing a website I tried to go through the Asp.Net Core. I found some tutorials on the web and started learning; however, there was a problem I faced. Despite the fact that I have been working with .Net and C# (mostly with unity game engine, which led to a mobile game) for 2 years or even more, by start learning Asp.Net Core, I found out that I do not know .Net as much as I expected. There were somethings I should have learned before. I searched for other frameworks and Django was a popular one. Besides, I have planned to learn python for machine learning. The website I want to make (with a small team) is nearly similar to KhanAcademy.(We are going to use react for front-end) So, what should I do? Continue .Net core with its amazing new features, or start getting into the python and Django? Your helps accompanied by reasons will be greatly appreciated! -
How Can I upper the word 'i' to 'İ'?
in my project there is a profile that name is "İsmet". When Django try to search it with the following code, return empty. Profile.objects.filter(name__icontains='i') But when I try this return correctly; Profile.objects.filter(name__icontains='İ') is there a way to search with like this? By the way, I try to search with 'i.upper()' but this convert 'i' to 'I'. So this is not work for me. -
Django and Postgres: greater than for tuples
How can I compare tuples in the Django ORM? Say I have a Postgres query like: SELECT * FROM my_table WHERE (last_updated, id) > (1575452913, 123) ORDER BY (last_updated, id) LIMIT 50 How can I express this in Django? Looking at https://docs.djangoproject.com/en/3.0/ref/models/querysets/#gt nothing leaps out. The field_name__gt=something method doesn't really seem to be compatible with this. -
Why do I still get the old values for ManyToManyField comparison?
I found many ways to do it, but it seems that nothing work. I have a model that has a manytomanyfield to another model, I want to be able to compare old values from the manytomany field, and the new ones. class A(models.Model): registers = models.ManyToManyField('B',blank=True) def save(self,*args,**kwargs): try: old_registers = self.__class__.objects.get(pk=self.pk).registers.all() print(old_registers) print(old_registers.difference(self.registers.values_list())) except Analyseur.DoesNotExist: old_registers = None if (old_registers != None) and old_registers.difference(self.registers.values_list()): print("Values changed") class B(models.Model): name = models.CharField(max_length=32) Note that I interact with the models in Django Admin. When I save the instance, I always get the old values for self.__class__.objects.get(pk=self.pk).registers.all() and self.registers.all(). -
How to include multiple context elements in render()
I'm new to Django. My views.py file looks like this - from django.shortcuts import render from django.http import HttpResponse import twitterData # Create your views here. def home(request): profiles = twitterData.getTwitterProfileData() return render(request, "blog/home.html", profiles) This code works fine, profiles is simply a dict of user profile names gathered from Twitter api. Only thing is I want to put this also {"Title": "Home"}. This would allow the page to display the correct title. I try and write the code like this - # Create your views here. def home(request): profiles = twitterData.getTwitterProfileData() return render(request, "blog/home.html", {profiles, "title": "Home"}) and it doesn't run. How can I use multiple items to send to page? -
Django form not saving email
My views- from django.shortcuts import render, redirect from .AuthForms import registerUserForm from django.contrib import messages from django.contrib.auth import login, authenticate def registerUsers(request): if request.method == 'POST': ucf = registerUserForm(request.POST) if ucf.is_valid(): ucf.save() new_user = authenticate(username = ucf.cleaned_data['username'], password = ucf.cleaned_data['password1']) login(request, new_user) return redirect('content') else: ucf = registerUserForm() return render(request, 'LoginAndSignUp/SignUpPage.html', {'ucf': ucf}) My form - I have extended the usercreationform from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm , PasswordResetForm from django import forms class registerUserForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Email', 'autocomplete':'off'})) username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off',})) password1 = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'})) password2 = None class meta: model = User fields = ['username', 'email', 'password1'] class userLoginForm(AuthenticationForm): username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username','autocomplete':'off'})) password = forms.CharField(widget= forms.PasswordInput(attrs={'placeholder':'Password'})) class userPasswordResetEmailForm(PasswordResetForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'placeholder':'Enter your email', 'autocomplete':'off',})) class Meta: model = User fields = '__all__' The email field is not saving the email to database wherease the username and password is correctly being saved. Someone please help