Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django quering foreign key from backward
I am trying to query from backward: at fist see my models: from django.db import models class Blog(models.Model): title = models.CharField(max_length=100, unique=True) body = models.TextField() category = models.ForeignKey('blog.Category', on_delete=models.CASCADE) def __unicode__(self): return '%s' % self.title class Category(models.Model): name = models.CharField(max_length=100, db_index=True) I have many category and many post, one category name is tech I am trying to get all the post those are in tech category. I tried like this. Category.objects.filter(contain__exact='tech') but it is not work anymore. Can anyone help me to figure get it done? -
How can I fix this conflict of packages while using Django, Channels, and Heroku?
I am following this tutorial on how to deploy a Django+Channels webapp on Heroku, and I've come across a problem when I run the following line: daphne chat.asgi:channel_layer --port 8888 I get the following: ERROR: daphne 2.3.0 has requirement asgiref~=3.0, but you'll have asgiref 1.1.2 which is incompatible. ERROR: channels 2.2.0 has requirement asgiref~=3.0, but you'll have asgiref 1.1.2 which is incompatible. Based on that, I went on to install: pip install asgiref~=3.0 However, when I run the daphne line I again, I got: ERROR: asgi-redis 1.4.3 has requirement asgiref~=1.1.2, but you'll have asgiref 3.0.0 which is incompatible. It's my first time tampering with web servers, asynchronicity, and these more complex libraries, so does anyone know how I can fix this problem? The tutorial I am following is this one in case you need: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django -
Reference ManyToMany Field in Django Model Method
I am attempting to reference the ManyToMany connection between Units and Add-Ons in my code to enable a method that provides the price, but I seem to be unable to reference the relationship in a Model method, can somebody point me in the right direction? class Unit(models.Model): class Meta: permissions = ( ('generate_unit_csv', 'can generate unit csv'), ) unique_together = ['building', 'unit_number', 'property'] add_ons = models.ManyToManyField( 'properties.RentalAddOns', related_name='add_on_units') ... def get_add_on_price(self): total_price = 0 # there is no self.add_on_units or self.add_ons for add_on in self.add_on_units: total_price += add_on.price return total_price When I call the method I get an Attribute Error: 'Unit' object has no attribute 'add_on_units' -
How can i filter between two models?
I have two models. One is a Partner. Another is Contact. Partner is the companys information. Contact is a contact for that company. How can I get a list of contacts from a company by comparing the name of the company to the foreign key partner which is who the contact belongs to. I have tried using querys but the result was not what i expected. class Partner(TimeStampedModel, StatusModel): name = models.CharField(blank=False, help_text="Name of the role or function", max_length=64, verbose_name="Partner Type", ) parent = models.ForeignKey( 'self', blank=True, help_text="Parent Company name (if necessary)", null=True, on_delete=models.CASCADE, max_length=200 ) class Contact(ContactModel, TimeStampedModel): partner = models.ForeignKey( Partner, blank=True, null=True, on_delete=models.SET_NULL, related_name="contacts",) What i want is a list of contacts belonging to that company. Lets say the company name is Shell. on The contact i would fill out the partner being shell. and i want to query all the partners shell has. -
How to use model one objects in model two in Django?
I have created a model that is used to create user using form. i want to use the objects of model one in model two in form to create new user id Models.py: class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Rooms(models.Model): name = models.CharField(max_length=200) room_num = models.IntegerField() def __str__(self): return str(self.name) class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.OneToOneField(Rooms,on_delete=models.CASCADE, blank=False) investigation = models.CharField(max_length=300) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,null = False) Forms.py: from .models import Patient,Ipd class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','investigation'] views.py: @login_required def ipd (request,patient_id): patient = Patient.objects.get(pk=patient_id) if request.POST: data = dict(request.POST) data['patient']=Patient.Patient_id formtwo = IpdForm(request.POST) if formtwo.is_valid(): if formtwo.save(): return redirect('/', messages.success(request, 'Patient is successfully updated.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: formtwo = IpdForm(request.POST) return render(request, 'newipd.html', {'form2':formtwo ,'form':patient}) I want to create new ipd_id using Patient Model and Ipd Model but I am ending with Invalid Form -
Setting DEBUG = False causes 500 Error in Django
I change the DEBUG = False in setting, my site generate 500 error code. I have tried all changes in my setting but still error 500. I'm using Django 2.1, Python 3.6 and Heroku Here is my setting file Setting file database Static, Root Path heroku logs --tail -
Filter cyclical relations
I have couple of models, Data, which contains different versions of some data and Master, which keeps track of all versions, and a current_version. Like this: class Master(models.Model): current_version = models.OneToOneField('Object', related_name='+') class Data(models.Model): master = models.ForeignKey('Master', related_name='data') I would like to get all instances of Data which are only a current_version of Master. As in: Data.objects.filter(Q(master__current_version=???)) How do I construct such a filter? -
How to write an if statement based on a request path
I know I can do the following to display the word "active" in a template using an if function to check the url vs the request.path: {% url 'dashboard' as dashboard %} {% if request.path == dashboard %}active{% endif %} How do I call the url object within the if statement? Eg: {% if request.path == url.dashboard %}active{% endif %} -
How to write a get endpoint returned data from file multiplied by parameters from query
I try to write a get endpoint for data from file. I also want to multiply data by parameters from query, unfortunately I get an error. Is there any way to avoid it? Error I get: AssertionError at /data/ 'DataView' should either include a serializer_class attribute, or override the get_serializer_class() method. # Views.py class DataView(ListAPIView): def get_queryset(self): mult = self.request.query_params.get('mult', None) y = np.loadtxt('media/data_vv.txt')[:10] x = list(range(len(y))) print(mult) if mult is not None: y *= float(mult) data = {'x': x, 'y': y} return data I want to avoid the error and get the data. -
Why is JS code in HTML file not working after adding type and src?
<script type='text/javascript'src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue = $(this).attr('for'); if (forValue) { forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-'); $(this).attr({'for': forValue}); } }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); var conditionRow = $('.form-row:not(:last)'); conditionRow.find('.btn.add-form-row') .removeClass('btn-success').addClass('btn-danger') .removeClass('add-form-row').addClass('remove-form-row') .html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>'); return false; } function deleteForm(prefix, btn) { var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (total > 1){ btn.closest('.form-row').remove(); var forms = $('.form-row'); $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); for (var i=0, formCount=forms.length; i<formCount; i++) { $(forms.get(i)).find(':input').each(function() { updateElementIndex(this, prefix, i); }); } } return false; } $(document).on('click', '.add-form-row', function(e){ e.preventDefault(); cloneMore('.form-row:last', 'form'); return false; }); $(document).on('click', '.remove-form-row', function(e){ e.preventDefault(); deleteForm('form', $(this)); return false; }); I tried changing the script type and src … -
Django with DEBUG = True and django.contrib.staticfiles not finding static files
I am running Django with DEBUG = True and staticfiles in the INSTALLED_APPS. However my program is not finding the static files. I don't really want to do collectstatic... Is there any common reason why this may happen? -
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