Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view with related value in a list of list
I have a Creator and Listing model, in one of html template, I need to display the Listing attributes and the Creator attribute associated with it, I tried to get all unique creators and put that in set but my Listing is a list of lists, I need to get all attributes from both models which matches creator attribute and an element list of listing. I guess Django has a better approach for this, may be I am doing all wrong, here is what I tried so far. Model class Creator: first_name =models.CharField(max_length=200) last_name = models.CharField(max_length=200) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') class Listing: creator = models.ForeignKey(Creator, on_delete=models.PROTECT) View def index(request): creators = set() listings_by_creator = set() for e in Listing.objects.filter(is_published=True).select_related('creator'): creators.add(e.creator) if any(x != e.creator for x in listings_by_creator ): listings_by_creator.add(e) context = {'zipped_app_list': zip(listings_by_creator, creators)} template {% if zipped_app_list %} {% for list_of_listing,creator in zipped_app_list %} ............. Now I need to display creator value and item with creator value in list_of_listing -
How can a programmer help the black lives matter movement?
I’m guessing this will get removed but I figure y’all answer all my other programming questions so why not ask? Anyone know of ways a programmer can help support the mission of Black Lives Matter or other movements seeking equality? -
How to download videos from Telegram API to local storage in Django
I want to download videos from Telegram API to my local storage using Python -
Django-Taggit tables not being created in PostgreSQL
Adding django-taggit to an existing Django app using PostgreSQL for db. I've used the django-taggit library before with no problem (but with a SQLite db). Makemigrations and Migrate commands look like they complete fine, but no taggit tables are created in PostgreSQL (in SQLite, two tables are created -> taggit_tag and taggit_taggeditem). So something is blocking the table creation. Django version = 3.0.7 Django-Taggit version = 1.3.0 Taggit has been included in Django settings: THIRD_PARTY_APPS = [ "crispy_forms", "allauth", "allauth.account", "allauth.socialaccount", "taggit", "django_countries", ] and models.py for the app: from django.db import models from django.urls import reverse from django.conf import settings from autoslug import AutoSlugField from model_utils.models import TimeStampedModel from taggit.managers import TaggableManager class Quote(TimeStampedModel): quote = models.TextField( "Quote", blank=False, help_text='Quote text', ) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, ) author = models.ForeignKey( 'authors.Author', related_name="author_quotes", on_delete=models.PROTECT, blank=False, null=True, ) tags = TaggableManager() def get_absolute_url(self): return reverse( 'quotes:detail', args=[str(self.id)] ) def __str__(self): return self.quote admin.py for the app includes: from django.contrib import admin from .models import Quote # admin.site.register(Quote) class QuoteAdmin(admin.ModelAdmin): list_display = ( 'quote', 'author', 'creator', 'tag_list', ) fields = [ 'quote', 'author', 'creator', 'tags', ] def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): return u", ".join(o.name for o in … -
Django Download csv after post request
I want to create an endpoint, in this endpoint its possible to send POST request, if the POST request is validated, then the page download a csv I created the serializer form to make a easy validation of the data received My problem is that the csv its easy downloaded in a HttpResponse, but i need neccesary to make a endpoint and a validation of the data in a post request. This are my files #urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^hello-view/', views.HelloApiView.as_view()), ] Serializers #serializers.py from rest_framework import serializers class HelloSerializer(serializers.Serializer): """Serializes a name field """ name = serializers.CharField(max_length=100) seller_id = serializers.CharField(max_length=100) def validate_name(self, dob): UnitOfMeasureName = ["Each", "Grams", "Ounces", "Pounds", "Kilograms", "Metric Tons"] if dob in UnitOfMeasureName: return dob else: raise serializers.ValidationError('Wrong username') And the views files In this file i created the export function to try to export the csv data, but doesnt works import csv from django.shortcuts import render from django.http import HttpResponse from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from . import serializers class HelloApiView(APIView): def export(self, request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['First name', 'Last name', 'ID']) response['Content-Disposition'] … -
Django: violates not-null constraint on .create, However attribute is not part of that model
In Django, when trying to create a new record of my "Cast" model, I get the following error regarding the "image_cover" attribute. The problem is that "image_cover" is not a defined attribute of my "Cast" model. So I'm not sure where it's coming from. Any Help is appreciated! Thanks The Error: django.db.utils.IntegrityError: null value in column "image_cover" violates not-null constraint DETAIL: Failing row contains (33, FAKE CAST, 2020-06-11 00:34:59.421996+00, 2020-02-20 07:00:00+00, 1, 4, url, t, {}, null). ####BELOW IS A NOTE ``` 33 = *pk*, FAKE CAST = *name*, 2020-06-11 00:34:59.421996+00 = *modified_datetime*, 2020-02-20 07:00:00+00 = *created_datetime*, 1 = *book*, 4 = *created_by*, URL = *character_cast_url*, t = *public*, {} = *character_cast*, null = *aliases OR image_cover* ``` Details This error occurs as part of my coded application, but also when trying to create a "cast" via the built-in Django admin. For simplicity, I'll focus this question around the later. Probably Important: While "image_cover" is NOT part of the "Cast" model, The only place it does exist is as a charfield on the "Book" model (a foreign key on the "Cast" model). This seems slightly irrelevant, however, since when I create a cast via the Django Admin, I can simply … -
Replace or extend User model in Django 3 in custom model
I am trying to replace User model or Extend (not sure what indeed), in Django for being able to use authenticate() and decorators as @login_required and/or permissions in my methods. Why I am doing this? may you ask. Is because the Django project is not following the best practices or orthodox ways of the framework. Before me was another developer taking this kind of desicions. The project is in an advanced stage. Ok, my model is this (only this no Meta or anything more in this class): class UsuarioDiplomado(models.Model): nombres = models.CharField(max_length=50) apellidos = models.CharField(max_length=50) telefono = models.CharField(max_length=20) celular = models.CharField(max_length=20) correo = models.CharField(max_length=70) fecha_nacimiento = models.DateField() rol = models.ForeignKey("core.Rol", on_delete=models.PROTECT) activo = models.BooleanField(default=True) eliminado = models.BooleanField(default=False) password = models.CharField(max_length=20, default='123') hashusuario = models.CharField(max_length=100, default='') sucursal = models.ForeignKey("core.Sucursal", on_delete=models.PROTECT, default=1) this is the class that I want to use as extension of User class specifically the fields correo (email), and password in the settings.py I setup AUTH_USER_MODEL = 'colposcopia.UsuarioDiplomado', but as expected not working because lacks of the REQUIRED_FIELDS AttributeError: type object 'UsuarioDiplomado' has no attribute 'REQUIRED_FIELDS' I am not sure how can achive this? or what I need to do this. Can you shine some light please? -
Javascript Date unnecessarily adjusts for timezone
I am storing a date as a django DateField in my database. It simply looks like "2020-06-25" in the database. This string is returned from my api, and passed into a javascript "Date" as such: date = new Date(due_date) logging this date results in: Wed Jun 24 2020 17:00:00 GMT-0700 (Pacific Daylight Time) I don't care about the time, only the date. How do I get javascript Date to ignore the time, and not adjust for the difference in timezone between the DB and the local user? If a user sets the due date for a project in one timezone, I want every person to see the same due date. -
trying to make django load environment vars from a .env.local file using django-environ from within a venv
I keep getting this traceback (pythonApp) D:\task_trackv2>python manage.py makemigrations D:\task_trackv2\apps_config\settings.py D:\pythonApp\lib\site-packages\environ\environ.py:637: UserWarning: Error reading .env.local - if you're not configuring your environment separately, check this. warnings.warn( D:\task_trackv2\apps_config\settings.py D:\task_trackv2\apps_config\settings.py Traceback (most recent call last): File "D:\pythonApp\lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\pythonApp\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "D:\pythonApp\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "D:\pythonApp\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\pythonApp\lib\site-packages\django\core\checks\translation.py", line 60, in check_language_settings_consistent get_supported_language_variant(settings.LANGUAGE_CODE) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "D:\pythonApp\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\belkin\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked … -
Django day and time picker
I'm trying to build my first website with django,I've accomplished user registration and login so far but now I'm stuck: I want to show to the users a weekly calendar where they can pick a day and book a gym class. I tried to handle every week day like a form field but it didn't work. Any advice on how I should tackle this? I'm looking for something like an explanation/a tutorial and would avoid a github project, if possible. Thank you! -
Cannot modify/override templates for django-allauth and django-comments-xtd
I have a Django project using Wagtail CMS. I'm using django-allauth for user accounts and django-comments-xtd for handling comments on the blog. I want to modify the templates for both of these apps. I've followed directions for doing so from their respective documentation, tutorials, and answers here on SO, but nothing I've tried works. (For reference, these SO answers have not helped.): override templates in django-allauth How to override template in django-allauth? Unable to override django-allauth templates What I've done is copied the templates I wanted to modify from site-packages/allauth/templates/account and site-packages/django_comments_xtd/templates/comments and into my project's templates directory (project/mysite/templates/account and project/mysite/templates/comments, respectively). However, when I modify the copied templates in my project's templates directory, the changes are not reflected. For fun, if I delete the templates in the site packages directory, then I get an error saying the templates do not exist. What's strange is that the first place Django looks for the templates is in my project's templates directory (and they are there), yet I get the error. Also, if I modify the templates under site packages directory, the changes ARE reflected, but I know this is bad practice because if I update these packages, my changes will be … -
Why is Django adding an extra character to the table name of a legacy database?
I am following this_site for onboarding a legacy database. Though, irregardless of the method used Django is adding an extra character (an s) to the only table within a legacy sqlite database (table: Dogs). Screenshot below of the extra character: And my entire models.py below. Accessing the database through python's sqlite library I can query the table 'dogs' and get expected results where as querying 'dogss' yields the error "no such table: dogss". from django.db import models from datetime import datetime # Create your models here. class Tutorial(models.Model): tutorial_title = models.CharField(max_length=200) tutorial_content = models.TextField() tutorial_published = models.DateTimeField('date published', default=datetime.now()) def __str__(self): return self.tutorial_title class Dogs(models.Model): #id = models.AutoField(primary_key=True) date_of_death = models.TextField(db_column='Date of Death', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. land_of_birth = models.TextField(db_column='Land of Birth', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. registered_name = models.TextField(db_column='Registered Name', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. call_name = models.TextField(db_column='Call Name', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. breeder_name = models.TextField(db_column='Breeder_name', blank=True, null=True) # Field name made lowercase. registration_field = models.TextField(db_column='Registration#', blank=True, null=True) # Field name made lowercase. Field renamed … -
Not able to deploy Django properly on Cpanel (static part)
I tried all steps and commands to enable the static part when project deployed on Cpanel python app but I failed. Please help me out. Thanks in advance. Deployed: Deployed my codes on Cpanel on goDaddy Images which are visible are from imported from the Internet not from static file Expected: (On local machine) I'm able to open each tab in local but getting 404 error on deployed one. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse from django.http import HttpResponseRedirect from .forms import ManuForm def home(request): if request.method == 'GET': return render(request, 'manufacture_page/homepage.html', {'form': ManuForm()}) else: try: form = ManuForm(request.POST) if form.is_valid(): form.save(commit=True) messages.info(request, 'Thanks! Will contact you back.') return redirect(request.META['HTTP_REFERER']) else: print("IN ERROR") errmsg= str(form.errors) print(errmsg) if "Phone already exists" in errmsg: errmsg="Error!! Entered Number already exists!" elif "Enter a valid phone number" in errmsg: errmsg="Error!! Enter number with country code. (e.g. +917529984220)." else: errmsg="Error!! Bad data passed in!" messages.error(request,errmsg) # return render(request.META['HTTP_REFERER'], 'homepage.html', {'form': ManuForm(), 'error': errmsg}) return redirect(request.META['HTTP_REFERER'], {'form': ManuForm(), 'error': errmsg}) return redirect(home) except ValueError: return render(request, 'manufacture_page/homepage.html', {'form': ManuForm(), 'error':'Bad data passed in!'}) def about(request): return render(request, 'manufacture_page/about.html') def services(request): return render(request, 'manufacture_page/services.html') settings.py import os BASE_DIR = … -
Node js vs Django vs Flask for multiple videos streaming from python
I got 6 real-time videos which are inference output from heavy deep learning calculation from python, and I've tried to display them to PyQt that lots of threading issues with ugly GUI!!. So, I want to use a framework only to display well and fancy GUI! There seem lots of frameworks based on my google search, and I have no idea which one is the best for my current project among Node js, Django, and Flask! I need to display 6 real-time videos with 10~15 FPS. Communicating well with python. Easy to build GUI, I have some features like logging, displaying real-time graph(optional) -
How to convert django.request logger time to UTC?
I have an application in another timezone, but I want to keep all logs in UTC. I already defined my own Formatter for Python logging, and all logger calls that I have throughout the app, are all using UTC, but django.request logs, are still using locale's app timezone (both logs bellow, were generated by a single request): Django Request Logger: [10/Jun/2020 16:59:52] "POST /api/v1/report/ HTTP/1.1" 200 761 Application Logger: [10/Jun/2020 23:00:02] INFO - REPORT_OK {'country': 'USA', 'ip': '127.0.0.1'} How can I apply a similar approach to django.request logger? -
NoReverseMatch at / Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:
I'm following django tutorial step by step, but can't to find out why I'm getting this error: NoReverseMatch at /polls/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<pk>[0-9]+)/$'] My code(basically everything copied from tutorial - https://docs.djangoproject.com/en/3.0/intro/tutorial03/) views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] polls/urls.py app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/index.html <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> -
Using custom user model in Django always return anonymous user in template
I have created a custom user model since I need three information( email, institute id, password) to login to the system. I have also created an authentication backend for this purpose. when I try to login, it redirects to the correct view. But the template shows anonymous user instead of logged in user. It's not going into this condition {% if user.is_authenticated %}. However, user.is_authenticated is true in view. Can anyone please help me to figure out the problem? Any suggestion will be appreciated. I have attached my code below. Thanks in advance. model.py class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, center_id, password, **extra_fields): values = [email, center_id] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, center_id=center_id, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, center_id, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, center_id, password, **extra_fields) def create_superuser(self, email, center_id, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, center_id, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address',max_length=255,unique=True,) … -
Unable to send mail to Outlook using PasswordResetView in Django Rest Framework
My urls file looks like this : urlpatterns = [ path('', include(router.urls)), path('password-reset/', PasswordResetView.as_view( #template_name='users/password_reset.html' ), name='password_reset'), path('password-reset/done/', PasswordResetDoneView.as_view( #template_name='users/password_reset_done.html' ), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view( #template_name='users/password_reset_confirm.html' ), name='password_reset_confirm'), path('password-reset-complete/', PasswordResetCompleteView.as_view( #template_name='users/password_reset_complete.html' ), name='password_reset_complete'), ] My settings.py file also has EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have even configured the EMAIL_HOST and EMAIL_PORT in settings.py I have tried using dockerimages like https://hub.docker.com/r/mailhog/mailhog and https://hub.docker.com/r/namshi/smtp as well for setting up SMTP server since my application runs on Docker. But they say that mail sent but I do not recieve any email. I even tried using locallost SMTP server using Django - [Errno 111] Connection refused but that doesnt work. However when I use this line EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' then I can see the email body. I have no idea on how to proceed further. Please help me. -
more than one site ERROR Django uwsgi config problem
I am trying to run multiple websites with Django nginx and uwsgi services. Can you help? django project install aws ec2 amazon.using 80 port runing no problem bu using 81 port Error :502 Bad Gateway nginx/1.14.0 (Ubuntu) ngix settings : upstream app_a { server unix:///home/ubuntu/gym/gym.sock; } upstream app_b { server unix:///home/ubuntu/DemoGym/DemoGym.sock; } server { listen 80; server_name ...163; charset utf-8; client_max_body_size 20M; uwsgi_read_timeout 6000; uwsgi_send_timeout 6000; uwsgi_connect_timeout 6000; keepalive_timeout 6000; location / { include /etc/nginx/uwsgi_params; uwsgi_pass app_a; root /home/ubuntu/gym; } location /static/ { alias /home/ubuntu/gym/crm/static/; } location /media/ { alias /home/ubuntu/gym/media/; } } server { listen 81; server_name ...163; charset utf-8; client_max_body_size 20M; uwsgi_read_timeout 6000; uwsgi_send_timeout 6000; uwsgi_connect_timeout 6000; keepalive_timeout 6000; location / { include /etc/nginx/uwsgi_params; uwsgi_pass app_b; root /home/ubuntu/DemoGym; } location /static/ { alias /home/ubuntu/DemoGym/crm/static/; } location /media/ { alias /home/ubuntu/DemoGym/media/; } } uwsgi settings : [uwsgi] plugins=python3 chdir=/home/ubuntu/gym/ home=/home/ubuntu/env/ module=mdsite.wsgi:application master=True gid=ubuntu uid=ubuntu socket=/home/ubuntu/gym/gym.sock touch-reload=/home/ubuntu/.reload chmod-socket=666 chown-socket=ubuntu vacuum=True env LANG="en-US.utf8" env LC_ALL="en-US.UTF-8" env LC_LANG="en-US.UTF-8" Error :502 Bad Gateway nginx/1.14.0 (Ubuntu) -
Group data by year and month | django rest framework
I have various reports and I want to retrieve them this way: year: "2019", months: [ { month: "01", reports: [reports for jan] } { month: "02", reports: [reports for feb] } ] I've achieved something similar on a full Django project ( see below ) but I'm unable to do the same on drf. def all_reports_by_month(request): reports = Report.objects.all() total_reports = reports.count() ordered_reports = Report.objects \ .annotate(month=TruncMonth('date')) \ .values('month') \ .annotate(c=Count('id')) \ .values('month', 'c') \ .order_by('-month') context = { 'ordered_reports': ordered_reports, 'total_reports': total_reports } return render(request, 'dashboard/reports.html', context) this is the current setup for reports on my DRF back-end right now : model.py : class Report(models.Model): # each code from shop code = models.ForeignKey(Shop, to_field='code' , on_delete=models.CASCADE) clics = models.IntegerField(blank = True, null = True) rdv = models.IntegerField(blank = True, null = True) date = models.DateField(blank = True, null = True) serializers.py : class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = '__all__' views.py : class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer urls.py : from rest_framework.routers import SimpleRouter from .views import ReportViewSet router = SimpleRouter() router.register('', ReportViewSet, basename='reports') urlpatterns = router.urls Thanks ! -
Setting up Apache ssl returns 403 error (port 443) mod_wsgi
I'm using apache to serve a Django app using mod_wsgi on windows and it works fine on the HTTP (port 80) but whenever I use port 443 or the SSL it seems that it's trying to access another directory C:/wamp64/www/ here's how my vhosts(port 443) looks # virtual SupervisionTool <VirtualHost *:443> ServerName mydomain.com WSGIPassAuthorization On WSGIApplicationGroup %{GLOBAL} SSLEngine on SSLCertificateFile "etc/ssl/certificate.crt" SSLCertificateKeyFile "etc/ssl/private.key" SSLCertificateChainFile "etc/ssl/ca_bundle.crt" ErrorLog "logs/app.error.log" CustomLog "logs/app.access.log" combined WSGIScriptAlias / "C:\Users\administrator\app\app\wsgi_windows.py" <Directory "C:\Users\administrator\app\app"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/Users/administrator/app/static_files" <Directory "C:/Users/administrator/app/static_files"> Require all granted </Directory> Alias /media "C:/Users/administrator/app/media" <Directory "C:/Users/administrator/app/media"> Require all granted </Directory> </VirtualHost> # end virtual SupervisionTool and when I access the app I get this message Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.12 mod_wsgi/4.7.1 Python/3.6 Server at www.mydomain.com Port 80 setting the app I uncommented LoadModule ssl_module modules/mod_ssl.so only in my httpd.conf and the code mentioned above is in my httpd-vhosts.conf and my logs mention this mod_ssl/2.4.41 compiled against Server: Apache/2.4.41, Library: OpenSSL/1.1.1c Init: Session Cache is not configured [hint: SSLSessionCache] Init: Initializing (virtual) servers for SSL AH00455: Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.12 mod_wsgi/4.7.1 Python/3.6 configured -- resuming normal operations AH00403: Child: Waiting for data for listening socket 0.0.0.0:80 client denied by server configuration: C:/wamp64/www/ … -
É possivel utilizar 2 Forengkey em um mesmo model no django?
Estou tentando fazer com que ele pegue o valor de venda do model Estoque automaticamente, assim como ele pega o nome do Produto, porém não consigo colocar 2 relacionamentos no mesmo model. É possível fazer algo do tipo no backend ou terei que fazer no front com javascript por exemplo. Python 3.7 e django 3.0 class Estoque(models.Model): nomeProduto = models.CharField(max_length=120) quantidade = models.DecimalField(max_digits=10, decimal_places=0) valorUnitario = models.DecimalField(max_digits=10, decimal_places=2) valorTotal = models.DecimalField(max_digits=10, decimal_places=2) valorVenda = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.nomeProduto class Venda(models.Model): produto = models.ForeignKey(Estoque, on_delete=models.DO_NOTHING, related_name='nomedoproduto') quantidadeProduto = models.DecimalField(max_digits=10, decimal_places=0) **precoVenda = models.ForeignKey(Estoque.valorVenda, on_delete=models.DO_NOTHING, related_name='valorcomercial')** total = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
Django DRF and XLSX binary file uploads from Postman
Hi im trying to upload an XLSX to my django application with DRF. I am getting the follow error { "detail": "Unsupported media type \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\" in request." } My Header Content-Type is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet". The Django DRF document tells me DRF is passing me that error when i try to print(request.FILES), but it doesn't really explain how to handle this. Can someone show me how to handle XLSX file uploads? Thanks! -
Django 3: browser doesn't display the content of a variable
I started learning Django 3 from a book. I have the following code: views.py: from django.views.generic import TemplateView class HomepageView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['my_statement'] = 'Nice to see you!' return context index.html <h1>Greetings</h1> <p>Hello, world!</p> <p>{{ my_statement }}</p> The browsers (Opera and Firefox) will display fine the first 2 lines but nothing for the third in the index.html (so urls.py and settings.py should be correct?) Inspecting the page source I see for the third line the opening and closing paragraph tags with nothing in between. If I write abc or whatever before or after the {{ }}, that abc text gets displayed. I have even copy/pasted the code from the book authors, and no change. I'm sure I'm missing something obvious, but what? -
Django Pagination for Component
I'm having trouble getting pagination to work on a component template with a has-many relationship where we have a view for ModelA which has a component template for ModelB, but ModelB does not have its own url. I'm guessing that I have an error in the views.py but I'm not really sure what else I should put to get pagination working for ModelB. Any and all help would be greatly appreciated! I can also put up more code on request. Views: ModelAView(ListView): model: ModelA template_name = 'modela.html' # Model A has-many Model B ModelBView(ListView): model: ModelB template_name = 'modelb.html' # this paginate is not working paginate_by = 10 template for modela.html: {% for a in object_list %} {% include 'modelb.html' with modela=modela %} {% endfor %} template for modelb.html: {% for modelb in modela.modelb.all%} # this is displayed in a table format but not being paginated. ... {% endfor %} urls.py url(r'^modela/$', ModelA.as_view(), name='model-a')