Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to add value to a field by calculating two values for tow fields in django api rest framework not template
#models file I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... If there are any modifications to the important classes, I want to deduct a payment from the original amount and then show the remaining amount after each payment to the user... I want the process to rest framework api endpoint # this class adds payment to each product price class Payment(models.Model): PK = models.AutoField(primary_key=True) payments = models.FloatField(default=0) description_paid = models.TextField(max_length=1500, default='') payment_date = models.DateField(default=datetime.date.today) product = models.ForeignKey('Product',related_name='paymentProducts' , on_delete=models.CASCADE) imag_file = models.ImageField(upload_to='uploads' , blank=True , null=True) deserved_amount = models.FloatField(default=0, null=True , blank=True) ''' I want to add value to deserved_amount field by calculating a payments minus from the class product inside field selling_price ... please help me , thanks ''' #this is class add a product this is class add a product this is #class add a product this is class add a product this is class add #**strong text**product class Product(models.Model): JAWWAL = 'JAWWAL' type_category = [ (JAWWAL,'جوال'), ('SCREEN','شاشة'), ('FRIDGE','ثلاجة'), ('LAPTOP','لابتوب'), ('WASHER','غسالة'), ('ELECTRICAL DEVICES','جهاز كهربائي'), ('FURNITURE','موبيليا'), ('ATHER','اخرى'), ] PK = models.AutoField(primary_key=True) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0) supplier_name = models.CharField(max_length=70 , blank=True , null=True) category = … -
Failure to access image from ImageField from model to display on one of my html pages
I am working on a commerce app wher a user can create a listing and also upload the image of the listing. The data is handled by a ModelForm: class ListingForm(ModelForm): class Meta: model = Listing exclude = [ 'date_made', 'user', 'category', 'is_active', ] The ModelForm inherits from the Listing model. Pay particular attention to the upload_image attribute: class Listing(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] title = models.CharField(max_length= 64) date_made = models.DateTimeField(auto_now_add=True) description = models.TextField() user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE, related_name='user_listings', null=True) starting_bid = models.DecimalField(decimal_places=2, max_digits=264, default=10.00) upload_image= models.ImageField(blank=True, upload_to='media/') category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='name', related_name='category_listings', default=NAME_CHOICES[4][0], db_constraint=False) listing_category = models.CharField(max_length=12, choices=NAME_CHOICES, null=True, default=NAME_CHOICES[4][0]) is_active = models.BooleanField(default=True) def __str__(self): return f'{self.title}' I also have tried to make some media file configurations to my app. settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') (global/project) urls.py: urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my views.py looks like this, im not sure if it is relevant to the problem: def create_listing(request): if request.method == 'POST': import datetime listing_form = ListingForm(request.POST) # bid = request.POST['starting_bid'] if listing_form.is_valid(): bid = listing_form.cleaned_data['starting_bid'] listing_form.save(commit=False) # listing_form.user = request.user listing_form.user = request.user listing_form.date_made = datetime.datetime.today() listing_form.is_active = … -
Django Model Form is not validating the BooleanField
In my model the validation is not validating for the boolean field, only one time product_field need to be checked , if two time checked raise product_field = models.BooleanField(default=False) product_field_count = 0 for row in range(0,product_field_count): if self.data.getlist(f'product_info_set-{row}-product_field'): product_field_count += 1 if product_field_count <= 1: raise ValidationError( _( "Manage Only Preferred Weeds Need to Be Select Once" )) validation error. -
Three strings of code repeat in three different view-functios
I have three view-functions in views.py in django project that using a same three arguments in them: paginator = Paginator(post_list, settings.POSTS_LIMIT) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) How can I put em in a single function (make an utility) to use one string of code in my view-functions, instead of repeat using three? Thats my first question here, thank you :) -
How can I allow users to send emails through my django app but coming from their own gmail account?
I have a django app where users can send emails through the app to contacts that they upload themselves. I use Sendgrid to send the email and the recipient receives an email from a "white-label" address like hello@mydomain.com Now, I would like to implement a system where I can allow users to send emails through our app but that those emails are sent by their own email address. To make it simple, let's just consider "Gmail" and if a user want they can "login with their gmail account" on my app and then send emails from my app that are sent from their account... I know that Gmail has an API and I wonder if I can leverage it to do what I need. -
Created a virtual environment 'test' in my windows command prompt, but workon test not working in visual studio code? How to fix?
Error: PS C:\Users\ARYAN\projects\project1> workon test workon : The term 'workon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 workon test + CategoryInfo : ObjectNotFound: (workon:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Django rest framework for Meetingroom Reservation tasks
I need to realize the following tasks: Create employee Create meeting room Get meeting room reservations and the possibility to filter by employee Create reservation (Reservation has title, from and to dates, employees) So, first I created 2 apps Employees and Reservations, this is the Employees' model (Employees/models.py) : from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager # Creating the CustomUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("An Email must be provided") if not password: raise ValueError("The Password is mendatory") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) # Creating User Model class User(AbstractBaseUser,PermissionsMixin): # Abstractbaseuser has password, last_login, is_active by default email = models.EmailField(db_index=True, unique=True, max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=25) mobile = PhoneNumberField(null=False) address = models.CharField( max_length=250) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','mobile'] … -
What's a proper way to SET aurora_replica_read_consistency in django?
I am looking for a proper way to connect to Aurora from a redundant django app. I have a django app that runs in multiple regions. The Aurora cluster in AWS is configured to have a writable master in one region and a read-only replica with write-forwarding in the other region. This, supposedly, allows apps to "transparently" write to the read-only DB. It's not very transparent because it requires for every session to SET aurora_replica_read_consistency=SESSION. I was hoping to achieve this in the DATABASE session of the django settings file like so: DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.mysql', 'NAME': 'mydb', 'USER': 'admin', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'DB_HOST', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET aurora_replica_read_consistency=SESSION', }, }, } However, this throws an error on the aurora master, which is writable. The error states something that you can only set this variable on the read-only replica. I.e. my django container won't even boot on the master. I tried screwing with the connection signals; however, I did not find a way to make it run the SET command as the first thing after any new django connection to the DB. Signals seem to require each app to have a signal handler. The way … -
How to run pytest on Django rest framework app?
I want to run a pytest on 201 a successful post with just a single field in my project. I have a middleware.py which does something with the last object in the list whenever the project is ran. I have pytests at the moment to judge length of the entries but I want to run pytest when a post is successfully posted? I wish to do the same with a GitHub workflow test -
[DjangoRest + React]: Can't delete items and problems posting (error 403 and 301)
I'm building a very simple react + django website. Everything was going fine until today I made some changes to both the backend and frontend to add a third app that displays dummy pictures with a description. Up until that point, I was using axios to make get, post and delete requests with no trouble. I just wrote axios.post("api/", item) and it would post the item, or axios.delete(api/{props.id}) and the item would be deleted. Now, none of these work. At first I started getting 403 errors. Doing some troubleshooting, I tried adding the full url to see if it worked. Post worked. axios.post("localhost:8000/api/", item) now posts the item. The thing is that when I try to delete - axios.delete(localhost:8000/api/{props.id}) -, I get a 301 error. Besides kicking myself for not backing up before, what can I do? These are the backend and frontend codes. Frontend: import React, { useEffect, useState } from "react"; import Header from "./UI/Header"; import NewTask from "./tasks/NewTask"; import TaskList from "./tasks/TaskList"; import axios from "axios"; import classes from "./ToDo.module.css"; function ToDo(props) { const [taskList, setTaskList] = useState([]); const refreshList = async () => { await axios.get("todo/").then((res) => { const filteredData = res.data setTaskList(filteredData); }); }; useEffect(() … -
How to properly pass an enum class to the .HTML template in django
I have an Enum class like this one: models.py . . class Status(Enum): New = 1 Modified = 2 Done = 3 and I want to pass this to the html template in order to iterate over it and use it. so in my views.py I am passing it like so views.py from models import Status . . status_options = Status return render(request, 'orders.html', {status_options':status_options}) and the problem is when I try to use it inside the HTML template I don't get any values I tried the following orders.html {% for status in status_options %} {{ status.name }} {% endfor %} But I don't get any output Can anyone provide me with some guides here, please? -
Configure the parameters and response template of swagger ui in django
I am using drf_spectacular from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView, ) Can someone please inform me how to custom the JSON "template" that the users see in specific api URLS below? (shown below) For example, in the parameters I want it to be { "number": 0 } and in the response { "alphabet": "a" } -
Modifying Ajax Request for Geonames (show only one city)
I have the following code, and I would like to obtain the information of Geonames, with the streets names of the city of Barcelona. As I have it now, it shows me streets from all over Spain, and I would like it to only show me the one from a certain city, for example Barcelona. That's my actual code: $("#id_start_point").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://secure.geonames.org/search", dataType: "jsonp", data: { featureClass: "R", fcode: "ST", country: "ES", type: "json", maxRows: 10, name_startsWith: request.term, username: "----" }, success: function( data ) { response( $.map( data.geonames, function( item ) { return { label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, value: item.name, } })); } }); }, minLength: 2, select: function( event, ui ) { if (ui.item) { $("#id_start_point").val(ui.item.name); } } }); Thanks! -
Django: How to update DB with renaming of choice fields
Say I have a field which choices A, B, and C. In the next iteration, I rename A to D. When I run migrate, all records that hads this field set to A will be set to ----. Is there a way to tell Django to change A to D during the migration? -
How to give permission to users of one group to create users of another group?
I want to create an application in which only organizations can register themselves and then they register their students. I can't find a way to do it. Is it possible to do it without making the organization as admin as multiple organizations can register on app. This is my user model. ''' from django.db import models import uuid from django.contrib.auth.models import User class OrganizationModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) organization_name = models.CharField(max_length=264,unique=True) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization'] def __str__(self): return self.organization_name class StudentModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) roll_no = models.CharField(max_length=20) organization_name = models.ForeignKey(OrganizationModel,to_field="organization_name",on_delete=models.CASCADE,related_name="student") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization','roll_no'] def __str__(self): return self.organization_name class Meta: constraints = [ models.UniqueConstraint(fields=['organization_name', 'roll_no'], name='unique_student') ] ''' -
Django Celery, Celery beat workers
In celery I've 3 types of tasks first task executes in every 3 minutes and take almost 1 minute to complete, second task is periodic which runs on every monday and takes almost 10 minutes to complete, the third and last one is for sending users emails for register/forget password, I'm confused how many workers/ celery beat instances I should use, can anyone help me out please? -
check if someone already answered the post Question in Django
I am building a discussion Forum where user can ask question and can reply on other's questions. I want to show "Answered" if the Question is already answered and show "Not answered yet" if Question is not answered by any user My model.py class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.CharField(max_length=5000) timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.CharField(max_length=5000) post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' View.py def forum(request): user = request.user profile = Profile.objects.all() if request.method=="POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect('/forum') return render(request, "discussion.html", {'post':post, 'replies':replies}) -
getting ModuleNotFoundError at /admin/login/. How to solve this error
While login in as a superuser getting this error. Below I have mentioned the installed app and middleware in settings.py and I have gotten the error named ModuleNotFoundError. Exception Type: ModuleNotFoundError Exception Value: No module named 'account.backends' Exception Location: , line 973, in _find_and_load_unlocked Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.2.13 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chatbot_app', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] error Traceback (most recent call last): File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\src\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 398, in login **self.each_context(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 316, in each_context 'available_apps': self.get_app_list(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 505, in get_app_list app_dict = self._build_app_dict(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 450, in _build_app_dict has_module_perms = model_admin.has_module_permission(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\options.py", line 548, in has_module_permission return request.user.has_module_perms(self.opts.app_label) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 458, in has_module_perms return user_has_module_perms(self, module) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 221, in user_has_module_perms for backend in auth.get_backends(): File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 38, in get_backends return get_backends(return_tuples=False) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 27, in get_backends backend = load_backend(backend_path) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 21, in load_backend return import_string(path)() File "D:\PROJECTS\src\lib\site-packages\django\utils\module_loading.py", … -
Create folder and subfolder with django app
Maybe this is to trivial question, but please assist me. How can I create folder and subfolder in it with django python. When I google I just get some information about folder structure, but it is not what I am looking for. Please share some code examples if it is possible Many thanks. -
How can i make different login for buyer and seller ? then they will redirect their own profile
details about the questions .................................................................................................................................................................................................... ##I follow this post same to same. ###https://areebaseher04.medium.com/how-to-implement-multiple-user-type-registration-using-django-rest-auth-39c749b838ea ''' ##core/models.py) from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): #Boolean fields to select the type of account. is_seller = models.BooleanField(default=False) is_buyer = models.BooleanField(default=False) class Seller(models.Model): seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) area = models.CharField(max_length=100) address = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.seller.username class Buyer(models.Model): buyer = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.CharField(max_length=100) def __str__(self): return self.buyer.username #serializers.py from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from rest_framework.authtoken.models import Token from core.models import Seller, Buyer class SellerCustomRegistrationSerializer(RegisterSerializer): seller = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False area = serializers.CharField(required=True) address = serializers.CharField(required=True) description = serializers.CharField(required=True) def get_cleaned_data(self): data = super(SellerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'area' : self.validated_data.get('area', ''), 'address' : self.validated_data.get('address', ''), 'description': self.validated_data.get('description', ''), } data.update(extra_data) return data def save(self, request): user = super(SellerCustomRegistrationSerializer, self).save(request) user.is_seller = True user.save() seller = Seller(seller=user, area=self.cleaned_data.get('area'), address=self.cleaned_data.get('address'), description=self.cleaned_data.get('description')) seller.save() return user class BuyerCustomRegistrationSerializer(RegisterSerializer): buyer = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False country = serializers.CharField(required=True) def get_cleaned_data(self): data = super(BuyerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'country' : self.validated_data.get('country', ''), } data.update(extra_data) return data def save(self, request): user = super(BuyerCustomRegistrationSerializer, self).save(request) user.is_buyer = True … -
Comment POST request working but comments not appearing under post
I'm relatively new to all this. I'm in the process of creating a social media page with django/python. The ability to create a post in a news feed (i.e. list of posts) and the ability to click on one post to see a more detailed view is working properly. When a user clicks on a single post to see it in more detail they also have the ability to add a comment.Here's the problem: the 'create a comment' input box is working fine, as is the 'post comment' button, but when you click the 'post comment' button my terminal does show that the comment is being posted, but the list of comments never appears. What appears in my Powershell/Terminal when I click the 'post comment' button: [DD/MONTH/2022 HH:MM:SS] "POST /social/post/5 HTTP/1.1" 200 3995 screenshot of what appears on my website my settings.py installed apps: INSTALLED_APPS = [ 'social', 'landing', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_bootstrap5', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.facebook', ] my views.py: from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.views import View from django.views.generic.edit import UpdateView, DeleteView from .models import Post, Comment from .forms import PostForm, CommentForm class … -
Django corsheaders not affecting staticfiles - CORS errors only on static content
I've been successfully using CORS_ORIGIN_ALLOW_ALL = True with my views and I have been able to serve Django views to other domains, no problem. Now, I replaced a call to view to just getting a static file, and this is failing with a CORS error. This is not a problem in production, because I don't use Django to serve static files in production. Yet, how can I enable CORS_ORIGIN_ALLOW_ALL for staticfiles in development? -
digital ocean deployment error: 502 Bad Gateway
I had my site up and running, but the admin CSS was not loading, I am not sure what I did that the server did not agree, but now the entire site is down with a 502 Bad Gateway message. Here are the content of some key files sudo nano /etc/systemd/system/gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service file (sudo nano /etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=eson Group=www-data WorkingDirectory=/home/eson/example ExecStart=/home/eson/example/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ example.wsgi:application [Install] WantedBy=multi-user.target Here is what Nginx has sudo nano /etc/nginx/sites-available/example: server { server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/eson/example; } location /media/ { root /home/eson/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.example.com example.com; return 404; # managed by Certbot … -
Django Can't recreate Database table?
Unfortunately I deleted two database table from my phpmyadmin database, I deleted migration file from corresponding app, and run this two command python manage.py makemigrations app_name python manage.py migrate But still cant recreate my database table. how to fix this issue? -
Django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net'
After starting project django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' or FileNotFoundError: [Errno 2] No such file or directory: '/proc/5390/task/56199' Full trace of OSError: 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 "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/lib/python3.8/pathlib.py", line 1140, in glob for p in selector.select_from(self): File "/usr/lib/python3.8/pathlib.py", line 587, in _select_from for p in successor_select(starting_point, is_dir, exists, scandir): File "/usr/lib/python3.8/pathlib.py", line 535, in _select_from entries = list(scandir_it) OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' Trace of …