Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration of video calling functionality with Django and Django Channels
I have created a chat application with Django using Django-Channels, but for enhancement I want to add video calling functionality as well. I'm not getting any Idea how i can achieve this task. Please provide me some references so that i can implement it. Currently after searching the only option I'm getting is WebRTC. But there is not proper documentation of it's interrogation with Django. -
Why am I not being able to save my addresses? django/ajax
I'm trying to develop an e-commerce website with django. I want to use ajax to handle my checkout form. When I added Ajax, after filling out the form and clicking the submit button, I am seeing that my form and data is not getting saved by going into my admin. It's also not being redirected to return HttpResponseRedirect(reverse(str(redirect))+"?address_added=True"), rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=u6hDPBVuOZbDmoHvRFWb2PvfK1YamCIKGSaDkKdVTviWvJODgY5lM6rKppoW1oeP&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on. Can anyone please help me out with what's wrong? My accounts.views.py: from django.shortcuts import render, HttpResponseRedirect, Http404 from django.contrib.auth import logout, login, authenticate from django.contrib import messages from .forms import LoginForm, RegistrationForm, UserAddressForm from django.urls import reverse def add_user_address(request): try: redirect = request.GET.get("redirect") except: redirect = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if redirect is not None: return HttpResponseRedirect(reverse(str(redirect))+"?address_added=True") else: raise Http404 My urls.py: path('ajax/add_user_address/', accounts_views.add_user_address, name='ajax_add_user_address'), My checkout.html: <form method="POST" action="{% url 'ajax_add_user_address' %}?redirect=checkout"> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-dark" type="submit">Place Order</button> </div> </form> -
Which is the best way to make backend for a small website? [closed]
Good afternoon! I'm currently working on a website, and front end is mostly done, now i want to implement authorization form. I got curious which way is better, i want to make a a back end system on a virtual machine using ubuntu. I just thinking which environment is better for simple website. I'm thinking of nodejs since i was using it for some API's or to use Python + Django. MongoDB as a database. Is there any resources that i can look into how to connect back end with front end when back end on virtual machine? And is it good way of doing it? Or better to do back-end internal? -
Djongo Using ArrayField throws Apps No Loaded Error on makemigrations
I am trying to create a django model using djongo which uses ArrayField class SubModel(models.Model): i = models.IntegerField() class Meta: abstract = True class BiggerModel(models.Model): subarr = models.ArrayField(model_container=SubModel) When I run makemigrations, I get the error AppRegistryNotReady("Models aren't loaded yet.") This is happening only if I use ArrayField. Not with any other fields I am using django 2.1.5 and djongo 1.3.2 -
Django Psycopg2 Error When Running Migrations in Testing
I developed a basic version of a Django app in SQLite3. Then, it came time to switch it to Postgres and put in production. When doing so, I noticed that I was able to create and run migrations for the new database. However, when trying to run tests for the Postgres version, I run into an issue. Here it is. I run tests with coverage run --source='.' manage.py test; however, the same thing happens when running via python manage.py test Creating test database for alias 'default'... Got an error creating the test database: database "test_app_web" already exists Type 'yes' if you would like to try deleting the test database 'test_app_web', or 'no' to cancel: yes Destroying old test database for alias 'default'... Creating test database for alias 'extra'... Traceback (most recent call last): File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column aldryn_people_person.name does not exist LINE 1: SELECT "aldryn_people_person"."id", "aldryn_people_person"."... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/commands/test.py", line 26, in run_from_argv super().run_from_argv(argv) File "/home/user/miniconda3/envs/app-web-test/lib/python3.7/site-packages/django/core/management/base.py", line … -
Django does not find static on all pages except the main
The project is hosted (support say to solve the problem yourself and therefore my friends hope for your help) and you can find it at: https://caparolcenterspb.ru All styles, pictures and js appear on the main page, but not on other pages. You can see the errors directly in the browser, but just in case I give a screen: -
How to measure latency of API calls?
I am building an API with Django. And I need to record the time it takes each user to ping the nearest server. The users communicate with the API through an Android app. The app uses a load balancer that assigns the user to the nearest server. I know that it's possible to ping the server with a computer to get the RTT, but I cannot find a way to get latency from an arbitrary user, which can only communicate with the server using the app. -
how to fetch data from database in django using phpmyadmin
model.py from django.db import models class Reg(models.Model): First Name = models.CharField(max_length=10) Email ID = models.CharField(max_length=20) TUID = models.CharField(max_length=10) Password = models.CharField(max_length=8) how to fetch data from database without using underscore in first name -
How to get fields of foreign key
In models.py: class Comment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField() rating = models.FloatField(null=True) aggregate = models.FloatField(null=True) date = models.DateTimeField(auto_now_add=True) class Item(models.Model): id_item = models.AutoField(primary_key='true') item_name = models.CharField(max_length=100, null=False) slug = models.SlugField(max_length=250, blank=True, null=True) item_description = models.TextField() item_img = models.ImageField(blank=True, null=True, upload_to="static/item/cover/") tags = TaggableManager() In views.py: def detail(request, slug_text): details = Item.objects.filter(slug=slug_text) if details.exists(): reviews = Comment.objects.filter(item=slug_text) details = details.first() average = reviews.aggregate(Avg("rating"))["rating_avg"] average = round(average, 2) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST, author=request.user, item=details) if form.is_valid(): form.save() return HttpResponseRedirect(slug_text) else: return HttpResponse('<h1>Trang không tồn tại</h1>') return render(request, 'homepage/detail.html', {'detail': details, 'form': form, 'average': average}) What if I want to get the item.slug = slug_text field in here? reviews = Comment.objects.filter(item=slug_text) -
TypeError at /gym/ninja/ninja() got an unexpected keyword argument
actually i am trying to sumbit the details from my contact from to them of my django app but i am facing same error with all the varriable i am am able to get the details from my html page and can print it in my vs code cmd but when i try to save it in my model i face same error for all variable so please can anyone help me with it enter code here html code <form method="POST" action=""> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="col"> <label for="inputEmail1">E-mail</label> <input type="text" class="form-control" name="emails" id="emails" placeholder="Enter your E-mail"> </div> <div class="col"> <label for="inputEmail2">Phone-Number</label> <input type="text" class="form-control" name="phones" id="phones" placeholder="Enter your phone number"> </div> </div> <div class="form-row"> <div class="col"> <label for="inputEmail1">Age</label> <input type="text" class="form-control" name="ages" id="ages" placeholder="Enter your age"> </div> <div class="col"> <label for="inputEmail2">Height</label> <input type="text" class="form-control" name="height" id="height" placeholder="Enter your height"> </div> </div> <div class="form-row"> <div class="col"> <label for="inputEmail4">Weight</label> <input type="text" class="form-control" name="weight" id="weight" placeholder="Enter your weight"> </div> <div class="col"> <label for="inputEmail3">Food Habit</label> <input type="text" class="form-control" name="habit" id="habit" placeholder="Are you veg/non-veg/vegan"> </div> </div> <br> <div class="form-group"> <label for="exampleFormControlTextarea1">Enter other important detail's</label> <textarea class="form-control" placeholder="Enter your message here....." id="messagess" name="messagess" rows="5"> Submit </form> my model that i have … -
proper name for custom User and Manager in Django
In my django project I've created a customized models for User and its manager class. I named them User (which inherits from AbstractUser) and UserManager (which inherits from BaseUserManager). Given that these are the default django's name for those models, is there any problem in that? I run the following form django shell: >>>from django.contrib.auth import get_user_model >>>user = get_user_model() >>>user.objects These are the outputs: <class 'myapp.models.models.User'> <class 'myapp.models.models.UserManager'> Apparently no conflicts are shown, so it seems to be all right. I hope some django experts could confirm me I won't have any surprise later on through the development. -
The right decision to use images of different sizes on the site
I have a question about how to organize the work of loading images into the backend for working with the tag in templates. I have two solutions that I thought of: Download one image, then make it functional to access a specific URL and get a specific size. Download the image, and then run the celery task, which using the Pillow will create copies of the image in the same folder. The names of the copies will be something like: tumbnail.jpg, small.jpg, etc. Which method does the majority use, or which is better, why? -
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']