Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save multiple values in one field (Django)
The problem: I have a model, which is referencing the basic User model of django. Right now, if I submit the form Django updates my database by replacing the existing data with the new one. I want to be able to access both of them. (In weight and date field) Models file: I saw other posts here, where they solved a problem by specifying a foreign key, but that doesn't solve it for me. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) date = models.DateField(auto_now_add=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Views file: This is where I save the data that I get from my form called WeightForm from django.shortcuts import render from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from .forms import WeightForm def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, … -
Graphite Browser "Exception Value: attempt to write a readonly database"
Well, i got into graphite and graphite-web and got stuck at the "Exception Value: attempt to write a readonly database" Error. I already tried chmod and chown at the db itself and im still getting this Error. File is under /opt/graphite/storage/graphite.db it got rwx-rwx-rwx (chmod 777) perms and i tried www-data as owner and put root back at it cause it got the same error. Environment: Request Method: GET Request URL: http://IP:8000/composer Django Version: 1.8.18 Python Version: 2.7.16 Installed Applications: ('graphite.account', 'graphite.browser', 'graphite.composer', 'graphite.dashboard', 'graphite.events', 'graphite.functions', 'graphite.metrics', 'graphite.render', 'graphite.tags', 'graphite.url_shortener', 'graphite.whitelist', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'tagging') Installed Middleware: ('graphite.middleware.LogExceptionsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.gzip.GZipMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/graphite/webapp/graphite/composer/views.py" in composer 27. profile = getProfile(request) File "/opt/graphite/webapp/graphite/user_util.py" in getProfile 35. return default_profile() File "/opt/graphite/webapp/graphite/user_util.py" in default_profile 51. 'password': '!'}) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in manager_method 127. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in get_or_create 407. return self._create_object_from_params(lookup, params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _create_object_from_params 439. obj = self.create(**params) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in create 348. obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save 734. force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 762. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in _save_table 846. result = self._do_insert(cls._base_manager, … -
Hy i have a problem in my django app sohow i can solve it you will see all of the requireddocuments in the desc
Hy guys i'm achraf chahin a beginner web developer so i have a problem in my django app so it's a school management system that give courses exercices also link of live streams but there is a problem in my app even if the file is stored in my static files it giving me file not found i don't know what is the problem here some pics [This Images][1] [1]: https://i.stack.imgur.com/62sZW.png [This Images][2] [2]: https://i.stack.imgur.com/L5zlO.png [This Images][3] [3]: https://i.stack.imgur.com/9OIaj.png [This Images][4] [4]: https://i.stack.imgur.com/jOHcA.png [This Images][5] [5]: https://i.stack.imgur.com/i1Nj7.png [This Images][6] [6]: https://i.stack.imgur.com/MzRDQ.png [This Images][7] [7]: https://i.stack.imgur.com/lWjV3.png please help your answers will really gonna help me and others like me a lot -
looking for the best economic solution to deploy a flask application on the web. if you have any suggestion (MVC flask with JWT token ) please advice
looking for the best economic solution to deploy a flask application on the web, and also wants to know the deployment process. I am a beginner in python and flask, if you have any good structural suggestion (MVC in the flask with JWT token ) for API will be helpful. -
Summing up total amount from multiple models in Django
The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code class FurnitureItem(models.Model): fur_title = models.CharField(max_length=200) fur_price = models.FloatField() fur_discount_price = models.FloatField(blank=True, null=True) fur_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) fur_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.fur_title class FurnitureOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_ordered = models.BooleanField(default=False) item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.fur_title}" .... def get_final_fur_price(self): if self.item.fur_discount_price: return self.get_total_discount_fur_price() return self.get_total_item_fur_price() class FurnitureOrder(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) fur_items = models.ManyToManyField(FurnitureOrderItem) date_created = models.DateTimeField(auto_now_add=True) ordered_created = models.DateTimeField() fur_ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total_fur_everything(self): total = 0 for fur_order_item in self.fur_items.all(): total += fur_order_item.get_final_fur_price() return total class GraphicItem(models.Model): graphic_title = models.CharField(max_length=200) graphic_price = models.FloatField() graphic_discount_price = models.FloatField(blank=True, null=True) graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True) label = models.CharField(choices=LABEL_CHOICES, max_length=1) category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24) graphic_descriptions = models.TextField() slug = models.SlugField() date = models.DateTimeField(default=timezone.now) def __str__(self): return self.graphic_title class GraphicOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) graphic_ordered = models.BooleanField(default=False) item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.graphic_title}" .... def get_final_graphic_price(self): if self.item.graphic_discount_price: return self.get_total_discount_graphic_price() return … -
i have erroe ith paginating in django
hi im trying to use django paginator but i get 404 error i want to reach to this url http://127.0.0.1:8000/products/2/?page=1 but i get 404 error where is the problem ?please help me views.py from django.core.paginator import Paginator, EmptyPage, InvalidPage def sort(request, value): category = Category.objects.all() if(value=='2'): products_list = Product.objects.all().order_by('price') elif(value=='3'): products_list = Product.objects.all().order_by('-price') elif(value=='4') : products_list = Product.objects.all().order_by('-id') elif (value == '5'): products_list = Product.objects.all().order_by('-view') paginator = Paginator(products_list,5) try: page=int(request.GET.get('page','1')) except: page = 1 try: products = paginator.page(page) except(EmptyPage,InvalidPage): products = paginator.page(paginator.num_pages) context = { 'products': products, 'category': category, 'value' : value } return render(request, 'shopPage.html', context) urls.py path('products/<value>', views.sort, name='sort'), shopPage.html <div> <ul> {% if products.has_previous %}> <li><a href="products/?page={{ products.previous_page_number }}">previous</a></li> {% endif %} {% for pg in products.paginator.page_range %} {% if products.number == pg %} <li class="active"><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% else %} <li><a href="products/?page{{ pg }}">{{ pg }}</a></li> {% endif %} {% endfor %} {% if products.has_next %} <li><a href="products/?page={{ products.next_page_number }}">next</a></li> {% endif %} </ul> </div> -
Update multiple rows with Django (different ids) using different values for each id (as keys)
Let's say I have a model: I have some items: grocery = { status : True, fruits: ['1', '23', '55'], comments: {'1': "test", '23': "test2", '55': ""} I have a rough potential Django update query: Fruit.objects.all().filter(id__in=grocery.get('fruits')).update(status=grocery.get('status'), comment=grocery.get('comments')) I'm successfully updating the status but I want to dynamically update the comments so that if the Fruit object in question has, for example, id: 23, the fruit comment will be test2, or if the object has 'id: 55' it will be '' -
Django - Date problem in CRUD application
I'm using flatpickr for date informations in my Django application. The problem is when I want to update worker informations, in edit.html page default value of birth_date is not displaying correctly. For example, I've created worker Xen who was born in 01-05-1997, and click to update his name, in birth_date input it displays today's date. Here are my codes: forms.py class WorkerForm(ModelForm): class Meta: model = Worker fields = "__all__" widgets = { 'birth_date': DateTimeInput(format='%Y-%m-%d %H:%M:%S', attrs={'class':'datetimefield'}) } models.py: class Worker(models.Model): ... birth_date = models.DateTimeField(blank=True, null=True) edit.html: ... <div class="form-group row"> <label class="col-sm-2 col-form-label">İşçinin doğum tarixi</label> <div class="col-sm-4"> <input class="datetimefield" type="date" name="birth_date" id="birth_date" value="{{ worker.birth_date }}" /> </div> </div> ... <script> window.addEventListener("DOMContentLoaded", function () { flatpickr(".datetimefield", { enableTime: true, enableSeconds: true, dateFormat: "Y-m-d H:i:S", time_24hr: true, locale: "az", }); }); </script> -
i got this Error TypeError at / Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models
i got this Error Twitter() missing 4 required positional arguments: 'pwd', 'path', 'desc', and 'speed' i don't create models import os from time import sleep from flask import Flask, render_template, request from selenium import webdriver from werkzeug.utils import secure_filename def Twitter(user, pwd, path, desc, speed): if user: driver = webdriver.Chrome( executable_path=r"C:\Users\pc\Downloads\chromedriver.exe" ) driver.get("https://twitter.com/login") user_box = driver.find_element_by_class_name( "js-username-field" ) user_box.send_keys(user) # password pwd_box = driver.find_element_by_class_name( "js-password-field" ) pwd_box.send_keys(pwd) login_button = driver.find_element_by_css_selector( "button.submit.EdgeButton.EdgeButton--primary.EdgeButton--medium" ) login_button.submit() sleep(speed) # Attach-Media img_box = driver.find_element_by_css_selector( "input.file-input.js-tooltip" ) img_box.send_keys(path) sleep(speed * 3) # Discription text_box = driver.find_element_by_id( "tweet-box-home-timeline" ) text_box.send_keys(desc) # Tweet tweet_button = driver.find_element_by_css_selector( "button.tweet-action.EdgeButton.EdgeButton--primary.js-tweet-btn" ) tweet_button.click() sleep(speed * 5) driver.refresh() driver.close() return 1 pass -
Email Verification in Django when a new user signs up
I am creating a user registration page for my website. I want to send an email verification mail to the mail the user inputs while registering. I tried many solutions but nothing seems to work for me. My code: views.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'Home/register.html', context) def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') return redirect('login') context = {} return render(request, 'Home/login.html', context) forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password1", "password2"] -
Django how the query GenericForeignKey relation(s)?
I want to display my users the content they have already brought by the "my_purchases" view (see below). For each object the user buy's a license is getting created and placed at the Licenses model: licensable_models = models.Q(app_label='App', model='model1') | \ models.Q(app_label='App', model='model2') class Licenses(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=licensable_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') license_holder = models.ForeignKey(User, verbose_name="License Holder", on_delete=models.CASCADE, null=True) paid_amount_usd = models.DecimalField(verbose_name="License Price (USD)", max_digits=8, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))], null=False) paid_date = models.DateTimeField(auto_now=True) class Meta: verbose_name = "License" verbose_name_plural = "Licenses" ordering = ['-paid_date'] Creating a license and accessing the content after payment works fine! I expect that there is no buggy code but I currently don't really understand how I can create a query to grab all related objects the user has already brought and a license as been created. views.py def my_purchases(request): user = User.objects.get(pk=request.user.pk) template = 'App/my_purchases.html' if request.method == 'GET': list_my_purchases = sorted( chain( < how does this query have to look like? > ), key=attrgetter('paid_date'), reverse=True ) paginator = Paginator(list_my_purchases, 10) # Show 10 purchases per page page = request.GET.get('page') my_purchases = paginator.get_page(page) args = {'user': user, 'my_purchases': my_purchases, } return render(request, template, args) At each of my Model1 and Model2 (mentioned … -
Django password reset _getfullpathname error
I am trying to set up a password reset form but I get the following error after trying to send an email, weirdly I noticed that if I put email that doesn't match any of the emails provided by users it works, error only occurs when email matches one provided by a user. Error: TypeError at /password_reset/ _getfullpathname: path should be string, bytes or os.PathLike, not NoneType urls.py from django.contrib.auth import views as auth_views #import this urlpatterns = [ ... path('accounts/', include('django.contrib.auth.urls')), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), path("password_reset/", views.password_reset_request, name="password_reset"), ] views.py def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "registration/password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com' , [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ("/password_reset/done/") password_reset_form = PasswordResetForm() return render(request=request, template_name="registration/password_reset_form.html", context={"password_reset_form":password_reset_form}) password_reset_form.html {% extends 'base.html' %} {% block content %} <!--Reset Password--> <div class="container p-5"> <h2 class="font-weight-bold mt-3">Reset Password</h2> <hr> <p>Forgotten your password? Enter your email address below, and we'll email … -
Django rest raising error "The submitted data was not a file. Check the encoding type on the form." to angualar Http Client
The are any solutions to the problem but m not able to find the root cause and also to mention no of the solution is working in my case. What I am trying to do is to upload a file to Django rest API from a angular Http Client Service. I am taking up the input form the user passing to the service at the end I have declared a type specific for the type of model I am creating an object for but I am not getting the same error again and again. I read some where that Django file uploader doesn't understand some char-set format but I still can't understand whats wrong with it. ``` var report = <CompleteReport> { title:'heelo', description:'sdfsdfs', author: 'report', article_upload_images: [uuid4(),], presentation_upload_images: [uuid4(),], report_article: article_object, report_image: image_object, report_podcast: podcast_object, report_presentation: presentation_object, report_video: video_object }; let headers = new HttpHeaders({ 'Accept': 'application/json' }); let options = {headers: headers}; return this.http.post<any>(url, report, options) -
How to pass Django view's data to jquery?
I want to pass page object data to jquery to print next and previous page. I used json.dumps(page), but it didn't workout, getting error. I used django pagination but on click next and previous buttons the page is reloading. so, i am trying using jquery. How to solve this, please suggest me. views.py: def render_questions(request): questions = Questions.objects.all() p = Paginator(questions, 1) page = request.GET.get('page', 1) try: page = p.page(page) except EmptyPage: page = p.page(1) return render(request, 'report.html', {'ques': page}) template.html: <form id="myform" name="myform" action="answer" method="POST"> {% csrf_token %} <div class="divs"> <div class="questionscontainer"> {% for question in ques %} <h6>Q &nbsp;&nbsp;{{ question.qs_no }}.&nbsp;&nbsp;<input type="hidden" name="question" value="{{ question.question }}">{{ question.question }}</h6> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_a}}">&nbsp;&nbsp;&nbsp;A)&nbsp;&nbsp;{{ question.option_a }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_b}}">&nbsp;&nbsp;&nbsp;B)&nbsp;&nbsp;{{ question.option_b }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_c}}">&nbsp;&nbsp;&nbsp;C)&nbsp;&nbsp;{{ question.option_c }}</label> </div> <div class="radio pad"> <label><input type="radio" name="answer" value="{{question.option_d}}">&nbsp;&nbsp;&nbsp;D)&nbsp;&nbsp;{{ question.option_d }}</label> </div> {% endfor %} </div> </div> <ul class="pagination"> <li><a class="button" id="prev">prev</a></li> <li><a class="button" id="next">next</a></li> <input type="submit" value="Submit" onclick="submitTest()" class="button"> </ul> </form> script: I need to get the page object in my script and i should print one by one question using next and previous buttons. $(document).ready(function(){ $(".divs .questionscontainer").each(function(e) { if (e … -
nginx directory forbidden using passenger_wgsi.py with django
I am trying to configure plesk with django nginx , I am using my vps with centos 8 and plesk 18 . I am getting 403 forbidden error . If a place index.html it works but it is not working with passenger_wsgi.py file this is my server log proxy_error logs 020/10/22 10:30:28 [error] 119522#0: *49 directory index of "/var/www/vhosts/xxx.com/httpdocs/djangoProject/" is forbidden, client: 162.158.165.181, server: xxx.com, request: "GET / HTTP/1.1", host: "xxx.com" error logs [Thu Oct 22 08:49:00.606752 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name [Thu Oct 22 08:49:00.632957 2020] [ssl:warn] [pid 84873] AH01909: xxx.com:443:0 server certificate does NOT include an ID which matches the server name passenger file code import sys, os ApplicationDirectory = 'djangoProject' ApplicationName = 'djangoProject' VirtualEnvDirectory = 'venv' VirtualEnv = os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin', 'python') if sys.executable != VirtualEnv: os.execl(VirtualEnv, VirtualEnv, *sys.argv) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory)) sys.path.insert(0, os.path.join(os.getcwd(), ApplicationDirectory, ApplicationName)) sys.path.insert(0, os.path.join(os.getcwd(), VirtualEnvDirectory, 'bin')) os.chdir(os.path.join(os.getcwd(), ApplicationDirectory)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', ApplicationName + '.settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() nginx.conf user root; worker_processes 1; #error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; #pid /var/run/nginx.pid; include /etc/nginx/modules.conf.d/*.conf; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr … -
Django: Extending base.html in django admin
I've a base.html file which has vertical and horizontal menu-bar: Wherever I want to use that I just simply write: {% extends 'base.html' %} {% block content %} //html code {% endblock content %} But I don't know how to use the same file base.html from templates directory in djando admin. I want output like this: What I Tried: How to override and extend basic Django admin templates? How do I correctly extend the django admin/base.html template? Override Navbar in Django base admin page to be same as the base.html -
Django save user and profile with signals
Im still learning Django and I am stuck at user registration / profile creation. My goal So, the purpose of this is to save the new user and at the same time save the profile of the new user with de data from the form. I use 2 forms u_form and p_form. What I have done so far: Created model Profile with OneToOneField to User Created 2 forms for User (u_form) and Profile (p_form) Created signals.py to create new Profile when new User is created In the view I have create function with u_form.save() Problem This works, but the new Profile is completely empty.. When I put p_form.save() in my view it gives me this error: NOT NULL constraint failed The code models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) voorletter = models.CharField(max_length=10) voorvoegsel = models.CharField(max_length=10) achternaam = models.CharField(max_length=200) depers = models.CharField(max_length=25) depersoud = models.CharField(max_length=25) telefoonnummer = models.CharField(max_length=25) class Meta: verbose_name = "Collega" verbose_name_plural = "Collega's" def __str__(self): return self.depers signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if … -
Django does not gracefully close MySQL connection upon shutdown when run through uWSGI
I have a Django 2.2.6 running under uWSGI 2.0.18, with 6 pre-forking worker processes. Each of these has their own MySQL connection socket (600 second CONN_MAX_AGE). Everything works fine but when a worker process is recycled or shutdown, the uwsgi log ironically says: Gracefully killing worker 6 (pid: 101)... But MySQL says: 2020-10-22T10:15:35.923061Z 8 [Note] Aborted connection 8 to db: 'xxxx' user: 'xxxx' host: '172.22.0.5' (Got an error reading communication packets) It doesn't hurt anything but the MySQL error log gets spammed full of these as I let uWSGI recycle the workers every 10 minutes and I have multiple servers. It would be good if Django could catch the uWSGI worker process "graceful shutdown" and close the mysql socket before dying. Maybe it does and I'm configuring this setup wrong. Maybe it can't. I'll dig in myself but thought I'd ask as well.. -
Error 502 with conflicting server name and (2: No such file or directory)
Mywebsite.co.uk displays a 502 Error. Running sudo tail -F /var/log/nginx/error.log outputs: 2020/10/22 09:42:13 [warn] 200096#200096: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:13 [warn] 200107#200107: conflicting server name "mywebsite.co.uk" on 0.0.0.0:80, ignored 2020/10/22 09:42:29 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:42:50 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:42:51 [crit] 200110#200110: *4 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 37.70.203.239, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "xxx.xx.xxx.xxx" 2020/10/22 09:43:00 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:43:24 [error] 200110#200110: *1 open() "/home/user/mywebsite-app/static/admin/css/fonts.css" failed (2: No such file or directory), client: 37.70.203.239, server: mywebsite.co.uk, request: "GET /static/admin/css/fonts.css HTTP/1.1", host: "mywebsite.co.uk", referrer: "http://mywebsite.co.uk/" 2020/10/22 09:57:01 [crit] 200110#200110: *10 connect() to unix:/home/django/gunicorn.socket failed (2: No such file or directory) while connecting to upstream, client: 103.42.252.150, server: _, request: "GET / HTTP/1.0", … -
How to add part of the path before the language code for django translate i18n
How to add part of the path before the language code for django i18n_patterns ? Example: my project is located at: http://domain.site/sub/admin/ When changing the language, a redirect to http://domain.site/`en`/sub/admin/ occurs automatically , but me need to so http://domain.site/sub/`en`/admin/. Thanks! urls.py code: urlpatterns = i18n_patterns ( ... path ('admin /', admin.site.urls), ... prefix_default_language = False, ) settings.py code: LANGUAGES = [ ('en', _ ('English')), ('ru', _ ('Russian')), ] i18n_switcher.py: from django import template from django.template.defaultfilters import stringfilter from django.conf import settings register = template.Library() def switch_lang_code(path, language): lang_codes = [c for (c, name) in settings.LANGUAGES] if path == '': raise Exception('URL path for language switch is empty') elif path[0] != '/': raise Exception('URL path for language switch does not start with "/"') elif language not in lang_codes: raise Exception('%s is not a supported language code' % language) parts = path.split('/') if parts[1] in lang_codes: parts[1] = language else: parts[0] = "/" + language return '/'.join(parts) @register.filter def switch_i18n(request, language): """takes in a request object and gets the path from it""" return switch_lang_code(request.get_full_path(), language) html link for change language <a href="{{ request|switch_i18n:'en' }}"> <img class="i18n_flag" src="{% static 'images/lang-en.svg' %}"/> </a> / <a href="{{ request|switch_i18n:'ru' }}"> <img class="i18n_flag" src="{% static 'images/lang-ru.svg' %}"/> … -
How to resolve JSONDecodeError at / in Django
This is my code I have been using views.py from django.shortcuts import render import requests from django.http import HttpResponse def form(request): return render(request,'hello/index.html') def home(request): a=request.POST.get("num") if not a: a=0 response = requests.post('http://127.0.0.1:5000/index'+ str(a)).json() return render(request, 'hello/index.html', {'out': response['out']}) index.html <!DOCTYPE html> <html> <body> <form action ="home" method="POST"> {% csrf_token%} <label for ="num">Your number: </label> <input type="text" name="num"> <input type ="submit" > </form> <div> {{ out }} </div> </body> </html> I am getting JsonDecoder error for these code I dont know how to solve it -
Django get fields of the ForeignKey Model efficiently?
I am using django-rest-framework as backend and react as a frontend For example if I have the following tables in Django class Master1(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Master2(models.Model): field1 = models.CharField(max_length = 100) field2 = models.CharField(max_length = 100) field3 = models.CharField(max_length = 100) class Transaction(models.Model): master1 = models.ForeignKey(Master1) master2 = models.ForeignKey(Master2) title = models.CharField(max_length = 100) I want to create a view for the Trasaction that displays several fields from each of its related models in frontend. Can someone suggest an efficient way of doing that. Should I just define the fields it needs in the view or should I use nested serializers? -
WSGI/Django 1.8 No handlers could be found for logger "django.request"
I wanted to try out graphite+graphite-web and followed this guide here: https://www.metricfire.com/blog/install-graphite-common-issues/#Log-rotation after that i got some errors and fixed a few of them! but now i got stuck at that one: On the website from graphite-web i get this error: graphite-web In the error.logs i have this error: error.log This are my wsgi.py settings: wsgi.py This are my apache2 settings: apache2-graphite.conf If u need anything else, let me know! -
AMQP service: how to check if running, stop and start it
I have an old Django app using celery==3.1.18 and amqp==1.4.9. I am trying to replace amqp with rabbitmq but I need to understand how the old system works. I cannot find any documentation helping me with this task. How do I check status, stop, start amqp services? Any link to documentation explaining how to move from amqp to rabbitmq will be greatly appreciated. Thank you. -
Invisible output in postgreSQL using jsonb
Only the table "checks_check" experiences this. It's not only invisible, there is actually no output to work with. The table was create by django 1.11. Terminal