Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images in stored in AWS S3 not loading in Chrome but work in Firefox
I am hosting static files for a Django web application in AWS S3 using the Python storages package. The application's static assets load in Firefox, but in Chrome, the image files will not load. I am running the local Django development server. The error I am getting for the image file is: Access to XMLHttpRequest at 'https://bucket.s3.amazonaws.com/static/svg/parts/part1.svg' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My cors configuration for the AWS bucket is the following: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> I am only having issues with the image files. JavaScript, CSS, and webfont files (Fontawesome) are all loading fine in Chrome, it's just .svg and .png files that aren't loading and that I am getting the error for. All of this works fine in Firefox with all images loading from AWS S3. I have tried the following settings in Django: AWS_S3_SECURE_URLS = True AWS_S3_SECURE_URLS = False I have verified the the URLs in the browser are rendering as either http or https depending on the boolean value. Neither of these settings makes a difference in Chrome. I am using the corsheaders package in … -
How to over ride the get context data method in view
I am currently trying to create a like button for my posts in Django I have reached to the part where I can add a like but I am facing difficulty writing the code related to the view which linking the PostListView if there is user who liked it or not. I am getting an error: Exception Value: name 'post' is not defined Here is my Model: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='likes') def __str__(self): return self.title Here is my URL path('like/', like_post, name='like_post'), here is the view class PostListView(ListView): model = Post template_name = "score.html" ordering = ['-date_posted'] context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 5 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) _____________________ is_liked = False | if post.likes.filter(id=request.user.id).exists(): <-----| I Think the issue is is_liked = True | with this code context = {'post': post, | 'is_like': is_liked, | } |_____________________ return context def like_post(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): posts.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect(post.get_absolute_url()) here is the template {% extends "base.html"%} {% block content %} {% for post in posts %} <div style="padding-top: 200 … -
Submit button not working and redirecting to 404 error page in Django
I have deployed Django in my site subdomain apps.webmatrices.com through cPanel and the home page of my Django app apps.webmatrices.com/adsense-eligibility-checker is working but when I fill the form and click on the SUBMIT Button it redirects to 404 error page instead of running the second function scanned(requests) in mainApp/views.py. This is inside mainApp/views.py directory: def home(request): return render(request, 'home.html') def scanned(request): email = request.POST['email'] site = request.POST['site'] rating = request.POST['stars'] source = request.POST.getlist('source') ...... return render(request, "result.html", {'rMsg':rMsg,'result0':result0, 'result1':result1,'site': site,'show_site':show_site, 'vips':m1, 'domain':domain, 'site_age':site_age, 'sent': sent}) Inside MainApp/urls.py: from django.urls import path from.import views urlpatterns=[ path('', views.home, name='home'), path('scanned/', views.scanned, name='scanned') ] Inside home.html: {% extends 'main.html' %} {% load static %} {% block content %} {% csrf_token %} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static 'style.css' %}"> <form method='POST' action="/scanned/" class='FormBody'> {% csrf_token %} <div id='tab'> <h2>Adsense Eligibility Checker</h2> <fieldset class='siteAndEmail'> <legend>Site & Email</legend> <div class='form-wrapper'> <div class='full-input'> <label for="site">Your Site URL</label> <input type="domain" name='site' class='input' placeholder="https://yoursite.com"> </div> <div class='full-input'> <label for="email">Your Email</label> <input type="text" name='email' class='input' placeholder="youremail@gmail.com"> </div> </div> </fieldset> <fieldset class='siteAndEmail reached'> <legend>How did you reached us?</legend> <label class='c1'> <input type="checkbox" name='source' value='Facebook' /> <i id='icon' class="fa fa-facebook" style='background:linear-gradient(white,lightblue); color:dodgerblue;'></i> Via Facebook </label> <label class='c1'> <input type="checkbox" name='source' … -
Django MySQL Database location and setup
So I have a MySQL database for my Django project which I think is located in the default directly (wherever that should be). When I want to move my whole Django project to a different computer, how do I move that database? The my.cnf file is located inside the same directory as the settings.py file for the Django project. I am using macOS. In short: How do I copy my database file to my Django project directory and reconfigure its path to that? -
how to save mutiple checkboxes data and value in django
i am fresher of python django, i want to save 10 out of 25 values in django api. i am posting the values from the react js using check box. i do not how to write that much code in django api..can any one on that..if do you have any link share me please..i am beginner of django.. if you have time please share me what is the procedure of do write code for these this are the values i am posting from front end with that i sending checked status of that checkbos {Maths Physics Chemistry: true, Biology Physics Chemistry: true, Maths Biology Physics Chemistry: true, Commerce Economics Civics: true, History Economics Civics: true} Biology Physics Chemistry: true Commerce Economics Civics: true History Economics Civics: true Maths Biology Physics Chemistry: true Maths Physics Chemistry: true __proto__: Object -
publish website to Raspberry Pi 3 from Pycharm and Django
I'm developing a website from Pycharm and Django on Window but I don't know how to publish it to Raspberry Pi 3. Can anyone have any idea -
how to download html to pdf in Django framework
I am building an CV maker website, in which i what to add a download feature, that is, when the user select an template, fill the required data(the whole template will be in html form) then how can i add the download feature so that the HTML page will be downloaded into PDF file. This the first problem, 2. one is, do i need to create a separate form.py for each template, or is their any way that only one form will be applicable for all the templates. I am working on Django framework. -
Am I dynamic filtering in Django correctly?
I needed a way to get URL parameters and put them and their values into a query set's .filter() if they exist. After a day of piecing together information from the Interwebs, I have a working solution to my problem. However, is it the best way to do this? I feel it can be improved or streamlined, but my tiny brain is failing me: In utilities.py: def get_filters(url, allowed): query = parse.urlsplit(url).query pack = dict(parse.parse_qsl(query)) translated = {} for pk, pv in pack.items(): for ak, av in allowed.items(): if pk == ak: translated[av] = pv return translated In view.py: from utilities import get_filters people = Person.objects.all() url = request.get_full_path() allowed_filters = { 'location': 'person_location', 'role': 'person_role', } filters = get_filters(url, allowed_filters) if filters: filtered_query = people.filter(**filters) else: filtered_query = people if ('search' in request.GET) and request.GET['search'].strip(): query_string = request.GET['search'] query_search = get_query(query_string, ['person_first_name', 'person_last_name']) query_results = filtered_query.filter(query_search) else: query_results = filtered_query It does everything I need it to: if a URL parameter is in the allowed list, it takes that parameter and value, packs it into a dictionary, and shoves it into filter() to be unpacked by the interpreter. This way whenever I want to add a new filter, I … -
Fetch data from multiple table in django
I have a below models in my models.py file class Member(models.Model): # This field type is a guess. agre = models.BooleanField(default=False, editable=False) # This field type is a guess. reject = models.BooleanField(default=False, editable=False) memberid = models.AutoField(primary_key=True, editable=False) memberdate = models.DateTimeField(default=timezone.now) fname = models.CharField(max_length=25) mname = models.CharField(max_length=25) lname = models.CharField(max_length=25) mobile1 = models.CharField(max_length=15) email = models.CharField(max_length=150) mem_img = models.ImageField(upload_to='member_pics') dob = models.DateTimeField(default=timezone.now) def newlocation(self, filename): filspilt = filename.split(".") exten = filspilt[-1] return "newfile1"+"."+exten.lower() class Meta: managed = False db_table = 'member' class Memberprt(models.Model): memberid = models.IntegerField() memberprtid = models.AutoField(primary_key=True) relative_name = models.CharField(max_length=100) relativeid = models.IntegerField() relationtypeid = models.IntegerField() member = models.ForeignKey(Member, on_delete=models.CASCADE) class Meta: managed = False db_table = 'memberprt' I want to get a list of member with its relative_name. i.e. I want to get Member.fname and Memberprt.relative_name. How to acheive this. -
Django Server Does not affect view changes
I m using Nginx, and Gunicorn on Ubuntu 18.04 to serve my Django project. I configured everything ( like here ) properly and working so well, but I noticed that changes in my views doesn't affect my server side, although template changes are applied. This is my scenario : First Commit : service.views.py : def showSudent(req): student = Student.objects.get(pk=1) return render(req, 'bio.html, { 'student' : student} ) template/bio.html : <h3>{{ student.firstName }}</h3> Second Commit : service.views.py : def showSudent(req): student = Student.objects.get(pk=1) return render(req, 'student.html, { 'student' : student} ) template/bio.html : <h3>{{ student.lastName }}</h3> I changed views and template both and pull them to server. So now, django is still renders 'bio.html' ( but it must render 'student.html' ) , by the time interestingly it shows 'student.lastName' now. It means, django sees my template changes but not views changes. I repeatedly checked everything is right on server, yes all codes are right at server but not affects any view changes although all my templates changes are affected. Also I restarted nginx, even rebooted the server several times. What is the problem with that ???? -
I am using Django-user-accounts. Why am I getting 404 and 302 response codes when I try to access the sign-up url?
urls urlpatterns = [ path('account/signup/', views.SignupView.as_view(), name="account_signup"), ] views class SignupView(account.views.SignupView): form_class = myproject.forms.account_forms.SignupForm identifier_field = 'email' def generate_username(self, form): # do something to generate a unique username (required by the Django User model, unfortunately) username = _generate_unique_uuid() return username def after_signup(self, form): #self.create_profile super(SignupView, self).after_signup(form) def _generate_unique_uuid(): for i in range(10): username = uuid.uuid4() try: User.objects.get(username=username) except ObjectDoesNotExist: return username template <form method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{form.as_p}} <div class="submit-row"> <input type="submit" value="Sign up!"> </div> </form> Note: when I type 127.0.0.1:8000/account/signup in the browser, it returns empty to(127.0.0.1:8000) the output after requesting the url -
Some fields are not been updated in the database when filling a form - Django
I am having problems when filling the forms in my project, some of the fields when introduced are not getting uploaded to the database, while the other ones do, but there is no error showing up when running the server. Although the MedicalInfo model, the RelativesInfo model and the Insuranceinfomodel are linked to the Patients model through the foreign key but when looking up in the admin page it appears as created but not linked to the patient, i dont know what am i doing wrong, if you need some extra info just let me know. This are my models class Patient(models.Model): Codigo = models.CharField(max_length=20,default=None,null=False) Nombres = models.CharField(max_length=100,null=False) Apellidos = models.CharField(max_length=100,null=False) Fecha_Nacimiento = models.DateField() Telefono = models.CharField(blank=True,max_length=25,default='00000000') Correo = models.EmailField(blank=True) Genero = models.ForeignKey(Gender,on_delete=models.DO_NOTHING,default=None,null=True) Nacionalidad=models.ForeignKey(Nationality,on_delete=models.DO_NOTHING,default=None,null=True) Estado_Civil = models.ForeignKey(CivilStatus,on_delete=models.DO_NOTHING,null=True) Ocupacion = models.CharField(max_length=200) Lugar_de_Procedencia = models.CharField(max_length=200) Lugar_de_Residencia = models.CharField(max_length=200) def __str__(self): return self.Nombres + ' ' + self.Apellidos class MedicalInfo(models.Model): Expediente = models.CharField(max_length=500,blank=True) Sangre = models.ForeignKey(BloodType,on_delete=models.DO_NOTHING,default=None,null=True) Peso = models.FloatField() Estatura = models.FloatField() Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class InsuranceInfo(models.Model): Seguro = models.ForeignKey(InsuranceCompany,on_delete=models.DO_NOTHING, default=None,blank=True,null=True) Tipo_de_Poliza = models.ForeignKey(Policy,on_delete=models.DO_NOTHING,default=None,blank=True,null=True) Numero_Poliza = models.IntegerField(default=None,blank=True,null=True) Vencimiento = models.DateField(default=None,blank=True,null=True) Paciente = models.ForeignKey(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class Relatives(models.Model): Parentesco = models.ForeignKey(Family_relation, on_delete=models.DO_NOTHING,default=None,blank=True,null=True) Nombre = models.CharField(max_length=100,blank=True) Apellido = models.CharField(max_length=100,blank=True) Telefono = models.CharField(max_length=100,blank=True) Correo = models.EmailField(blank=True) Nacimiento = … -
While I use multprocessing.Process in Django,raise AppRegistryNotReady("Apps aren't loaded yet.")
def funtest(): time.sleep(10) from multiprocessing import Process def testView(request): try: Process(target=funtest).start() return HttpResponse('ok') except Exception as e: return HttpResponse(str(e)) I have tried to add django.setup(),but it doesn't work well -
django runserver error "Secure Connection Failed An error occurred during a connection to 192.168.99.100:8000. PR_END_OF_FILE_ERROR"
I'm working on a Django project that cloned from git, i use docker container, that is all run well but when i start Django local sever , I 'm faced to this errors. I don't know how to define the cause, is there anyone have been facing one similar, looking forward to a response. thanks! -
Django Project Documentation Type of Relationship
I am documenting a Django Project that deals with objects Store, Person, Transaction, and Address I would appreciate you reading the thing just as sanity check to me but my real question is in the last paragraph. Only Showing The Fields Which Are a Relation Store # The intention here is for each Store to have exactly 1 address that can not be shared with another Store. # I represent this on my diagram as 1-to-1 Store --> Address address = models.OneToOneField(Address, on_delete=models.PROTECT) Person # The intention here is for each Person (used for Employee and Customers) to have exactly 1 address that can not be shared with another Person. # I represent this on my diagram as 1-to-1 Person --> Address address = models.OneToOneField(Address, on_delete=models.PROTECT) # The intention here is for many Persons to be associated with a Store. # In this case the association would mean they were an employee of the Store. # There is a dummpy Store that all customers are associated with (I know not the best design) # I am represting this relationship as Many-to-1 Person --> Store store = models.ForeignKey(Store, on_delete=models.PROTECT) Address # No relation fields Transaction # The intention here is for … -
celery 4.4.2 and django 3.0.2 raising self.notregistered error but calling the function in python manage.py shell works fine
I am trying to add celery to my django project. everything works fine when i run it from the manage.py shell, my celery worker returns the result of the add() function. when i call this function from my view it raises a not registered error and a module object not callable error on celery/base.py line 1253 celery/app/base.py", line 1253, in loaderreturn get_loader_cls(self.loader_cls)(app=self) TypeError: 'module' object is not callable raise self.NotRegistered(key) celery.exceptions.NotRegistered: 'home.tasks.add' both are from the apache error log my home.tasks.py looks like this from celery import shared_task from celery.schedules import crontab from django.db import connection from django.utils import timezone, translation #import pandas as pd from home.models import * from residence_management.models import * from sqlalchemy import * from django.conf import settings from django.contrib.auth.models import User from decimal import Decimal @shared_task def add(x, y): return x + y my view where i call the task has the import: from home.tasks import add in the view itself i just call add(9, 5) and it fails with the above error (without the @shared_task decorator it works fine). when calling the function in the shell, even with the @shared_task decorator it works fine, i can start the celery worker without problems as well. [2020-05-13 … -
my navbar dropdown menu is not working in django project using bootstrap4
Building my first Django app from a tutorial, following the instructions pretty much verbatim but my navbar dropdown menu is not working no matter what I try, so unable to log out or change password from the navbar <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'home' %}">Bk-Styles-007</a> {% if user.is_authenticated %} <ul class="navbar-nav mr-auto"> <li class="nav-item"><a href="{% url 'article_new' %}">+ New</a></li> </ul> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary"> Log In</a> <a href="{% url 'signup' %}" class="btn btn-primary ml-2"> Sign up</a> </form> {% endif %} -
Rest Framework pass additional variables to ModelViewSet
Might seem like a dumb question but trying to pass additional filter variables to a ModelViewSet but request.data is empty. class ObjViewSet(viewsets.ModelViewSet): def get_queryset(self): if self.request.get('orderBy', None): return Obj.objects.all().order_by(self.request.get('orderBy')) else: return Obj.objects.all() What is the correct way to do this? I don't want to screw up the /view/<id>/ routing but I also wish to pass a couple more variables via /view/?orderBy=id&var2=val2 Using DefaultRouter router.register('objs', views.ObjViewSet, basename="obj") -
NoReverseMatch at /theme/ Reverse for 'article' with arguments '('',)' not found. 1 pattern(s) tried: ['theme/(?P<article1_id>[0-9]+)$'
I have the following views def article1(request, article1_id): article1 = get_object_or_404(Presse, pk=article1_id) context = { 'article1': article1, } return render(request, 'article/article1.html', context) The following urls from django.urls import path from . import views urlpatterns = [ path('', views.theme, name='theme'), path('<int:article1_id>', views.article1, name='article'), ] but get error when trying to pass parameter on my templates url <h4 class="uk-margin-top"><a href="{% url 'article' article1.id %}">{{entreprenariat.titre}}</a></h4> -
Update field value in instance Django
What is the best way the update the total field with value total the rows the file? Implement in model or views or other? How to make The file registration will always be through django-admin models.py class Registry(models.Model): file_upload = models.FileField(blank=True, null=False) #csv or xlsx total = models.CharField(max_length=100, null=True, blank=True, default=None) -
Froward authenticated users from PHP app to Django
I'm building a web app on Django. My company has a PHP web app that employees are currently using. There already exists an user authentication system on the PHP web app. Is it possible to authenticate users on the web app then forward them to my app as authenticated users? We already have a rest API installed for forward some data from the PHP app to Django. Would this simplify the process? -
Django Invalidate Form Test If Extra Field Supplied
I have had some issue where a leak of User variables onto the registration form allowed users to set these on user creation. Can I ensure through testing that this will not be possible again? Let's say for example I don't want it to be possible that users can set their own 'coupon_code'. How would I test for that? Accounts/forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User class RegisterUserForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Required.') class Meta(UserCreationForm.Meta): model = User fields = ('username', 'password1', 'password2', 'email') exclude = ('coupon_code',) Accounts/tests/test_forms.py: from django.test import TestCase from Accounts.forms import RegisterUserForm, UpdateUserForm # Create your tests here. class RegisterUserFormTest(TestCase): #@classmethod #def setUpTestData(cls): # Set up non-modified objects used by all test methods def valid_data(self): return {'username':'abc', 'email':'abc@abc.com', 'password1': 'test123hello', 'password2':'test123hello'} def test_register_user_form_cannot_set_coupon_code(self): data = self.valid_data() data['coupon_code'] = '42' form = RegisterUserForm(data=data) self.assertFalse(form.is_valid()) Currently the above test fails, as the form is considered valid, even though excluded field is present -
Use login_required decorator in Django with firebase
I am a relative newbee with Django and firebase. Django comes with 'login_required' decorator to render a view only if user is logged in. from django.contrib.auth.decorators import login_required @login_required def my_view(request): ..... I want to use firebase as database with Django. I am not sure how to do use Django 'login_required' decorator with firebase. Is there a way I can have minimal changes somewhere and still be able to use the 'login_required' decorator. Other method is to write a custom decorator which I want to keep as second option. And if possible, will the method be applicable to all the other decorators also. Thank you in advance. -
Why are edits to my css file not showing up? Django
So I am noticing that my css changes are not being reflected. I did a hard-reload and cleared the cache but still nothing. Like I can literally delete the css file and my badge which I'm trying to edit is still there... it only goes away once I take it off of base.html directly. So what is going on here? I have a static folder in my app, with a css folder and then my css/notification file. I tried doing collectstatic through terminal but that doesn't do anything. Also, I already have my load static tag in my html. settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ "/DatingAppCustom/dating_app/static", ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'dating_app/media') -
Ordering Model based on a max Children Attribute (with potential ties) - Django
I would like to sort my Docket object based on the most recent Document (a child object). There are typically several documents with the same date_filed. Based on the tutorial, I tried sorting on -documents__date_filed and it sort of works. Because there are multiple Documents with the exact same date, my ListView shows 2-3 repeated rows (one for each date tie). How do I avoid getting the duplicated results and just have one row for each Docket in the output? class Docket(models.Model): name = models.CharField(max_length=200) class Meta: ordering = ['-documents__date_filed', Func(F('name'), function='LOWER')] class Document(models.Model): docket = models.ForeignKey(Docket, on_delete=models.CASCADE, related_name="documents") date_filed = models.DateTimeField(default=timezone.now)