Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django server Google Id_token verification using google.oauth2.id_token.verify_oauth2_token() not working
I'm trying to build a flutter app with django backend and need to implement google authentication as well. After receiving the Id_token from google, I send it to my django server. Whilst trying to verify google Id_token from my django server using google.oauth2.id_token.verify_oauth2_token(), it's always showing bad request. I'm passing id_token, requsts.Request() and Client_id of my flutter fronted app as the arguments. Is there any problem with the arguments passed? Is there anything I should do related to google, like creating an Oauth id for my backend server, or something like that.? I tried the solution given here but still not working. -
Run external application using Django
I am creating a django backend. In it I want to run an external Python application I wrote, when someone clicks a button. My project is distributed as follows: external_application_folder main_django_project_folder django_app_folder The way I am currently doing it is, I have created a html file which has a form in it <!DOCTYPE html> <html> <head> <title> ABM TRY </title> </head> <body> <form method="POST">{% csrf_token %} <button type="submit" name="run_external_code"> Run</button> </form> </body> </html> Inside the django_app's views.py I have from external_application_folder.run import external_function def ex_view(request): if request.method=='POST' and 'run_external_code' in request.POST: external_function() return render(request,"html_file.html",{}) whenever I run python manage.py runserver I get the following Watching for file changes with StatReloader Performing system checks... and then everything works. I am new to django, is this the best way to run external application using backend? -
Create a relation without a foreign key
How can I create a "belongs to" relationship in Django without creating a foreign key on the DB layer? -
EC2 .bashrc and .bash_profile re-setting
Reason I'm asking: pycurl requires both libcurl-devel and openssl-devel. To install these, I have these two lines the my .bash_profile: sudo yum install libcurl-devel sudo yum install -y openssl-devel Previously, I just ran those commands in the terminal while ssh'd into the EC2 instance. However, it seems that at random times those lines are cleared from the .bashrc and .bashprofile, and the packages no longer exist in the instance. Why is this happening? Is the EC2 instance refreshing to a clean version at some point? If so, why? And how can I ensure those two packages are default installed on every instance? When I eb deploy I still see the .bashrc and .bash_profile contain the yum install commands. The timing the files are refreshed seems random, and I can't figure out why. -
django many to many through forms
tengo una relación muchos a muchos, con una tabla intermedia con campos extra. Quiero crear un formulario que me permita ingresar un producto, y poder elegir un precio para 1 o más mercados. No logro resolver las views, para crear este formulario e imprimirlo en un template. Podrán ayudarme? Como debería quedar el formulario: Relación: Modelos: class Market(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=250) market = models.ManyToManyField(Market, through='Link') class Link(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) link = models.CharField(max_length=250) class Meta: unique_together = [['producto', 'supermercado']] Formularios: class MarketForm(ModelForm): class Meta: fields = ['name'] model = Market class ProductForm(ModelForm): class Meta: fields = ['name'] model = Product class LinkForm(ModelForm): class Meta: fields = ['market','product','link'] model = Link -
Django App on Elastic Beanstalk not Inserting to Specific Model in Deployed Version (works locally)
I have a Django web application that is hosted on AWS Elastic Beanstalk, with a PostgreSQL database on AWS RDS. I have a strange issue where data updates in the UI are inserted to the model locally, but not in the deployed version. Additionally, it's only for one specific model. The other models take UI inputs fine in the deployment. Again, this works perfectly locally, but not when deployed to Elastic Beanstalk. The weird part is that the other models in the application work fine in both local and deployed versions. Since it works locally, and only one model is impacted I don't necessarily know what code would be beneficial to post, and don't want to flood the post with unecessary code but I will be happy to provide relevant code. Any help would be greatly appreciated! I have reviewed the RDS logs, the Elastic Beanstalk logs, and access the EB instance using eb ssh to review additional logs there but find no indication of an error occurring. -
How to restart or reload Django when using it with gunicorn and nginx
I am new to Stackoverflow so i am sorry if i am a little bit of course I recently started to learn Django i am a noob at it still , i just installed django with gunicorn and nginx on a Ubuntu 20 server, and now i am configuring my server but i cant find how to reload or restart Django , any help? I added my domain to allowed_host and saved the file and its not reloading the config i needed to restart the server to reload and then i needed to go back into the venv stop nginx start gunicorn and start nginx again to work , i cant be doing this at evry change i make , and at this topic any ideea how can i make gunicorn start with nginx corectly? -
Django Simple History: Don't want to track User
I'm working on a Django project, and I'd like to use Django Simple History to track changes to records. However, I'm facing an issue: I don't want to track the user who made the change (I'm not using Django's auth app). When I try to perform the migrations, I receive this error message: SystemCheckError: System check identified some issues: ERRORS: my_app.HistoricalModel.history_user: (fields.E300) Field defines a relation with model 'auth.User', which is either not installed, or is abstract. data_lake.HistoricalInstance.history_user: (fields.E307) The field my_app.HistoricalInstance.history_user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. Is there a way to use the HistoricalRecords model disabling references to user model? -
FactoryBoy factory that does NOT generate an 'id' for an unmanaged Django model?
I've got a factory that I need to just generate the data I want it to - without having it create an 'id' attribute. I have a couple factories that look like this: class RatedPersonalityFactory(PersonalityFactory): person__end_year = get_end_year() rating_information__create_rating = False rating_information__section = None class Params: pass @post_generation def person(obj, create, extracted, **kwargs): PersonFactory( personality=obj, personality_id=obj.id, state_id=1234, first_name=obj.identity.first_name, last_name=obj.identity.last_name, middle_name=obj.identity.middle_name, birth_date=obj.identity.birth_date, number=obj.student_number, end_year=kwargs["end_year"], ) class PersonFactory(DjangoModelFactory): class Meta: model = Person database = "alternatives" django_get_or_create = ("personality_id",) class Params: # This will create the Personality that we can then use attributes from personality = SubFactory(PersonalityFactory) current_end_year = get_end_year() personality_id = SelfAttribute("personality.id") state_id = 1234 first_name = Faker("first_name") last_name = Faker("last_name") middle_name = Faker("first_name") number = SelfAttribute("person.student_number") active_year = 1 birth_date = Faker( "date_between", start_date=(datetime.now() - relativedelta(years=14)).date(), end_date=datetime.now().date(), ) start_date = Faker( "date_time_between", start_date="-1y", end_date="now", tzinfo=py_timezone(settings.TIME_ZONE), ) end_date = None end_year = LazyFunction(get_end_year) gender = Iterator(["M", "F"]) native_lang = "EN" The model looks like this: class Person(models.Model): personality_id = models.IntegerField(db_column="personalityID") state_id = models.IntegerField(db_column="stateID") first_name = models.CharField(db_column="firstName", max_length=35) last_name = models.CharField(db_column="lastName", max_length=40) middle_name = models.CharField(db_column="middleName", max_length=30) number = models.IntegerField(db_column="studentNumber") active_year = models.IntegerField(db_column="activeYear") birth_date = models.DateField(db_column="BirthDate") start_date = models.DateField(db_column="startDate") end_date = models.DateField(db_column="endDate", null=True) end_year = models.IntegerField(db_column="endYear") gender = models.CharField(db_column="gender", max_length=1) native_lang = models.CharField(db_column="languageAlt", … -
How to get a queryset of foreign keys from a current queryset in django
I have two models, Employee and Manager. The Employee model has a foreign key to Manager. Given an arbitrary queryset qs of Employee objects, I would like to get a queryset of their managers. This seems very simple but I can't find a way to do it. In naive python, I could get a list of these managers by doing something like: qs = Employee.objects.filter(whatever) managerlist = [] for emp in qs: managerlist.append(emp.manager) and this would give me a list of managers corresponding to employees in my queryset. But instead of a list I would like a queryset. Is there a quick simple way to do this? -
I have performance issue with apex charts
I have 3 async charts on one page and total number of data on the page is about 15k, but the chart is lagging a lot. Data is from the backend I use Django templates to iterate over specific data and add that data to the chart. First chart: var options = { series: [{ name: 'Fed Fund Rate', data: [ {% for int in interest %} { x: "{{int.interest_date}}", y: ["{{int.strategy_interest}}"], }, {% endfor %} ] }, ], chart: { id: 'chart_1', group: 'social', height: 300, type: 'line',`your text` animations: { enabled: false }, zoom: { type: 'xy' }, }, dataLabels: { enabled: false }, yaxis: { type: 'numeric', }, xaxis: { type: 'datetime', }, }; var chart = new ApexCharts(document.querySelector("#chart-int"), options); chart.render(); Second: var options = { series: [{ name: 'OHLC', data: [ {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} ] }, ], chart: { height: '100%', id: 'chart_2', group: 'social', type: 'candlestick', animations: { enabled: false }, }, dataLabels: { enabled: false }, title: { text: '{{ticker}}', align: 'center', style: { fontSize: '24px', fontFamily: 'calibri' } }, yaxis: { type: 'numeric', }, xaxis: { type: 'datetime', … -
Setup an email notification when consumer: Connection to broker lost in celery
I want to implement an email system which will send an email whenever my celery worker lost connection with my Redis server. Whenever it lost connection it gives warning: [2023-03-02 21:33:48,272: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... And starts reconnecting with the server [2023-03-02 21:33:48,286: ERROR/MainProcess] consumer: Cannot connect to redis://127.0.0.1:6379//: Error 61 connecting to 127.0.0.1:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) I am using django 3.2.8 and celery 5.2.7. I went through the whole celery docs and source code I get to know there is a method on_connection_error_after_connected in the celery.worker.consumer.connection which get's triggered when it lost connection. -
Data not rendering in Cytoscape.js in the Django template
I am trying to display the data in the Django template in the form of graph. I am getting the data from Neo4J and for querying I am using neomodel. First I am serializing the data in the form of JSON accepted my Cytoscape.js. This is my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Graph View</title> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.min.js" integrity="sha512-gEWKnYYa1/1c3jOuT9PR7NxiVI1bwn02DeJGsl+lMVQ1fWMNvtjkjxIApTdbJ/wcDjQmbf+McWahXwipdC9bGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.8.4/cytoscape.min.js" integrity="sha512-gn5PcEn1Y2LfoL8jnUhJtarbIPjFmPzDMljQbnYRxE8IP0y5opHE1nH/83YOuiWexnwftmGlx6i2aeJUdHO49A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> #cy { width: 300px; height: 250px; display: block; background-color: #fff; } </style> </head> <body> {{data}} <div id="cy"></div> <div id="test"></div> <h2>Hello</h2> <script> var my_graph_data = JSON.parse('{{ data|escapejs }}'); var cy = cytoscape({ container: document.getElementById('cy'), elements: '{{data}}', style: [ { selector: 'node', style: { 'label': 'data(label)', 'width': '60px', 'height': '60px', 'color': 'blue', 'background-fit': 'contain', 'background-clip': 'none' } }, { selector: 'edge', style: { 'text-background-color': 'yellow', 'text-background-opacity': 0.4, 'width': '6px', 'target-arrow-shape': 'triangle', 'control-point-step-size': '140px' } } ], layout: { name: 'circle' } }); </script> </body> </html> This is the format of my data when I print my json [{'data': {'movieName': 'Matrix', 'director': 'John', 'rating': 9.0}}, {'data': {'movieName': 'John Wick', 'director': 'Bill', 'rating': 8.0}}] When I try the different data with same format I get the graph [ { 'data': { id: 'a', name: 'Sheraton … -
Running django migration gives "Wait for backup lock" in mysql
I am trying to run a django migration that creates 3 models and deletes 1 model with 350k rows. However, after running the migration, my mysql database is waiting for backup lock. <id> <admin> <ip>:<port> database_test Query Waiting for backup lock CREATE TABLE `table` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `column1` double precision NOT NULL, `column2` bigint NULL, `column3` bigint NULL) How can I resolve waiting for backup lock and what does it mean? -
{% if {club.c_type} == 'Tech' %} is giving error Code is working perfectly without it. Want to filter data on basis or Tech and Non Tech in same Page
{% for club in clubs %} {% if {club.c_type} == 'Tech' %} SOME CODE {% endif %} {% endfor %} def clubs(request): clubs_data = Clubs.objects.all() return render(request, 'clubs.html', {'clubs': clubs_data}) CLUBS_TYPE = {('T', 'Tech'), ('NT', 'Non-Tech')} class Clubs(models.Model): club_id = models.CharField(primary_key= True, max_length=5) c_name = models.CharField(max_length=50) c_logo = models.ImageField(upload_to='clubimg') c_type = models.CharField(choices=CLUBS_TYPE, max_length=2) -
I want to run "python manage.py makemigrations ". Got error "password authentication failed""No changes detected"
I want to run: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ python manage.py makemigrations And got this error: /home/ubuntu/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "diEvaR6s52EqJv" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "diEvaR6s52EqJv" warnings.warn( No changes detected I changed password for user and os: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ sudo -u postgres psql Password for user postgres: psql (14.6 (Ubuntu 14.6-0ubuntu0.22.04.1)) Type "help" for help. postgres=#ALTER USER diEvaR6s52EqJv WITH PASSWORD '#####'; (venv) ubuntu@ip-172-31-44-136:~$ sudo passwd postgres New password: And I ran: (venv) ubuntu@ip-172-31-44-136:/etc/postgresql/14/main$ sudo -u postgres psql Password for user postgres: (venv) ubuntu@ip-172-31-44-136:/etc/postgresql/14/main$ psql -U postgres Password for user postgres: Got error: psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: password authentication failed for user "postgres" I can't understand what do I have to do. Can anyone give me some advice? Almost struggling for a week. -
Django logging - logger from a module?
According to documentation I have to specify the LOGGING variable in settings.py Is it possible to pass logger from my custom module in django instead? For example, I have a following module: import logging import os class CustomFormatter(logging.Formatter): grey = "\x1b[38;20m" blue = "\x1b[1;34m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" logging_message_format = "\n%(asctime)s - (%(filename)s:%(lineno)d) - %(name)s - %(levelname)s - %(message)s" FORMATS = { logging.DEBUG: blue + logging_message_format + reset, logging.INFO: grey + logging_message_format + reset, logging.WARNING: yellow + logging_message_format + reset, logging.ERROR: red + logging_message_format + reset, logging.CRITICAL: bold_red + logging_message_format + reset } def format(self, record): log_fmt = self.FORMATS.get(record.levelno) formatter = logging.Formatter(log_fmt) return formatter.format(record) LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL', 'INFO').upper() logger = logging.getLogger("api") logger.setLevel(LOGGING_LEVEL) ch = logging.StreamHandler() ch.setLevel(LOGGING_LEVEL) ch.setFormatter(CustomFormatter()) # Set to False if too much output in container logger.propagate = True logger.addHandler(ch) I'm using it for logging in tests, as well as database and intending to use the same module for celery logging (probably modifying it a little bit). Is it possible to re-use the module for Django's runserver logging as well? -
Django built-in template tag to convert UTC to datetime?
Is there any way to convert a UTC, defined with models.CharField, to datetime using a built-in filter template tag? Or must i use a custom function (see below)? I have found nothing on this specific topic online. Here is an example Inside models.py: ... boarding_time_utc = models.CharField(max_length=15, default="14:00") ... def show_boarding_time(self): date_time = datetime.fromtimestamp(int(self.boarding_time_utc)) reable_date_time = date_time.strftime('%H:%M') return str(reable_date_time) Inside example.html: <td>{{ entry.show_boarding_time}}</td> Thats pretty much it. Thanks in advance! -
What are some ways to display images on server for a Django project? I keep getting 404 errors
A current miniproject that I am working on is a personal cocktail "cookbook" website, where I display different drinks, their recipes, my personal notes, images, etc. I configured the code in that when someone clicks on one of the many drinks that are displayed under a base alcohol category, they will be navigated to that one specific drink and be shown its attributes. The only thing that I haven't been able to do is having the server correctly display the image associated with the drink. Whenever I run the server and click on a specific drink, that entries' contents are shown in the correct format, but the image only appears as an icon and the server console keeps giving a 404 not found error. On Django admin, I am able to save images whenever I create a new entry, and VScode shows the correct location as to where the images are stored. I made sure that libraries like Pillow and Whitenoise have been downloaded. I also checked the MEDIA and STATIC section of my settings.py file to check the path configuration of where the images can be stored and served. But, so far, the server keeps giving a 404 error … -
phonenumber field authentication error in django
i am making a login function in django where user will input their phone number and password, they can access the account. but when i run the server, i get error that invalid phone number and password, but i registered proper phone number and password. I did some troubleshooting and come to know that phone number data is not showing. here's my code models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from .manager import MyUserManager # Create your models here. class MyUser(AbstractBaseUser, PermissionsMixin): username= models.CharField(max_length=50, null=True) phone_number = PhoneNumberField(unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return self.phone_number.as_e164 def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm from phonenumber_field.formfields import PhoneNumberField from .models import * class MyLoginForm(AuthenticationForm): phone = PhoneNumberField() password = forms.CharField(label='Password', widget=forms.PasswordInput) views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import MyLoginForm # Create your views here. def my_login(request): if request.method == 'POST': form = MyLoginForm(request, request.POST) if form.is_valid(): phone_number = … -
Choosing a right size for e-commerce platform images (grid-item, item, full-size item?)
I'm now a bit lost and can't find the right way or the best practice of choosing the right size of the image. I know that the image sizes should be optimal and not too big or small. So I've read and found that optimal size should be 800x800? So let's start with the things that I will be using in the front-end. So first of all I will have a grid in which I will display from 1 to 4 items in a row. The grid item has a max-width:574px; max-height:409px;. Let's continue to the main item page. I wish to display a slider in which the image should be centered and not full-width. Two things here, I don't really know what the wrapper should look like. This image has 700x109 but it does stretch to fill all the width, I would love to prevent it from happening. Another question is how should I process user uploaded images? Should I prevent users from uploading images that are smaller than 800x800 or something? How should I resize them, what resolutions should I save in our server? This is the grid-item with the visible size: f -
How to customise Folium html popups in a for loop in Django views?
I am trying to change the standard popups provided with Folium and make these work with a for loop. I am using Django. I succeeded on change the html, following a few tutorials. However I am struggling to understand how to call the variables in the html. Quite simply I have a map with a list of locations. If the user click on the locations the popup appear and would display logo, name and a few other things specific to the location. what I tried I tried different iteration including adding {{venue.name}} but clearly this doesnt work if I am not in the template.py. The current one """.format(venue.name)+""" is an example I found on a tutorial. However I must be missing something as this is not working for me. (https://towardsdatascience.com/use-html-in-folium-maps-a-comprehensive-guide-for-data-scientists-3af10baf9190) my question I suppose my question would be to know how I can call a variable in the for loop of my views.py where I am also trying to render the HTML from. In my particular case, how can I call {{venue.name}} in a format views.py is going to understand (I haven't added the files, as I didn't think it is necessary for this problem. I am obviously happy to … -
Django UpdateView does not validate form fields, and does not update
I have created the following Django UpdateView: class ProfileSettingsView(SuccessMessageMixin, UpdateView): template_name = "accounts/settings/profile_settings.html" form_class = ProfileSettingsForm success_message = "Your profile has been successfully updated." success_url = reverse_lazy("accounts:profile_settings") context_object_name = "staff_member" def get_object(self, queryset=None): staff_member = get_object_or_404(StaffMember, user=self.request.user) return staff_member The ProfileSettingsForm is defined as follows: class ProfileSettingsForm(forms.ModelForm): class Meta: model = StaffMember fields = ["profile_image"] And finally, the StaffMember model looks like this: class StaffMember(models.Model): user = models.OneToOneField( "auth.User", on_delete=models.PROTECT, related_name="staff_member" ) profile_image = models.ImageField( upload_to=get_profile_image_upload_path, blank=True, default="none.png", help_text="A profile image for this staff member. Must be square, and be in .png format.", validators=[FileExtensionValidator(["png"]), validate_img_square], ) My UpdateView renders correctly. I select an image from my local machine and press submit. The form posts successfully, and I see the success message. However, the validators, as defined on the StaffMember profile_image field have not been run. Also, the profile_image field is not updated. Why is validation not being called on my form fields, and why are they not being updated? What am I missing? Thank-you. -
How to do a Django list in list query
I have a list of lists filter items as this: [['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']] My database table has a field with a field(category) holding a list as value: ['4aa', '5bb'] How can I query to fetch items whose category is in the filter list? Something like: Table.objects.filter(category__in=[['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']]) -
How to make Django admin write LogEntry (history) for inline objects?
I have a model that is registered as a ModelAdmin, but for convenience is also an inline in another model. When creating or editing this related model, changes to the inline objects are not saved to Django's LogEntry, only the main object being edited. An example of this configuration is as follows: class Manufacturer(models.Model): ... class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer) ... Then, in admin: @admin.register(Car) class CarAdmin(admin.ModelAdmin): ... class CarInline(admin.StackedInline): model = Car class ManufacturerAdmin(admin.ModelAdmin): inlines = [CarInline] ... Currently, when editing a Manufacturer, even if I only add / remove cars, the only LogEntry added by Django is a change to Manufacturer (and the change message sucks by the way). ModelAdmin has methods called log_addition, log_change, and log_deletion, which I can use to create LogEntry objects, but how do I determine if an inline object has been added / changed / removed?