Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting a timer for players in an online game in Django [closed]
I am implementing an online poker game with Django. Each player in the game has a certain amount of time to perform an action. What solution do you suggest for placing this timer? For this project, I am using Django Channel and WebSocket, and the scheduling work is done there -
Accessing Django on a secondary device
I am trying to access Django from a secondary device i.e. android phone. I have made sure that The laptop I am running Django on is connected to the same network as my secondary device. I have turned off the firewall on my laptop I configured CSRF to accept POST requests a trusted origin in settings.py Thereafter running python manage.py runserver 0.0.0.0:8000 , the POST requests on my website works when I access it from the laptop I am running Django from. However, when I use the same link http://192.168.16.130:8000/ on my phone, the POST requests don't work. import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.16.130', '127.0.0.1', 'localhost', '0.0.0.0'] # !!! Added for CSRF protection # CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_ALL_ORIGINS=True CORS_ALLOWED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://0.0.0.0:8000", "http://localhost:8000", "http://192.168.16.130:8000", "http://127.0.0.1:8000", ] CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # !!! Added for … -
Cookiecutter-django custom User field is never saved to DB
I'm struggling with a banal (I guess) issue with cookiecutter-django... I added the field invitation_code to users.models.User: class User(AbstractUser): """ Default custom user model for pintable. If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = CharField(_("Full name"), max_length=255, null=True, blank=True) first_name = None # type: ignore last_name = None # type: ignore invitation_code = CharField( _("Invitation code"), max_length=8, null=True, blank=True ) Then I added the same field to users.forms.UserSignupForm: class UserSignupForm(SignupForm): """ Form that will be rendered on a user sign up section/screen. Default fields will be added automatically. Check UserSocialSignupForm for accounts created from social. """ invitation_code = CharField( label=_("Invitation code"), widget=TextInput(attrs={"placeholder": _("Invitation code")}), ) The problem is that when a new user is saved to DB, the invitation_code field is always None. What am I missing..? Thanks for your help! -
How to auto create foreingKey object (python with django)
I'm creating a simple rest api This is my actual result from devices, i create first the group and options, and then associate, but i want to create the options at the same time i create the device. My result from devices right now [ { "id_device": "a099d2ce-812b-4d85-8c8b-cfe71057fbe7", "group": { "id_group": "39407ef6-1a3e-4965-9b61-96f6c40b76b3", "name": "Cozinha" }, "options": [ { "id_option": "1b383a37-5229-4ae0-9649-f76aa32eeda0", "name": "1", "identifier": "POWER1" }, { "id_option": "4ff5406a-8c7b-4517-9ec0-14fd4f68f30b", "name": "2", "identifier": "POWER2" }, { "id_option": "a541216d-f509-4461-85ca-444491ac9217", "name": "3", "identifier": "POWER3" }, { "id_option": "3debe828-edd6-4d83-bfd8-2776a1594380", "name": "4", "identifier": "POWER4" } ], "name": "Interruptor 4", "identifier": "identifiertest" }, ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id_option = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id_group = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id_device = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): … -
Structure Policy for Django / Python Libraries
Question Summary Hi Folks, This is a kind of opinion question, I've built a Django library for my company and I keep swithering and changing my mind on how to structure it. Possible strategies I've come up with are below: Method 1 - Individual Libraries Split all parts of the library into separate repos. For example my_library_core my_library_cookies my_library_exporter and include from them individually. Pros Each library is compartmentalised and can be updated or included individually, so you can include only some of the functionality and install only some of the library modules. Cons Dependencies / functionalities between libraries can get out of sync, if library one is using version 1 of the core library and library two is using version 2, you're forced to upgrade both to upgrade one. Lots of separate repos to keep on top of. Harder to have a reliable "core" library for common functionality. Feels messy / uncentralised. Method 2 - Monolithic Library Have one large library that contains all functionality. Pros Centralised, everything is referencing the same library. Dependencies are centralised, the whole library has one set of dependencies that apply to all sub apps. Neater, everything imports from a one library. Cons Upgrading … -
Can't make superuser: error no such column
Hi I try make superuser to login my admin panel but I recieved this error while making superuser: django.db.utils.OperationalError: no such column: accounts_user.password1 and this is my model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(unique=True, max_length=10) email = models.EmailField() password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) is_publisher = models.BooleanField(default=False) def change_user_type(self): if self.is_publisher: self.is_superuser = True self.save() -
Handling concurrent user in Django + PostgreSql
I am creating a website which will take input from form and store it to database (PostgreSql) and the Input will be used for operation using python (eg: adding two numbers taken from form) and also there will be a button to take input from form again and previous given input will also be seen by a click. My question is : Let's say 100 users at same time comes to the website and filling the form, then in that case how should I handle the database, how to Store data each time from form so that It will not be an issue for other user and user can only see their previous input. I am new to development field, So I have no idea how to handle this. -
I am experiencing an error which comes anytime
I am experiencing an error which comes anytime i.e. sometime the code works fine but other time, this error occurs. I am working on login and signin project with minimalist html. The error is "Reason given for failure: CSRF token from POST incorrect." from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User from home.models import contactIssue from django.contrib.auth.forms import UserCreationForm def index(request): if (request.method=="POST"): if (request.POST.get('LoginButton','false')!='false'): return redirect('loginPage') else: return redirect('signinPage') return render(request, template_name="index.html") def loginFunc(request): if (request.method=='POST'): username = request.POST.get('username','Not found') password = request.POST.get('password','No password') print(username, password) try: user = User.objects.get(username=username) print(user) user = authenticate(request, username=username, password=password) if (user is not None): print("Login successful") login(request, user) return redirect('/loginPage') else: print("Login failed") except: print('No user found') return render(request, template_name='loginPage.html') def signinPage(request): # if (request.method=='POST'): # username = request.POST.get('username','Not found') # email = request.POST.get('email','No email') # password = request.POST.get('password','No password') # print(username, email, password) # return redirect('/') form = UserCreationForm(request.POST or None) if (request.method=="POST"): if (form.is_valid()): user = form.save() login(request, user) return redirect('/') return render(request, template_name='signPage.html', context={'form':form}) def logoutFunc(request): logout(request) return redirect('/') def contact(request): if (request.method=='POST'): username = request.user.username description = request.POST.get('description', 'No description') contactObject = contactIssue.objects.create(username=username, description=description) contactObject.save() print("contact submitted … -
Django how to compare stored hash password and plain password
I'm new to Django and I created function to allow admin to create users accounts. I used a password generator + make_password() function to hash the password. Now it's sending the plain password to users email and storing it in the database hashed. now the user is able to login with the hashed password only. my view.py: @admin_login_required def add_emp(request): if request.method == 'POST': user_name = request.POST['user_name'] user_email = request.POST['user_email'] user_otj = request.POST['user_otj'] user_password = pwo.generate() user_password1 = make_password(user_password) empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj) if empObj: subject = 'Advanced Analytics Portal - Login Info' message = f'Name : {user_name}, \n Email : {user_email}, \n Password : {user_password} \n FROM - AA Portal' email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [user_email]) messages.success(request, "Employee was added successfully!") return HttpResponseRedirect('/create-emp') else: messages.error(request, "Some error was occurred!") return HttpResponseRedirect('/create-emp') return render(request, 'AddEmp.html') def user_login(request): if request.method == "POST": user_email = request.POST['user_email'] user_password = request.POST['user_password'] user_details = User.objects.filter(user_email=user_email, user_password=user_password).values() if user_details: request.session['logged_in'] = True request.session['user_email'] = user_details[0]["user_email"] request.session['u_id'] = user_details[0]["user_email"] request.session['user_name'] = user_details[0]["user_name"] request.session['u_type'] = "emp" return HttpResponseRedirect('/user_index') else: return render(request, 'EmpLogin.html', {'msg': "0"}) else: return render(request, 'EmpLogin.html') Any idea how to make the user login with the plain password and keep it hashed in … -
Changing modelformset labels
I have created a modelformset for voting on multiple subtitles. It looks like this: I want to change the "Vote:" label to the names of the different subtitles instead (so if the subtitles are A, B and C, A should be before the first field, B for the second field etc.). How can I change this? The modelformset is created in the views.py like this: VoteFormSet = modelformset_factory(YesNoVote, form=YesNoVotingForm, extra=3) YesNoVotingForm looks like this: class YesNoVotingForm(forms.ModelForm): class Meta: model = YesNoVote fields = ['vote',] widgets = { 'vote': forms.Select(attrs={"required": True}), } and this is the yesnovote model: class YesNoVote(models.Model): subtitle = models.CharField(max_length=128) vote = models.CharField(choices=choices, max_length=10) user = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False, related_name="yesnovote_user", null=True) election = models.ForeignKey(YesNoElection, on_delete=models.CASCADE, related_name="yesnovote") def __str__(self): return f"{self.user} stemde {self.vote} bij {self.subtitle} (vallend onder {self.election})" and this is the html page: <form method="post"> {{ formset.management_data }} {% csrf_token %} {% for form in formset %} {{ form }} <br> {% endfor %} <button type="submit" name = "voting" class="btn btn-primary save">Submit</button> Let op: Je kunt je stem niet meer wijzigen. </form> -
fetch data from backend django and react
i'm trying to fetch data from my backend and i'm resiving this error "SyntaxError: Unexpected end of input" this my react app import './App.css'; import { useState, useEffect } from 'react'; function App() { const [articles, setArticles] = useState([]) useEffect(() => { fetch('http://127.0.0.1:8000/api/users/', { mode: 'no-cors', 'method':'GET', headers: { 'Content-Type':'application/json', 'Authorization':'token 2e8bfe0b7ff1716c0c255ac62adad9d9832e7173' } }) .then(resp => resp.json()) .then(resp => setArticles(resp)) .catch(error => console.log(error)) }, []) return ( <div className="App"> {articles.map(article => { return ( <h2>{article.first_name}</h2> ) })} </div> ) } export default App; -
Protection of Django Rest Framework API with AllowAny permission
I have a full-stack app and I am taking measures to protect the application from DDOS or bot attacks. All the sensitive data is protected by IsAuthenticated permission but there are still open APIs with public data with AllowAny permissions. I have so far added throttling and limited the request rate to 100 for both anonymous and authenticated users and on the frontend side I've added Captcha to protect the server from mass user registration, what are more ways to protect the server? REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("accounts.authentication.Authentication",), # "EXCEPTION_HANDLER": "accounts.custom_exception_handler.custom_exception_handler" 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/minute', 'user': '100/minute' } } -
How to check whether the database is closed in django
from django.db import connections from django.db.utils import OperationalError db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True In server I have not close the connection but unable to update the query it shows the db connection is closed. Is there any solution in django to check whether the database is closed -
how can I solve UNIQUE constraint failed: core_labor.id? I used shortuuid to generate uid?
from django.db import models from django.utils import timezone # Create your models here. class Labor(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=256) created_at =models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(auto_now=True) def __str__ (self): return f"Name: {self.name}" This is the serializers from rest_framework import serializers from ..models import Labor class LaborSerializer(serializers.ModelSerializer): class Meta: model = Labor fields = ['name'] This is the views from ..serializers.labor_serializers import LaborSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from ..models import Labor from django.utils import timezone from django.http import Http404 from rest_framework.permissions import IsAuthenticated from ..utils.utilities import generate_uuid generate_uid = generate_uuid() class LaborDetailViews(APIView): def get_labor(self, pk): try: return Labor.objects.filter(pk=pk) except Labor.DoesNotExist: raise Http404 def get(self, request, pk ): labor = self.get_labor(pk) serializer = LaborSerializer(labor ,many = True) return Response(serializer.data) def post(self, request): serializer = LaborSerializer(data = request.data) if serializer.is_valid(): Labor.objects.create(id = generate_uid, name = request.data['name'],modified_at = timezone.now()) labor = Labor.objects.filter(id= generate_uid).values() return Response ({"Message": "New Labor Status Added!", "Labor": labor, "Errors": serializer.errors}) I can't create new labor unless I reload the localhost server. When I use postman and try to add new labor(model) it throws me an error. which is that -
cart_total_amount showing 0 in django-shopping-cart
I have added cart.context_processor.cart_total_amount in settings.py But when i use it in the template it shows 0 I was expecting the total cart amount so want to know why the total cart amount is not showing up in {{cart_total_amount}} -
Django restarted (trigger file change) on every request when using runserver_plus
Django always detect file changes on every request on development mode. it was restarting even though i didn't make any change at all on the code. for a simple view this is not causing a problem. the process of rendering one page done before restart triggered. but if i have more complex logic in view, django restarted before the process of rendering a page completed. is any body know is this an expected behaviour? and why this is happened? how can i solve my problem? render a complex logic before django restarted. Is there are a way to disable that false positive trigger of file change? -
Try to make input file Not Required but it still Required in Django Python
Hi im still learning django and python, i made function to upload file, but i want the file is not required. heres my code: model.py class Ticket(models.Model): status = models.CharField(max_length=20, default="Pending") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) docfile = models.FileField(upload_to='attachments/file/%Y/%m/%d/%P', blank=True, null=True) views.py def new_ticket(request): form = TicketForm() if request.method == 'POST': form = TicketForm(request.POST, request.FILES) if form.is_valid() : form = form.save(commit=False) form.owner = request.user form.save() if form.docfile == 'docfile' : newdoc = TicketForm(docfile=request.FILES['docfile']) newdoc.save() return redirect('helpdesk:dashboard') documents = Ticket.objects.all() return render(request, 'helpdesk/new_ticket.html', {'form':form,'documents':documents}) forms.py class TicketForm(forms.ModelForm): status = forms.CharField(required=True) docfile = forms.FileField(required=False) class Meta: model = Ticket fields = ('status', 'docfile') new_ticket.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="status">Status</label> {% render_field form.status class="form-control"%} </div> <div class="form-group"> <label for="docfile">File Upload: </label> {% render_field form.docfile required=false class="form-control" %} </div> <hr> <input class="form-group button_main btn-lg" type="submit" value="Send" style="border: 0px;"></form> i already tried some solutions from this link : Django ModelChoice field is set to required=False but is still required in the browser Django Make ContentType Not Required Django form always shows error "This field is required" Django TextField always is required, despite blank=True,Null=True Django - Form template throws "This field is required" for Imagefield but the input field still … -
Vue-loader not recognizing template tag in a django + vue + tailwind SPA
I'm trying to set up a Django + GraphQL + Vue + Tailwindcss project on Windows 11 that would use static files generated by webpack but I'm getting the following 2 errors on vue files when trying to run npm run serve: ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??clonedRuleSet-14.use[1]!./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js??clonedRuleSet-14.use[2]!./node_modules/vue-style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js!./src/index.css) Module build failed (from ./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js): SyntaxError (1:4) C:\Users\deteu\Development\django\application\frontend\src\index.css Unknown word > 1 | // style-loader: Adds some css to the DOM by adding a <style> tag | ^ 2 | 3 | // load the styles @ ./src/index.css 4:14-324 15:3-20:5 16:22-332 @ ./src/main.js 9:0-21 ERROR in ./src/views/ProfileView.vue Module Error (from ./node_modules/vue-loader/dist/index.js): At least one <template> or <script> is required in a single file component. @ ./src/router.js 16:19-52 @ ./src/main.js 10:0-33 20:8-14 The second error is different on npm run build: ERROR Error: Build failed with errors. Error: Build failed with errors. at C:\Users\deteu\Development\django\application\frontend\node_modules\@vue\cli-service\lib\commands\build\index.js:207:23 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:148:8 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\HookWebpackError.js:68:3 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Cache.shutdown (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Cache.js:150:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1225:15 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Compiler.close (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1218:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:147:16 at finalCallback (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:441:32) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:458:13 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:33:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) … -
Django admin display queryset
In my admin panel, i want to display the userdetail objects for users who meet specific requirements: premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) But its not working and its not display this on the admin page. Here is my full code: class UserDetailAdmin(admin.ModelAdmin): def show_premium_users(self, request, queryset): premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) self.message_user(request, f'{premium_users.count()} premium users found') queryset = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False) print(queryset) return queryset show_premium_users.short_description = 'Show Premium Users' search_fields = ('user__username',) actions = ('show_premium_users') admin.site.register(UserDetail, UserDetailAdmin) How can I make it so i display the userdetail objects that meet the premium requirement on my admin page? -
Django ModelForm as controller of model field validation
I have an authorization form, and I get an error - "already have a user with this email". I want to use the forms as a layer of validating the data. I now, that i can pass instance of CustomUser in my form, but i can`t do it. Need other solution. @require_http_methods(["POST"]) @not_logged_in_user_only() def auth(request: WSGIRequest): form = UserAARForm(data=request.POST) if not form.is_valid(): return JsonResponse({'status': 'error', 'message': f'{form.errors.as_json()}'}) else: service = AuthenticateAndAuthOrRegistrUser() service.execute(req=request, data=form.clean()) if service.errors: return HttpResponseServerError() return redirect("profile_page") class SoundHomeUsers(models.Model): email = models.EmailField( max_length=254, unique=True, validators=[UserEmailValidator().is_valid]) password = models.CharField( max_length=254, validators=[UserPasswordValidator().is_valid]) class UserAARForm(ModelForm): class Meta: model = SoundHomeUsers fields = ['email', 'password'] -
How do I make an auto increment field that references other model fields in Django?
I'm making an Author model and I need to create an automatically increasing field by writing Post: Class Author(models.Model): author_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) post_count = models.PositiveIntegerField(default=0, null=True) # This field! Class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) body = models.TextField() author = models.ForeignKey('Author', to_field="author_id", null=True, on_delete=models.SET_NULL, db_column="author") created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) How do I make it? -
Django 4.2 and NGINX - The page isn’t redirecting properly
I am trying to add ssl to my test django server that is on AWS. I followed a tutorial to add ssl with certbot, add the proxy_pass but I never got it to work, so after three days trying all kinds of things, I give up. Could you guys please have a look and let me know where I am wrong? I am also confused about the environment variables, $host is blank and so are the others, I am going to assume they should be populated? I know nothing about NGINX, sorry about the noob questions. server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 404; } server { listen 80; listen [::]:80; server_name techexam.hopto.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name techexam.hopto.org; ssl_certificate /etc/letsencrypt/live/techexam.hopto.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/techexam.hopto.org/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; include /etc/nginx/mime.types; charset UTF-8; location /static/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location /media/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header Host $host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Additional logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; error_page 502 /error_pages/502.html; location = /error_pages/502.html { internal; root /usr/share/nginx/html; } } } -
Gunicorn, serve VPS, can't load CSS to admin panel
Previously, I have never been involved in setting up and maintaining a VPS. I recently launched a project using ubuntu + nginx + gunicorn. Everything works fine, but the CSS are not loaded to admin panel. At first, not understanding what was the reason, I tried to install grappelli - without success. After I found information that gunicorn cannot load admin CSS. The solution I see is to configure nginx to render CSS to admin panel. However, I couldn't to set up nginx correctly when I tried to set up a server without gunicorn. As a result, the server gave the nginx stub and I couldn't log into the server (although nginx did not show any syntax errors) - I had to delete the server and set up a new one. Therefore, I ask for help: what needs to be written in the nginx configuration so that, in addition to transmitting traffic, it also gives the CSS of the admin panel? I will be grateful for any answer! -
Django docker: docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed
I want to deploy my django project with docker and uwsgi on windows 11, but get some errors. docker build . -t djangohw docker run -it --rm djangohw -p 8080:80 docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-p": executable file not found in $PATH: unknown. Dockerfile FROM python:3.9 ENV DEPLOY=1 WORKDIR /opt/tmp COPY . . RUN pip install -r requirements.txt EXPOSE 80 CMD ["sh", "start.sh"] start.sh python3 manage.py makemigrations board python3 manage.py migrate uwsgi --module=mysite.wsgi:application \ --env DJANGO_SETTINGS_MODULE=mysite.settings \ --master \ --http=0.0.0.0:0 \ --processes=5 \ --harakiri=20 \ --max-requests=5000 \ --vacuum requirements.txt django==4.1.3 django-cors-headers pytest pytest-django coverage uwsgi -
Form wont update home db page. django and python
My django project wont update my home db page with the information from the join.html page. My urls.py file from django.urls import path from . import views urlpatterns = [ path( '' , views.home, name ="home"), path('join',views.join, name ="join"), ] views.py from django.shortcuts import render from .models import PersonInfo from .forms import PersonInfoForm import csv from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage #from rest_framework.decorators import action #from rest_framework.response import Response # Create your views here. def home(request): all_members = PersonInfo.objects.all return render(request, 'home.html', {'all':all_members}) def join(request): if request.method == "POST": #console.log("hello") #if "submitButton" in request.POST: form = PersonInfoForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'join.html', {}) else: return render(request, 'join.html', {}) forms.py from django import forms from .models import PersonInfo class PersonInfoForm(forms.ModelForm): class Meta: model = PersonInfo fields = ['customerName','address','age','email','accountId'] models.py from django.db import models from django.utils.translation import gettext # Create your models here. class PersonInfo(models.Model): accountId = models.IntegerField(default=None) customerName = models.CharField(max_length = 50, default=None ) address = models.CharField(max_length = 50, default=None) email = models.EmailField(max_length = 200, default=None) age = models.IntegerField(max_length = 3, default=None) def __str__(self): return self.customerName + ' ' #return self.accountId class book(models.Model): accountId = models.IntegerField( ("Account_ID") ) customerName = models.CharField( ("Customer_Name"), max_length = 50, default=None …