Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When to start the google cloud profiler in a Django project?
I'm attempting to add the google cloud profiler to my Django App Engine project, and would like to know where the best place to call it is? Google Cloud Platform's documentation says to start the profiler as early as possible: You should call start one time, and as early as possible in your application. In a Django project, running on GCP App Engine Flex, where is the best place to call this so that 1. It is called only once, 2. It is not called on things like tests, migrations etc. My initial thought was to place it in manage.py under execute_from_command_line, but I realised that this would call the profiler for simple things like manage.py test. Django 2.2, App Engine Flexible, Gunicorn. -
how to get information the two (csrf_token) in same page
I have two forms, but i need get information the first form but i dont know how to make Is django 1.11 and python 2.7 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Administrador</title> <link rel="stylesheet" href="../../static/css/estilo-competencias.css"> </head> <body> <div class="container-alumnos"> <form action="/seleccion" method="POST"> {% csrf_token %} <div> <select id="carrera" name="Carrera"> <option value="1">TICS</option> <option value="2">Carrera</option> <option value="3">Carrera</option> <option value="4">Carrera</option> <option value="5">Carrera</option> </select> </div> <div> <select id="Alumno" name="Nombre"> {% if alumno|length > 1 %} {% for alumno in alumno %} <option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option> {% endfor %} {% else %} <option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option> {%endif%} <input type="submit" name="Seleccionar"> </select> </div> <label for="ID">ID</label> <input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br> <label for="apellidos">Apellidos</label> <input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br> <label for="Correo">Correo</label> <input type="input" name="Correo" disabled value="{{alumno.correo}}"><br> </form> </div> <select id="opciones" name="Semana"> <option value="1">Semana 1</option> <option value="2">Semana 2</option> <option value="3">Semana 3</option> <option value="4">Semana 4</option> <option value="5">Semana 5</option> </select> <div class="container-listas"> <select id="competencias" name="competencia"> {% for comp in competencias %} <option value="{{comp.idCompetencias}}">{{comp.nombre}}</option> {% endfor %} </select> <div class="Container-listas-enviar"> <form action="/evidences" method="POST"> {% csrf_token %} <label for="Nivel-bajo">Bajo</label> <input type="radio" name="bajo" ><br> <label for="medio">Medio</label> <input type="radio" name="medio" ><br> <label for="Alto">Alto</label> <input type="radio" name="Alto" ><br> <input type="submit" value="Enviar"> </form> </div> </div> </body> </html> when i press Enviar in the second form (/evidences) i dont have access information … -
Django Auth.authentication always return none for Email
I am trying to implement an signup and login function. This is my views.py: here in auth.authenticate def login(request): if request.method == 'POST': f = auth.authenticate(email = request.POST['email'], password = request.POST['password']) print(f) if f is not None: auth.login(request,f) return redirect('home') else: return render(request,'login.html',{'error':'Wrong Username or password'}) else: return render(request, 'login.html') It always returns None and if I change to user and trying to login with username and password then it works fine it didn't work for email and password. i.e f = auth.authenticate(username= request.POST['username'], password = request.POST['password']) I have tried request.get.POST('email') but not working, and I have also checked request.POST['email'] and request.POST['password'] contains valid info. -
Django django-rest-auth shows "New password has been saved" when giving wrong oldpassword
I am using Django and django-rest-auth for authentication. When posting: curl -X POST -H "Authorization: Token sometoken" -d "oldpassword=somepassword&new_password1=somenewpassword&new_password2=somenewpassword" http://127.0.0.1:8000/rest-auth/password/change/ I always get "detail":"New password has been saved." Even if I don´t give the right password in the oldpassword field. Any idea why this happens and if there is a way to make sure the oldpassword entered is the current password? Is oldpassword maybe an optional field I can make required? -
How to link a user to a group where the user can view only the posts from other users in that group in Django
I have a class full of students. Within the class there are many groups of students. I want the students in each group to only be able to view the posts of the students in their group. I am not sure whether to make the groups via the django admin, or to make a model called class_group. I would like to be able to add student to one of these groups. I don't know how I would use the model route, because I am not sure of how to give a user a foreign-key to a model. Any advice would help! -
How to make a loop range in queryset when fetching data from database?
I am working in views.py to fetch data from database. All the items are present in database. I am trying to make a loop within range of 2. Because I arranged items in 3 columns in index.html. But when I looped the items in range 2 it is displaying all the items in one column. How to resolve this issue? def index(request): query = request.GET.get('srh') if query: target1 = Destination.objects.filter(title__icontains=query) target1 = Destination.objects.all() for field in target1: [Destination(img = f'{field.img}', title = f'{field.title}') for __ in range(2)] context = {'target1': target1} return render(request, 'index.html', context) else: return render(request, 'index.html') -
Serialising Django object: how to get clean output
I have a Django app with a set of markets, connected through a foreign key to a price history, defined in models.py as follows: class Market(models.Model): title = models.CharField(max_length=50, default="") current_price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField(default="") shares_yes = models.IntegerField(default=0) shares_no = models.IntegerField(default=0) b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Price(models.Model): market = models.ForeignKey( Market, on_delete=models.CASCADE, related_name='prices', default=None) price = models.DecimalField( max_digits=5, decimal_places=2, default=None) def __str__(self): return str(self.price) def get_absolute_url(self): return reverse('market_list') In a template, users see the current market price and can buy or sell shares relating to that market. They should also see a price graph, which I'm trying to populate by serialising from market.prices into price_items as follows (from views.py, ignore the toy values in labels): class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, pk): market = Market.objects.get(pk=pk) price_items = serializers.serialize('json', market.prices.get_queryset(), fields=('price')) labels = [1, 2, 3, 4] # Toy labels data = { "labels": labels, "prices": price_items} return Response(data) The relevant section of urls.py is as follows: urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('list/', MarketListView.as_view(), name='market_list'), path('<int:pk>/', MarketDetailView.as_view(), name='market_detail'), path('<int:pk>/buy/', views.buy, name='buy'), path('<int:pk>/sell/', views.sell, name='sell'), # url(r'^api/chart/data/$', ChartData.as_view()), path('<int:pk>/api/chart/data/', ChartData.as_view(), name='chart_data'), ] My … -
Double filter on detail view
I'm trying to create a detail view using function based view. This view must make visible only the already published posts and the non draft posts. def singlePost(request, slug_post, slug_category): post_category = get_object_or_404(BlogCategory, slug_category=slug_category) if post_filter == BlogPost.objects.filter(draft=True): raise PermissionDenied if post_filter == BlogPost.objects.filter(publishing_date__gt=datetime.datetime.now()): raise PermissionDenied else: post_filter == BlogPost.objects.all() post_details = get_object_or_404(post_filter, slug_post=slug_post) category_post_details = BlogPost.objects.filter(post_category=post_category) context = { "post_category": post_category, "post_details": post_details, "category_post_details": category_post_details, } template = 'blog/reading/single_post.html' return render(request, template, context) But when I use this I see this error message: name 'post_filter' is not defined How I can solve? NB: the view works fine in that way def singlePost(request, slug_post, slug_category): post_category = get_object_or_404(BlogCategory, slug_category=slug_category) post_details = get_object_or_404(BlogPost, slug_post=slug_post) category_post_details = BlogPost.objects.filter(post_category=post_category) context = { "post_category": post_category, "post_details": post_details, "category_post_details": category_post_details, } template = 'blog/reading/single_post.html' return render(request, template, context) -
Django How to get the current user in my forms class
I want to get the current user logged in my forms.py class for show his biography in a CharField (with placeholder or value) i've tried the init method but it doesn't work for me idk what i'm doing wrong ... here is my form class class ProfileSettingsForm(forms.Form): avatar = forms.ImageField(required=False) description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": "here i want the description of the current user"})) with init class ProfileSettingsForm(forms.Form): def __init__(self, user, *args, **kwargs): self.user = user super(ProfileSettingsForm, self).__init__(*args, **kwargs) avatar = forms.ImageField(required=False) description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": self.user})) I tried this method class ProfileSettingsForm(forms.Form): user = None def __init__(self, user, *args, **kwargs): self.user = user super(ProfileSettingsForm, self).__init__(*args, **kwargs) avatar = forms.ImageField(required=False) description = forms.CharField(required=False, max_length=230, widget=forms.Textarea(attrs={"value": self.user})) but it return None in my views.py: form = forms.ProfileSettingsForm(user=request.user) -
bundled vue component don't use my website css
I have a vue component budled with vue cli build as web component and I want to use it in my website page generated with django. I use Material Design Bootstrap to style my page and this work with no problem. But when i include my vueJS component, it work fine, but he have no style on it. actual result : https://i.imgur.com/4SiO7g6.png expected : https://i.imgur.com/LUhOsIk.png component.vue <style> <!--I have no style on my component--> </style> base.html <head> <!-- I include my style on the base page of my django app --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}{% endblock %}</title> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Material Design Bootstrap --> <link href="{% static 'css/mdb.min.css' %}" rel="stylesheet"> <!-- Your custom styles (optional) --> <link rel="stylesheet" href="{% static 'css/base.css' %}"> {% block css %}{% endblock %} <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> page.html <!-- And i use my bundled component in my page --> <nightmare-nightmare-part-survey id="{{ part.nightmaresurvey.id }}" end_date="{{ part.nightmaresurvey.get_end_time|date:"Y-m-d\TH:i:s" }}"></nightmare-nightmare-part-survey> -
how to add new field with initial value to django queryset result?
I have a queryset like this. <QuerySet [{'id': 5}, {'id': 4}]> i want to add new field 'n' to it with initial value 0 <QuerySet [{'id': 5, 'n': 0}, {'id': 4, 'n': 0}]]> this is my code: drivers_not_in_rides = Driver.objects.all().filter( car__ride__in=ride_ids_with_conditions ).values('id').annotate( n=0 ) but i get this error: 'int' object has no attribute 'resolve_expression' -
APIView interacting with foreign key object in Django
I have a Django application with a set of Market objects, each of which is displayed in a template where users can engage with the market by buying or selling shares. I'm struggling to display the price history as a graph. Here's what I have in terms of models, one for markets, and one for the price history of each market, connected through a foreign key: class Market(models.Model): title = models.CharField(max_length=50, default="") current_price = models.DecimalField(max_digits=5, decimal_places=2) description = models.TextField(default="") shares_yes = models.IntegerField(default=0) shares_no = models.IntegerField(default=0) b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) def __str__(self): return self.title[:50] def get_absolute_url(self): return reverse('market_detail', args=[str(self.id)]) class Price(models.Model): market = models.ForeignKey( Market, on_delete=models.CASCADE, related_name='prices', default=None) price = models.DecimalField( max_digits=5, decimal_places=2, default=None) def __str__(self): return str(self.price) def get_absolute_url(self): return reverse('market_list') On the templates side, the page displays a variety of information about the relevant market, enables the user to buy or sell, and displays a price graph: {% extends 'base.html' %} {% block content %} <div class="article-entry"> <h2>{{ market.title }}</h2> <p>Current price: {{ market.current_price }}</p> <p>{{ market.description }}</p> </div> <div style="display: flex"> <form action="{% url 'buy' market.id %}" method="post"> {% csrf_token %} <input type="submit" name="buy" class="btn btn-primary pull-right" value="Buy" /> </form> &nbsp; &nbsp; <form action="{% url 'sell' … -
How to do actions after return redirect?
I have this code: size = Size.objects.get(size = 'XS') good1.Size.remove(size) return redirect('/') time.sleep(600) good1.Size.add(size) So, I need to recover a model object after 10 min, but the user must be redirected to another page and be able to use another pages of the site during 10 min. How can I do it? -
Ways to Create a Dashboard using Flask and API in python and keep Webpage active even when not running the program
I have a general question which I am having difficulty solving. I know how to use flask/plotly/dash/AI to create an webpage or interactive plots/tables on webpage. (using the dev server: http://127.0.0.1:Port#/). However the issue is that if I want to create plots on a webpage ( with the web address) of my own, what is the best way to do that using flask/dash frameworks? Also since I will be running the program ( by fetching the data from a server), the python code may run as scheduled say twice on a day. But I want to keep my webpage the data even when the program is not running ( based on the refresh from the last run) What sort of techniqiues do I need to use. Will it be possible to do that using flask/dash framework or not possible. Do I need to use D3/React/Angular/ for this and if so how will it fix my problem? Thanks -
Django 'block' tag with name 'title' appears more than once
I'm trying to implement logic for my website with a title. But have this error - Django 'block' tag with name 'title' appears more than once. How do i fix this? base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %} Main {% endblock %}</title> <meta charset="utf-8"> In my template product_list {% extends 'shop/application.html' %} {% if category %} {% block title %} Product name of category {% endblock %} {% elif subcategory %} {% block title %} Product name of subcategory {% endblock %} {% endif %} ... How to implement it? Thanks for help! -
(Django 2.1) Media files doesn't show?
I have a page where I want to show images uploaded by the users. So i made a for loop to iterate through every image in the database so here's the template tags : <div class="row"> {% for image in Patient_detail.images.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <div class="card"> <img src="{{ image.pre_analysed.url }}" > <div class="card-body"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <!-- <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> --> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </form> </div> </div> </div> </div> {% endfor %} </div> The number of images in the model appear but the images don't show, it appears as a broken link. Models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') analysedimage = models.ImageField(upload_to=analyses_directory_path, verbose_name='analysed Image', blank=True) upload_time = models.DateTimeField(auto_now=True) a = models.CharField(max_length=250) b = models.CharField(max_length=250) c = models.CharField(max_length=250) d = models.CharField(max_length=250) e = models.CharField(max_length=250) f = models.CharField(max_length=250) g = models.CharField(max_length=250) h = models.CharField(max_length=250) i = models.CharField(max_length=250) j = models.CharField(max_length=250) def get_absolute_url(self): return reverse('analysed_images',kwargs={'pk':self.pk}) I reference patient_detail as it's the context_object_name of the detail view of this particular detail view and .images.all as i reference the related name in the model … -
Django Rest Framework, React and Localization
I have a django rest framework which interacts with react. What is the best way to manage localization in such projects? I have django.po on server side. Is it possible to create one file and synchronize with both apps? -
Python Django Admin | Use to change content from website
First of all, I wanted to say, that I couldn't find a proper solution to this problem, and I am very new to Django and I have no idea how I could make this. Nor finding the proper documentation to this problem. As an example, I have a template with the following inside a <div>. An image, header, and a description. I want to configure my Django-Admin site localhost:8000/admin/ to be able to manage this content. So I need to program something that can upload images to a specific folder, write a header and a description. So that the information is being generated as a div inside the template. So can anyone give me any tips on how I should do this project? And where to find the proper docs, and/or a proper way of how to do this? So what I want in the end is on my Django-Admin site the option to add new objects and edit current ones. And that these objects autogenerate inside the template. So should I write/edit/read from a JSON file, or is there another way how to do this. -
Mapping a 1 - many relation in a Django Rest Framework View
In my DRF i want to map a customers/sercvices relation in the view. So one Customer can have 0 - many services inside of it My serializer class appears to be fine class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['name' , 'phone' ,'email1' ... , 'service_id'] class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = ['service_name', 'product_name', ...] class Customer_ServiceSerializer(serializers.ModelSerializer): service = ServiceSerializer(many=True, read_only=True) class Meta: model = Customer fields = ['name' , 'phone1' , 'email1' ... 'service'] My Customer_ServiceSerializer class seems to be nested correctly Im stuck on how i would show these combined models in the view as i have tried multiple things and come up stuck class Customer_serviceListAPIView(generics.ListAPIView): ... def get(self, request, *args, **kwargs): Above is how i started my views but i am stuck on how to solve this problem tried for example this Serialize multiple models in a single view / https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html but i get Customer objects arent iterable so how would i go about this Thanks in advance -
Some CSS styles in css file are not applied, but they work when added to header of Html page
I previously had two CSS files, and the html page needed some css from one and only part of css from the other. The section of code was copied and pasted to the first CSS file, but these styles are not applied to the HTML page. when I create a block in the header and add the copied css styling into the html file, the styling is applied. I would like for the styling to work from linked css file. I checked that the linked urls are correct, and actually some of the other css files styles are used. I checked if I added the html elements into a wrong parent element, but does not seem to be the case. CSS file: #d_content_external{ line-height: 1.8; padding: 20px; } #d_links_indent{ margin-left: 40px; } /* OTHER STYLING ABOVE */ /* CODE BELOW ONLY WORKS IN HTML HEADER, NOT FROM HEADER FILE*/ #buttonwrapper{ padding: 10px 10px 15px 10px; } #attrwrapper{ position: relative; display: inline-block; width: 100%; } #dropupbtnIMG{ width: 100%; padding: 10px; font-size: 12px; font-weight: bold; background-color: #4d79ff; color:black; float: right; } /* attribution content DIV */ #divattributions{ min-height: 60px; max-height: 290px; padding: 10px; width:90%; font-size:14px; display: none; position: absolute; bottom: 100%; border-style: … -
Django celery - to check if a task is complete, if complete to restart the task (if not complete, do not restart the task)
I am currently trying to run a periodic check on a scheduled celery task every minute. If the task is still running, to let it continue running and not interrupt it, but if the task has no longer running, to activate the task and start running it. But at the moment, I cannot get the script to run only when it is no longer running. I have tried two methods of doing it but my script does not detect the existing running script and it starts to run even when it shouldn't and my task starts to run simultaneously. I am using celery 4.2.0 and django 1.11.6. Any tips on how I can solve this problem? Thanks in views.py Task to run @task(name='send-one-task') def send_one_task(): for i in range(1,100): time.sleep(1) print ("test1 " + str(i)) return None I have tried two methods to to check if process is complete and stopped running - if its not, do not rerun it method 1 @task(name='send-two-task') def send_two_task(): # method 1 from celery import current_task if current_task.request.task != "send-one-task": send_one_task() else: pass return None method 2 @task(name='send-two-task') def send_two_task(): from celery.task.control import inspect insp = inspect() testactive = insp.active() checkrunning = list(testactive.values()) try: … -
Archive data after every year
I have lots of models in my project like Advertisements, UserDetails etc. Currently I have to delete the entire database every year so as to not create any conflicts between this year data and previous year data. I want to implement a feature that can allow me to switch between different years. What can be the best way to implement this? -
Fix 'SECRET_KEY must not be empty' django error when hosting on pythonanywhere
I am trying to host my Django application on PythonAnywhere. Unfortunately, I cannot get past the following error: Error running WSGI application 2019-07-15 13:29:44,375: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I tried to follow their official tutorial for hosting an existing django app and have a basic wsgi configuration: # +++++++++++ DJANGO +++++++++++ # To use your own Django app use code like this: import os import sys # assuming your Django settings file is at '/home/myusername/mysite/mysite/settings.py' path = '/home/tkainrad/wagtail_cms_project' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'wagtail_cms_project.settings' ## Uncomment the lines below depending on your Django version ###### then, for Django >=1.5: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() To be sure, I have two identical settings.py files in /home/tkainrad/wagtail_cms_project and /home/tkainrad/wagtail_cms_project/wagtail_cms_project These settings.py files contain a secret key, similar to the following: SECRET_KEY = 'dafa_o^el4*4+************************_@3sdfasdf' I.e. I do not try to read the key from a system property. Atm, this is just a test deployment and I am only trying to get it to work. Security and best practices will follow afterwards. Do you have an idea what could be wrong? -
Django REST Framework Serialize model with foreign key
Simple question: I have next models: class Artist(models.Model): name = models.CharField(...) surname = models.CharField(...) age = models.IntegerField(...) clas Album(models.Model): artist = models.ForeignKey(Artist, ...) title = models.CharField(...) I wish to create an Album serializer that: Shows Artist information on GET Can link Artist using pk on POST I can make the POST using pk using the following serializer, but I don't know how to GET artist information in the same serializer: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = Album fields = '__all__' Thanks. -
Django ORM really slow iterating over QuerySet
I am working on a new project and had to build an outline of a few pages really quick. I imported a catalogue of 280k products that I want to search through. I opted for Whoosh and Haystack to provide search, as I am using them on a previous project. I added definitions for the indexing and kicked off that process. However, it seems that Django is really, really really slow to iterate over the QuerySet. Initially, I thought the indexing was taking more than 24 hours - which seemed ridiculous, so I tested a few other things. I can now confirm that it would take many hours to iterate over the QuerySet. Maybe there's something I'm not used to in Django 2.2? I previously used 1.11 but thought I use a newer version now. The model I'm trying to iterate over: class SupplierSkus(models.Model): sku = models.CharField(max_length=20) link = models.CharField(max_length=4096) price = models.FloatField() last_updated = models.DateTimeField("Date Updated", null=True, auto_now=True) status = models.ForeignKey(Status, on_delete=models.PROTECT, default=1) category = models.CharField(max_length=1024) family = models.CharField(max_length=20) family_desc = models.TextField(null=True) family_name = models.CharField(max_length=250) product_name = models.CharField(max_length=250) was_price = models.FloatField(null=True) vat_rate = models.FloatField(null=True) lead_from = models.IntegerField(null=True) lead_to = models.IntegerField(null=True) deliv_cost = models.FloatField(null=True) prod_desc = models.TextField(null=True) attributes = models.TextField(null=True) …