Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Model not updating
I have a Django model named User_Table. I want to update some data in it (particularly the OTP field and related stuff). I used this code - user_obj User_Table.objects.get(phone=phone) user_obj.otp=otp user_obj.time=datetime.datetime.now() user_obj.deviceuid='null' try: user_obj.full_clean() user_obj.save() print(user_obj.otp, User_Table.objects.get(phone=phone).OTP) return init_utils.reponse_for_save_id_output(True, None) except Exception as e: return init_utils.reponse_for_save_id_output(False, str(e)) When I runserver, the print statement above returns a random number (which it should, as an OTP is supposed to be random), and the second one is the older OTP value (which is supposed to be the random string printed first). In the Django admin, the OTP field has the older value. I have checked the otp variable's value and it is the right random string, the other fields, like name and deviceuid get updated. user_obj.OTP itself outputs that OTP is the right random string, which I guess should mean that the right otp is in user_obj. Why is django only updating a few fields and just leaving the otp field as it was? -
pip install mysqlclient with Python 3.8 not working
I have a django project with Python 3.8 and I am trying to install mysqlclient library through: pip install mysqlclient command. I got this error: MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2 I tried installation by using wheel file from where ( I tried every wheel from this site ) but I got the error: *...is not a supported wheel on this platform.* I tried to install it from the source but when I run this command python setup.py install I got the same error: MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe' failed with exit status 2 I tried this command pip install --only-binary :all: mysqlclient and I got the error: Could not find a version that satisfies the requirement mysqlclient (from versions: ) No matching distribution found for mysqlclient Please let me know if you have some suggestions. Thank you! -
Django Celery kombu issue
I am getting this issue while running Django celery: File "c:\python37-32\lib\site-packages\celery\utils\timer2.py", line 19 from kombu.async.timer import Entry, Timer as Schedule, to_timestamp, logger ^ SyntaxError: invalid syntax Celery version 3.1.25 Redis server version 2.4.5 (00000000:0) -
Updating Django
Why when I'm updating my Django to 3.0.5 my old Django version that I use has been removed. All codes are not working. What should I do if want to update my Django to latest version. And Keep my old version. -
Django Invitation mail issue
I am building an app where a user can send invite link to other users through mail. And its working fine. Now I want to send the link as a button instead of a raw link. But When I am trying to do that the button is redirecting to a page with incomplete URL. The localhost part is missing from the URL. Please suggest how can I attach the complete URL to the button. I am using send_mail from django.core.mail and render_to_string method to convert the HTML file. -
Is there a way I can create a widget interaction i
I am developing a new personal webpage. Here, I want to create a Graphical User Interface / Interactive Widgets that allows the user to move a skier up and down on the screen. The point is that the user can observe how these changes affect the velocity of a skier the bottom of the hill. I want this to be informative and want to use for educational purposes. Now the question is where should I start? I have created the webpage in Django as can be seen[here][1]. I have just started. Some options I have thought about: 1. Use Dash Plotly but here my problem is to understand how I can draw shapes and patches and interact with them 2. Use Matplotlib but then there is a problem to make this a web app? I would very much appreciate your help. Best, Christian -
Django Rest Framework no module named rest_framework but is installed
I do my first steps with the Django REST Framework. But when I do: python3 manage.py makemigrations && python3 manage.py migrate I get this error: ModuleNotFoundError: No module named 'rest_framework.renderers' I have checked the settings.py: INSTALLED_APPS = [ 'api', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] I checked pip3 if the package is installed: Django==3.0.5 django-rest-framework==0.1.0 djangorestframework==3.11.0 This is the code snippet where I use it and where I get the error: from django.http import HttpResponse from rest_framework.renderers import JSONRenderer from rest_framework.decorators import api_view from .models import Repo, Category from .serializers import repoSerializer, categorySerializer I do not know where the error is. Can somebody give me a hint? Is maybe there a problem with the migration? -
How to store/create data with multiple dates for the same timetable
I have a model of a timetable as below:- class time_table(models.Model): username = models.ForeignKey(User,db_column="username", on_delete=models.CASCADE,) sem_section = models.ForeignKey(sem_sections, db_column = "sem_section",on_delete=models.CASCADE,) subject_id = models.ForeignKey(subjects,db_column="subject_id", on_delete=models.CASCADE,) day_name = models.ForeignKey(days_ref, db_column = "days_ref",on_delete=models.CASCADE,) hour_no = models.ForeignKey(hours, db_column = "hour_no",on_delete=models.CASCADE,) def __str__(self): ret = str(self.username) +' takes ' + str(self.sem_section) + " class " + str(self.subject_id) + " on " + str(self.hour_no) + " on " + str(self.day_name); return ret class Meta: constraints = [ models.UniqueConstraint(fields=['sem_section', 'day_name', 'hour_no'], name='Allotment_check') ] I have to create multiple records that repeat for each tuple that is inserted like if i insert a slot for monday 4th hour having some subject it must be created for multiple recurring dates of the whole year or semester. Any sugestions on how to tweak the code or any extra code to add to achieve this goal. I am using Postgres for database. -
ProgrammingError at /api/profiles/ relation "DIApp_userprofile" does not exist?
I am creating a custom user model and i am using postgresql_psycopg2 as my database. I am able to create superuser and add user from there but when i create browsable api to create user i am getting an error. My views.py file: class UserProfileViewSet(viewsets.ModelViewSet): """Handle creating, creating and updating profiles""" serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.objects.all() my urls.py file: router.register('profiles', views.UserProfileViewSet) path('', include(router.urls)) So when i try the same using SQLite as database, it is working. I am using django 2.2 and djangorestframework 3.9.2 -
How to filter in views ? Django
If I want to filter information belonging to the person I clicked in, And it must show information for that person only. How can I filter in views? For example, I clicked on to see Spiderman's information and I had to divide that page to show the Spiderman event music video. How can I filter? my models.py app(actor) class Actor(models.Model): name = models.CharField(max_length=255, null=True, blank=True) picture = models.ImageField(null=True, blank=True) my views.py app(actor) class ActorDetailView(DetailView): model = Actor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["event"] = Event.objects.filter(.........) return context Event model that I will filter the data to show in actor.html class Event(TitleSlugDescriptionModel): actor = models.ForeignKey("actor", null=True, on_delete=models.SET_NULL) date = models.DateField() time = models.TimeField() image = models.ImageField(upload_to="images) What should I do? Thank you very much -
Run Python script in Django template through a button
I have a very small project in Django where I get fx_rates through a Python script (details below). These are used to convert amounts in different currencies to GBP. I would like to know how I can just have a button on the website that allows to refresh this query instead of having to run it manually in the IDE. Can I create a view for this? How would I show this in a template? Thanks fx_rates.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','fx_rates_project.settings') import django django.setup() from fx_rates_app.models import fx_table import pandas_datareader.data as web from datetime import datetime os.environ["ALPHAVANTAGE_API_KEY"] = '#########' fx_gbp_to_eur = web.DataReader("GBP/EUR","av-forex") eur = float(fx_gbp_to_eur[4:5].values[0][0]) fx_gbp_to_aud = web.DataReader("GBP/AUD","av-forex") aud = float(fx_gbp_to_aud[4:5].values[0][0]) fx_gbp_to_usd = web.DataReader("GBP/USD","av-forex") usd = float(fx_gbp_to_usd[4:5].values[0][0]) from datetime import datetime now = datetime.now() dt_string = now.strftime("%d/%m/%Y %H:%M:%S") webpg1 = fx_table.objects.get_or_create(eur_to_gbp=eur,aud_to_gbp=aud,usd_to_gbp=usd,date_time=dt_string)[0] -
Django didn't apply new modifications
I deployed my Django app, then I edit the source code, but my edits didn't applied. example: class Type(models.Model): seller = models.ForeignKey(Profile, related_name="cam_seller_profile", on_delete=models.CASCADE) label = models.CharField(max_length=150, null=True, blank=True) slug = models.SlugField(max_length=255, unique=True, blank=True) def __str__(self): return "test" the new update: def __str__(self): return self.seller.user.username result still the same as old I tried this to reload nginx but didn't work: service nginx reload sudo systemctl restart nginx sudo systemctl daemon-reload -
taking request user on Models.py DJANGO
Thanks for your time: I've got a model(Pets) that has a foreign key to other (People) and people has a OnetoOne (User). I'm trying to call the errors on a ModelForm doing the clean method on Models.py. although the foreign key field of Pets is set to be the request.user.person (reversed OneToOne field of User with People). When i try to save the form i get the error: models.py: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE, related_name='peop') nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) def clean_fields(self, exclude=None): super().clean_fields(exclude=exclude) slug = slugify(self.pessoa) if slug.startswith('a') and self.tipo == 2: if exclude and 'pessoa' in exclude: raise ValidationError('pessoas com a nao podem ter gatos') views.py: def create_pet_form3(request): if request.method == 'POST': form = PetForm5(request.POST) if form.is_valid(): pet = form.save(commit=False) pet.pessoa = request.user.person pet.save() else: raise ValidationError('corriga os erros') else: form = PetForm5() context = { 'form': form } return render(request, 'petform2.html', context) forms.py: class PetForm5(forms.ModelForm): class Meta: prefix = 'pet' model = Pets fields = ['nome', 'custo', 'tipo'] exclude = ['pessoa'] -
django 3 project application error on Heroku
i am trying to learn django based on the following tutorial, https://djangoforbeginners.com/pages-app/ i follow exactly the tutorial and run in to application error on heroku. I repeatedly check all the steps and redo several times and still didn't work. On local machine, the project works fine but after hosting on Heroku, it fails. i run heroku logs --tail --app appname and get the following: 2020-04-16T05:29:03.008550+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=damp-earth-41063.herokuapp.com i also search on this issue around and found the same issue but the answers didn't work either, like Django: Heroku Failing to launch, at=error code=H10 desc="App crashed" and Heroku Django app returning error heroku/router: at=error code=H10 desc="App crashed" Hopes you can provide me direction on how to deal with this. python 3.8.2 Django 3.0.5 gunicorn 20.0.4 pipenv 2018.11.26 thanks in advance -
How can I redirect with Primary key?
I'm doing an ecommerce project in which I have products page where the-end user can see list of products. What I want is that I the-end user to be able to see the product_detail page when the user clicks on product name like on amazon with primary key. mysql table description list of products -
Upload Large video file to Azure Blob using Javascript. for now file size should be 150GB as the max
function uploadBlobFromText() { // your account and SAS information var sasKey ="*******************"; var blobUri = "*************************"; var blobService = AzureStorage.File.createFileServiceWithSas(blobUri, sasKey); var files = document.getElementById('id_video_file').files; var file = files[0]; var customBlockSize = file.size> 1024.1024*32 ? 1024*1024 *4 :1024 *512 blobService.singleBlobPutThresholdInBytes = customBlockSize; var finishedOrError = false; var speedSummary = blobService.createFileFromBrowserFile('containername', 'directoryname', file.name, file, {}, function(error, result, response)) { finishedOrError = true; if (error) { console.log(error);} else {alert('Upload successfully!'); } }); };` this is i have done but giving me error StorageError {name: "StorageError", message: "An HTTP header that's mandatory for this request i…ae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z", code: "MissingRequiredHeader", headername: "x-ms-blob-type", statusCode: 400, …} name: "StorageError" message: "An HTTP header that's mandatory for this request is not specified.↵RequestId:bf55651e-401e-0103-7bae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z" code: "MissingRequiredHeader" headername: "x-ms-blob-type" statusCode: 400 requestId: "bf55651e-401e-0103-7bae-1366fb000000" stack: "StorageError: An HTTP header that's mandatory for this request is not specified.↵RequestId:bf55651e-401e-0103-7bae-1366fb000000↵Time:2020-04-16T05:22:06.4629956Z↵ -
Django - Aggregate with a Case where the values are not from the database
Let me start with saying that: Yes I know that I can just save the ratings as number to my database and I know it would be a lot easier that way. Nonetheless, if I was doing it this way(I am, I shouldn't be most probably but I am) so I want to solve it with the current setup as is, with only adjusting the rating_point property if possible. utils.models.Choices is basically a wrapper around regular python dictionaries, can share that too if needed. Tried to keep the code as clean as possible and am showing you all as little as possible to avoid any confusion, still seems large but I think all has to be here to easily debug it. from django.db import models from django.db.models import Avg, When, Case, Value from mptt.models import TreeForeignKey from utils.models import Choices class Product(CommonFields, ProductRelatedMixin): @property def rating_point(self): comment = self.comments.model return self.comments.aggregate( whatever=Avg( Case( *[ When( rating=rating, then=Value(comment.rating_points_map.get(rating)) ) for rating in comment.ratings.choices ], output_field=models.IntegerField() ) ) ) class Comment(CommonFields): ratings = Choices( POOR="POOR", OKAY="OKAY", GOOD="GOOD", AMAZING="AMAZING", EXCELLENT="EXCELLENT", ) rating_points_map = { ratings.POOR: 1, ratings.OKAY: 2, ratings.GOOD: 3, ratings.AMAZING: 4, ratings.EXCELLENT: 5, } user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='comments') product = models.ForeignKey('Product', … -
Django webapplication displaying source code in chrome, but working fine in firefox
In search portal of django, when the button search is clicked, it's displaying results in source code in chrome and newer versions of firefox. But, it's working fine in older versions of firefox. Is there anything to be done with code -
Django showing unnecessary information
I got my python script to run the way I want it, but for some reason I am getting some info showing up that I do not want. In this image, I dont want anything printed before the word "Acute". My python code is getting a wikipedia article, summarizing it, and printing the best sentences. However, no where do I have code to print the other stuff that is showing up. Once the generate button is clicked (which in this case it is) Here is my code: urls: from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.urls import path from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.button), url(r'^output',views.output,name="script"), url(r'^external',views.external), ] Views.py from django.shortcuts import render import requests from subprocess import run,PIPE import sys def button(request): return render(request,'index.html') def output(request): data=requests.get("https://regres.in/api/users") print(data.text) data=data.text return render(request,'index.html',{'data':data}) def external(request): out=run([sys.executable,'textSummary.py'],shell=False,stdout=PIPE) print(out) return render(request,'index.html',{'data1':out}) index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Card layout</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"/> <link href="https://fonts.googleapis.com/css2?family=Dancing+Script&display=swap" rel="stylesheet"> </head> <body> <h1 class="StorySpinner"><u>Story Spinner</u></h1> <main> <div class="container"> </div> <section class="cards"> <div class="card"> <div class="card__image-container"> <img … -
What is the correct way to link home and about page in django urls?
Right now what I am doing is this: pages app > urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about', views.about, name='about'), ] project > urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) This seems to work fine. I am able to go to the homepage and the about page fine, but I have seen other people do as in the following: project > urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), path('about/', include('pages.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) So basically, in the project urls file, the line 'path('about/', include('pages.urls')),' is added. So I was wondering what is the correct way of linking the about page in the project urls file. -
Django - Heroku push succeeds but getting AttributeError (module has no attribute)
I pushed my web app to Heroku and it built / deployed fine, but I get this error when I access it: AttributeError at / module 'wakemeup.models' has no attribute 'environment' Exception Location: /app/lib/UsefulFunctions/googleUtils.py in <module>, line 16 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] It works fine locally, so my first thought was a PYTHONPATH issue, but it seems to be similar: Python Path: ['C:\\Users\\ravioli\\projects\\dcp', 'C:\\Program Files (x86)\\Python38-32\\python38.zip', 'C:\\Program Files (x86)\\Python38-32\\DLLs', 'C:\\Program Files (x86)\\Python38-32\\lib', 'C:\\Program Files (x86)\\Python38-32', 'C:\\Program Files (x86)\\Python38-32\\lib\\site-packages'] Directory structure (simplified) googleUtils.py (simplified) import os import sys import io import copy from urllib.error import HTTPError # Import - Google from google.oauth2 import service_account ... # Import - Application from lib.UsefulFunctions.dataUtils import get_setting import wakemeup.models.environment as env class GoogleDriveManager(): ... I originally had the import wakemeup.models.environment as env line as from wakemeup ... import but that was giving me a circular dependency error, so I changed it and it works fine locally. Not sure if that has to do with it. How can I fix this so it works on Heroku? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x102980b70>
I have been trying to fix this but I am not able to understand it. I am using Python 3.7.2, Django 2.1.11 and Django-weasyprint 0.5.4. I have read other issues like these but none of them fit my problem. I have tried fixing the issue of value error by using export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 but these also does not seem to be working. Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x102980b70> Traceback (most recent call last): File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/nirwan/Desktop/CASS-Degrees-Code/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen … -
Django how to assign a function for sending emails from to an HTML button
I am new to django and i would like to know how i can give the function "Initial_Report(request):" to an html button so that every time is clicked it performs the given function. Views code def home(request): return render(request, 'home.html') def Initial_Report(request): noc_emails = Employee.objects.exclude(Position__Position__contains='Customer').values_list('Email', flat=True) cs_emails = Employee.objects.filter(Position__Position__contains = 'Customer').values_list('Email', flat=True) noc_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', noc_emails) cs_message = ('Initial Outage Report', 'This is a new outage report ,The information is in the document', 'from@example.com', cs_emails) send_mass_mail((noc_message,cs_message), fail_silently=False) return render(request,'InitialReport.html') Urls urlpatterns = [ path('', views.home, name='home.html'), path('admin/', admin.site.urls), path('Initial_Report', views.Initial_Report, name = 'Initial_Report' ), ] Home.html <button> Send Initial Report</button> -
Django Celery RabbitMQ access denied (403) ACCESS_REFUSED
I have a django project with heroku with celery integrated. I've got the rabbitmq add-on through heroku and have tested my task locally to success. The issue I'm having is connecting my remote server to rabbitmq/cloudamqp. I believe the credentials I'm using are the culprit of the problem, but I'm unsure where I'm going wrong. I'm using the credentials provided to me via the cloudamqp dashboard. This includes: AMQP URL User & Vhost Password In my settings.py I have: CELERY_BROKER_URL= "amqp://{User}:{Password}@{AMQP URL}:5672/" I've tried a variety of other forms with similar results. The latest error output is: amqp.exceptions.AccessRefused: (0, 0): (403) ACCESS_REFUSED - Login was refused using authentication mechanism AMQPLAIN. For details see the broker logfile. Am I using the right credentials? Do I need to create a rabbitmq user through the command line and not the admin dashboard? -
How can I filter a Django query with a list of values in queryset?
I am new to this, and can't figure out where I've gone wrong. I am using the Django rest framework my output is like this I want to use the filter in "views.py" to filter by "rate_types".how can I write a query for this case? [ { "submitted_candidate_id": 1, "submit_candidate": [ { "candidate": [ { "rate_types": "Daily", }, { "rate_types": "Daily", }, ] } ] } ]