Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Columns in Bulma lies horizontally, can we fix the number of column in one row and rest in another?
<section class="section"> <div class="container"> <div class="tile is-ancestor"> '''{% for service in allServices %}''' <div class="tile is-vertical is-parent"> <div class="tile is-child box"> <h1 class="title is-centered">{{service.serviceTitle}} </h1> </div> </div> '''{% endfor %}''' </div> </div> [ if i keep on adding column it lies horizontally no matter how many columns you have* -
Can't retrieve data from mysql to html template in django (PyCharm)
I am hoping someone can help me here; been stuck for a while in this part of learning web development. I am using django in PyCharm community edition. Everything with Apache and MySQL seems to be working well. I am at the stage of making html templates and I am able to log data into MySQL databases. I wanted to retrieve data from a database into a template but it just does not work and I get a warning saying "Unresolved attribute reference '…' for class '…'" when defining a view in PyCharm. These are my files: # views.py from django.shortcuts import render from .models import AirplanePics # AirplanePics is a model def pictures(request): obj = AirplanePics.objects.get(id=1) context = { 'datax': obj, } return render(request, 'pictures.html') In models, I tried a workaround that I read in this forum, but it just recognized 'objects' (in the views.py class) and removed the warning # models.py from django.db import models class AirplanePics(models.Model): author = models.CharField(max_length=30) title = models.CharField(max_length=30) description = models.TextField() def __str__(self): return self.author # models.py (with the workaround) from django.db import models class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True class AirplanePics(BaseModel): id = models.AutoField(primary_key=True) author = models.CharField(max_length=30) title … -
How lazy are Django QuerySets?
Will the following code Query the database twice? Of course once to begin the for loop, but does it query the database with len()? I ask this because I know the Django count() function queries the database. events = Events.objects.all() for event in events: #First Query print(event.name) length = len(events) #Second Query? -
Confirm simplejwt expire in testcase
I'm just trying to understand djangorestframework-simplejwt expiration and want to know what is returned when the token expires. To explore this a wrote a simple testcase in my django project, but I can't seem to get the expire to occur. views.py import json from http import HTTPStatus from django.http import JsonResponse from rest_framework.decorators import api_view from .models import Visitor @api_view(["POST"]) def visitor_post(request): body_unicode = request.body.decode("utf-8") if not body_unicode.strip(): return JsonResponse({"status": HTTPStatus.BAD_REQUEST}, status=HTTPStatus.BAD_REQUEST) body = json.loads(body_unicode) submitted_datetime = body["submitted_datetime"] visitor = Visitor( representative_name=body["representative_name"], visitor_type=body["visitor_type"], visitor_count=body["visitor_count"], submitted_datetime=submitted_datetime, ) visitor.save() return JsonResponse({"status": HTTPStatus.CREATED}, status=HTTPStatus.CREATED) Currently my testcase is as follows: tests.py import datetime import json from time import sleep from http import HTTPStatus from typing import Optional, Tuple from accounts.models import CustomUser from django.urls import reverse from django.utils import timezone from django.test import override_settings from rest_framework.test import APIClient, APITestCase EXPIRE_WAIT_SECONDS = 5 SIMPLE_JWT_EXPIRE_TEST_SETTINGS = { "ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=EXPIRE_WAIT_SECONDS), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=14), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": False, "ALGORITHM": "HS256", "SIGNING_KEY": 'kkdkasjf;a', "VERIFYING_KEY": None, "AUTH_HEADER_TYPES": ("JWT",), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", } class ViewsTestCase(APITestCase): def setUp(self): self.valid_user = CustomUser(last_name="user", first_name="valid", username="validuser", email="validuser@email.com") self.valid_user_password = "mysecretpassword" self.valid_user.set_password(self.valid_user_password) self.valid_user.save() self.apiclient = APIClient() def _get_jwt_token(self, username: Optional[str] = None, password: Optional[str] = None) -> Tuple[str, str]: if not … -
I Have problem for using pip install flask-mysqldb on window 10 64bit , I got an Error
I trying to install MYSQL on window 10 64 bit , I have python3.7.4 version when I tray pip install mysql I got Error MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory , so I have Python Version: 3.7.4 Operating System: Windows 10 Pip Version: 20.1 Cannot pip install flask-mysqldb Here is a summary of the error i'm getting... C:\Users\Omar Faaruuq>pip install mysql Collecting mysql Downloading mysql-0.0.2.tar.gz (1.9 kB) Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysql, mysqlclient Building wheel for mysql (setup.py) ... done Created wheel for mysql: filename=mysql-0.0.2-py3-none-any.whl size=1252 sha256=fd9a7bdc9cfebc286a66598c32d555b935dfa38a3e1b687096dfa22bf50100d1 Stored in directory: c:\users\omar faaruuq\appdata\local\pip\cache\wheels\f6\60\6d\b1cf0653d003ddb0be2985a4d5f2c6f977d91f0862df094de8 Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\omar faaruuq\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\OMARFA~1\\AppData\\Local\\Temp\\pip-install-m0eys0mm\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\OMARFA~1\\AppData\\Local\\Temp\\pip-install-m0eys0mm\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\OMARFA~1\AppData\Local\Temp\pip-wheel-usgog472' cwd: C:\Users\OMARFA~1\AppData\Local\Temp\pip-install-m0eys0mm\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants … -
How can I use Ajax to display if username is already taken in django?
I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to refresh the entire page. I tried implementing some JS and Ajax, but since I'm totally new to JS, it's not working and I'm not sure why. What am I doing wrong? reg.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} {% block javascript %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/check_if_username_exists_view/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> {% endblock %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > <div class="is-valid"> {% bootstrap_form registration_form%} </div> {% csrf_token %} {% for field in bootstrap_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content … -
How to Schedule task to run at a specific time
I have a quiz application in django. I want to score the quiz one hour after the deadline. How can I schedule the score_quiz function to run one hour after the deadline for that quiz? -
Installing the correct version of GDAL
My version of Python is [MSC v.1916 32 bit (Intel)] on win32 but I cannot see a release 1916 in - http://www.gisinternals.com/release.php https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal https://trac.osgeo.org/osgeo4w/ Possibly I am misreading the websites. To be honest I found https://trac.osgeo.org/osgeo4w/ very confusing to navigate. Can anyone give me any guidance? -
Why isn't Django project working within pipenv?
I'm trying to get started with Django, and a tutorial I'm following recommended I use a Python Virtual Envrionment to separate projects/dependencies and I'm trying to use pipenv. These are the steps I've taken so far: Creating the virtual environment Installing Django And then here's me trying to create a django project Furthermore, pip freeze shows absolutely nothing in the virtual env so it's like no packages are being installed even though django installed successfully and the pipfile has: I'm very confused as to why the error message is coming up, I apologize as it's my first time using virtual environments. They seem really cool once you get them working. -
How to access field values/attrs in an inlineformset_factory?
Sometimes browsers can render an empty label in a select box as -----: In a ModelForm it's easy to fix this by replacing the empty_label attr as below: class CustomModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomModelForm, self).__init__(*args, **kwargs) # Loop over the ModelForm fields to update field types and attributed for field_name in self.fields: field = self.fields[field_name] if hasattr(field, 'empty_label'): # Remove the first empty label '-----' field.empty_label = None However, when using an inlineformset_factory how does one do similar? E.g. MyFormSet = inlineformset_factory( Author, Book, fields=MYFIELDS, extra=0 ) -
How is GoogleAPI + Python supposed to work in 2020? Conflicting information
I have been trying to manually utilize the GoogleAPI with Django for the first time but there seems to be so much conflicting information that it's really difficult for me to figure out what the actual flow that I need to follow is in 2020. Tools: Django 2.0, Python 3.7. Google API creds are created. Everything I can find on getting me through this is from 2011-2014 and appears to be deprecated or on its way out so I'm not sure which API I'm supposed to use. I've reviewed every topic on SO I can find but each one looks different and uses different APIs. However, some people recently commented that the scopes can still be used so you can understand my confusion. The actual problem with this code is that I receive a null value back from the GoogleAPI and I can't figure out how to get the actual data from the authorized user. import json from django.http import JsonResponse import google.oauth2.credentials import google_auth_oauthlib.flow from googleapiclient.discovery import build from users.models import CustomUser, OAuthCredentials from django.shortcuts import render, redirect, get_object_or_404 from urllib.request import urlopen JSON_PATH = 'users/client_secret.json' REDIRECT_URI = 'http://localhost:8000/users/oauth/google/callback/' API_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid', ] def oauth_google(request): flow … -
How to handle Nonetype Error with Mommy.make?
I am trying to create a user using mommy.make, sometimes the user created successfully, but others produces and error: AttributeError: 'NoneType' object has no attribute 'scheme' Here is my code: user = mommy.make(User,first_name='lisa') I imported the User model and it has a field called first_name. -
Validation always True (blank=False) for CharField but not with DateField
I have an inlineformset_factory containing a field. When this field is a CharField (blank=False) and I run is_valid() on the formset, True is always returned even though the CharField is left blank. When I replace the CharField with a DateField (default=timezone.now(), blank=False), is_valid() will return True only when the field is filled as expected. Why is the CharField always returning True when running is_valid() on the formset but the DateField does not? Note that I want the CharField to behave like the DateField. Interestingly enough, the formset behaves as expected when both the CharField and DateField are present. Code below is shown with title and date but I have tried with only title and only date as well. Any help is appreciated. This is driving me up the wall! models.py class Author(models.Model): author = models.CharField(max_length=128) description = models.CharField(max_length=1000) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(blank=False) date = models.DateField(default=timezone.now(), blank=False) forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('author', 'description') class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'date') BookFormSet = forms.inlineformset_factory( Author, Book, form=BookForm, fields=('title', 'date'), extra=1, can_delete=False, can_order=False ) views.py class CreateAuthorView(CreateView): template_name = "author_create.html" model = Author form_class = AuthorForm def get_context_data(self, … -
Django referrer get short domain in template
I save visits referrer address on db. But It save like this domain.com/domainurl_page1.php I want to delete after from .com, How can i cut domain like this ; domain.com i call referrers list in template; {% for i in get_all_referer %} {{ i.referer }} {% endfor %} my view.py ref = request.META.get('HTTP_REFERER', 'Direct') -
Django ORM: Sum value and then create extra field showing rolling average
Is it possible, using Django's ORM to create a Sum based on a Date column and then add an extra field with a rolling average. Let's say I have a table like this, called "Sales": |---------------------|------------------|--------------| | Date | Category | Value | |---------------------|------------------|--------------| | 2020-04-01 | 1 | 55.0 | |---------------------|------------------|--------------| | 2020-04-01 | 2 | 30.0 | |---------------------|------------------|--------------| | 2020-04-02 | 1 | 25.0 | |---------------------|------------------|--------------| | 2020-04-02 | 2 | 85.0 | |---------------------|------------------|--------------| | 2020-04-03 | 1 | 60.0 | |---------------------|------------------|--------------| | 2020-04-03 | 2 | 30.0 | |---------------------|------------------|--------------| I would like to group it by Date (column "Category" is unimportant) and add the Sum of the values for the date. Then I would like to add a rolling Average for the last 7 days. I tried this: days = ( Sales.objects.values('date').annotate(sum_for_date=Sum('value')) ).annotate( rolling_avg=Window( expression=Avg('sum_for_date'), frame=RowRange(start=-7,end=0), order_by=F('date').asc(), ) ) .order_by('date') This throws this error: django.core.exceptions.FieldError: Cannot compute Avg('sum_for_date'): 'sum_for_date' is an aggregate Any ideas? -
i want to scrap and find the mp3 url
this a website that play audio mp3 and I want to use it inside my APP react native but first i must find the url of mp3 audio https://www.maghreb.space/Music/Labess/144115/Ecouter -
Gunicorn isnt finding 'memcache' module but it is found when I run python3 manage.py runserver 0.0.0.0:8000
I'm having trouble with my server. This is a multitenant project, the one in the Windows server is working fine, but the one in Ubuntu is giving me a "No module named 'memcache'" error although it is installed. I know it is installed because I ran a "python3 manage.py runserver 0.0.0.0:8001' and when I accessed by my personal browser worked fine. Gunicorn is pointing properly to my virtual env and there are no log errors when I restart the service, I'm quite desperate now. -
Problem dockerizing django api losing statics
Hi I built my docker image with my django api. When I run and go into the page the default css is missing. I realized that the STATIC_URL='/static/' worked when I work with the virtualenv activated but when I run the docker the server doesn't find the files. So to force that it finds the files I saw where the files are installed when I run the docker and open a terminal in the container. Then I changed static_url to: STATIC_URL = '/usr/local/lib/python3.6/dist-packages/rest_framework/static/' STATICFILES_DIRS = [ '/usr/local/lib/python3.6/dist-packages/rest_framework_swagger/', '/usr/local/lib/python3.6/dist-packages/rest_framework/static/', '/usr/local/lib/python3.6/dist-packages/django/contrib/admin/', '/usr/local/lib/python3.6/dist-packages/', ] With this I was trying to force the server get the files from the url where they are inside the container but even with the correct url the server returns me NOT FOUND: /usr/local/lib/python3.6/dist-packages/rest_framework/static/rest_framework/js/csrf.js Even when I use find / -name csrf.js it returns me the same url where the server says not found and I don't know how to fix this kind of problem. Any ideas? -
Abstractbaseuser and Forms in Django
I use abstractbaseuser as an option in customization, whats things that i must change in working in admin and aslo the type of forms(modelForm or form.Forms or UserCreationForm ) which i have to use ? -
How to change HiddenInput value of form
I am trying to create a url from the title of an object which is given by the user. I figured I could do this in the clean_url method of the form but it does not seem to work. def clean_url(self): url = re.sub(r'\W+', '', str(self.cleaned_data['title'])) return url How can I add form.url data to the form before saving? -
Catch externally added data to Postgres database in Django
I have a Django backend for my project using Postgres as a DB. Apart from it, I have a systemd service running and inserting a new row in a specific table in the DB. I would need to detect the moment in which a new row is inserted in the table to run a callback function, which is defined in Django. The service takes different times to complete. I would also like to make it efficient. I thought of these options: I used to use celery in the project but don't anymore. It is kind of set up already, so I thought one option would be a PeriodicTask that checks if something has been addedd. I dislike periodic tasks, though, and it is not quite precise (there could be a gap between the time the service finishes and the time the task runs). So EASY but UGLY If it were possible, I would like to use a Postgres TRIGGER to insert my callback task in the Celery queue. On paper, that sounds fast and clean. I have NO CLUE how to add something to the Celery task queue though. So CLEAN and EFFICIENT but DIFFICULT I thought of implementing a … -
howto login with CustomUser
my application have two types of users Admin(not the admin of SuperUser) , Entrepreneur i create 3 class CustomUser, Admin, Entrepreneur: models.py #user-------------------------------------------------------------------------- class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"entrepreneur")) user_type=models.IntegerField(default=1,choices=user_type) email=models.EmailField(unique=True,blank=True) objects = UserManager() def __str__(self): return self.first_name #admin----------------------------------------------------------------------- class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,primary_key=True) date_naissance = models.DateField(default=timezone.now) adresse = models.CharField(max_length=20, blank=True) def __str__(self): return self.user.first_name # Entrepreneur---------------------------------------------------------------- class Entrepreneur(models.Model): user= models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True) date_naissance=models.DateField() adresse_entr=models.CharField(max_length=20,blank=True) telephone=models.IntegerField() statut_social=(('ce','celébataire'), ('ma','marié'), ('di','divorcé'), ('ve','veuf'), ) statut_social=models.CharField(default='ce',choices=statut_social,max_length=50) occupation=models.CharField(max_length=50) annnee_exp=models.IntegerField() def __str__(self): return self.user.first_name then i create a class form to use it for login forms.py class LoginForm(forms.ModelForm): class Meta: model =Entrepreneur fields={'email','password'} also a function for login and redirect to another home page views.py def login(request): if request.method =='POST': form =LoginForm() email=request.POST['email'] password=request.POST['password'] user=authenticate(request,email=email,password=password) if user is not None: login(request,user) return redirect('home.html') else: messages.warning(request,'email ou mot de passe invalide') return render(request,'login.html') in my login.html i have 2 tabs(1 by type of user) and one login form for each tab i want to login to the right place for each type of user it didn't work correctly what is my mistake? -
How do I attach a listener to a date selection in the Django admin?
I have a Django admin page for a model with a DateField called 'date': # models.py class Article(models.Model): date = models.DateField( help_text="Article publication date" ) # admin.py @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): change_form_template = "article_extension.html" I've extended the Admin add/change template for this model to include JavaScript to execute when a date is selected. In the Admin add/change page, the default widget for this field is a text element accompanied by a calendar selector. The page source does not show any code for the selector, so the only thing I can attach JavaScript to is the input box: <input type="text" ... id="id_date"> In the template's JavaScript, I've attached an EventListener for 'input' events on this input box: # article_extension.html {% extends "admin/change_form.html" %} {% block extrahead %} block.super <script type="text/javascript"> window.onload = function() { var dateInput = document.getElementById("id_date"); dateInput.addEventListener('input', dateListener); function dateListener() { console.log("date event recognized"); } } </script> {% endblock %} When I then select a date from the calender selector, the contents of the input box change to reflect the selected date, but the EventListener doesn't fire. If I manually type something into the input box, however, the EventListener fires and "date event recognized" shows up in the console. Evidently, … -
Log in with Ajax Django
I want to do my log in stuff with an ajax request so that the page doesn't reload. So instead of using a form with method="POST", I will just make a post request with the email and password field values. What are the upsides and downsides to this? How do I ensure security of the credentials? Please let me know if you have any questions! Thanks! -
how can i send formated date to api with react-datepicker
I'm trying to send a date to my API with react-datepiker and even though I set the dateFormat to yyyy/MM/dd I'm still getting "2020-06-19T04:00:00.000Z" as the value and it is whats being pushed to my API only to get an error to set the date format to yyyy/MM/dd Any ideas as to what this could be. Is this a bug? I am using react 16.5 and Django with drf for my backend the model uses DateField() and expects yyyy/MM/dd. Is there a workaround that anyone can think of? Thank you in advance! <DatePicker dateFormat="yyyy/MM/dd" selected={values.config[index].date} name={`config[${index}]['date']`} value={getIn(values, `config[${index}]['date']`) || "" } onChange={(e) => setFieldValue(`config[${index}] ['date']`, e)} className={"form-control" + (errors.date && touched.date? " is-invalid" : "") } />