Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to get display name from inside concat in Django?
So let's say I have this Model: class Cable(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.cableTypes, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) objects = CableQuerySet().as_manager() def __str__(self): return str(self.get_type_display()) + " Cable, " + str(self.length) + "m" I need to be able to pull results from the database using the __str__, and that has proven to not be possible. So instead, I was advised to use .annotate() with Concat() to achieve the same result. My problem is that I need the display name of Cable.type and not the value, or I need to be able to use the value of type as the key, and search the choices with that to then return the proper value. Is it possible to get display name from inside concat, or is there something that I can do that provides a similair outcome? -
Setting a value for when value isn't present
Using request.POST.get you can do this: token = request.POST.get('token', False) Is there a way to do the same thing using request.data['token'] -
How do you add parens to a CheckConstraint in Django
The following constraint: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | (models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) Generates a postgres constraint that looks like this: Check constraints: "approved_by_someone" CHECK (approved_at IS NULL OR approved_by_id IS NOT NULL AND approved_at IS NOT NULL) The parens in my python code disappear when converted into a sql constraint. My first thoughts were, OK, I can put those back by adding a models.Q around the AND condition: models.CheckConstraint(name='approved_by_someone', check=(models.Q(approved_at__isnull=True) | models.Q(models.Q(approved_by__isnull=False) & models.Q(approved_at__isnull=False)))) But still, NO the constraint is unchanged. -
NOT NULL constraint failed: articles_comment.article_id
I am following a tutorial where i build a newspaper app. So far so good but know I'm trying too add a comments section. If I add the comment true the admin in django i can see the comment and delete and update the comment on my site. But when i want too add a comment on the site I get the following error: NOT NULL constraint failed: articles_comment.article_id. Can somebody tell me what I'm doing wrong? This is my models.py from django.db import models from django.conf import settings from django.contrib.auth import get_user_model from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments',) comment = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return self.comment def get_absolute_url(self): return reverse('comment_detail',) This is my views.py from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Article, Comment class ArticleListView(ListView): model = Article template_name = 'article_list.html' class ArticleDetailView(LoginRequiredMixin, DetailView): model = Article template_name = 'article_detail.html' login_url = 'login' class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): … -
Django, DjangoFilterBackend filter doesnt work with union
I have some query, like q1 = ... q2 = ... q3 = ... q4 = ... result = q1.union(q2, q3, q4).distinct() return result I have used union becouse it fast! I can do like this, becouse it slowly: q1 = ... q2 = ... q3 = ... q4 = ... result = q1 | q2 | q3| q4 return result so, when i use union my DjangoFilterBackend fields filter doesnt work. How i can fix this? -
python / django: sharing a class instance variable within a class?
I would like to share a class instance variable within a class and it´s functions, But i don´t want to use global variables. Original this question came up after using a class based view (with it´s functions) in Django. But i guess it´s a python topic in general, i could answer myself Example class Aquarium(object): print("Aquarium check") class Fish(object): print("Fish check") # -- Constructor method with instance variables result def __init__(self, name, weight): self.name = name self.weight = weight # starting weight fish1 = Fish("Harry", 22) print(fish1.name) print(fish1.weight) # new food arrived def new_food(): fish1.weight = 24 new_food() # did Harry gained weight? print(fish1.name) print(fish1.weight) # more food arrived def more_food(): fish1.weight = 54 more_food() # did Harry even more gained weight? print(fish1.name) print(fish1.weight) Aquarium() So the logic is like, there is Fish in my Aquarium. One named "Harry" and he has a starting weight of "22". But when ever i fire some new_food functions in my Aquarium he gained "weight" or fish1.weight maybe changes. The thing is i need access to fish1.weight as a dynamic variable within the Aquarium class and the it´s def new_food() , def more_food()functions. Do i need a dictonary? -
Pass Foreignkey from User Input to DB
I'm trying to have user input the data and store into DB and map with the other data. Model: class Code(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True) Within the Model, there is another class class Pull(models.Model): code_pull = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) How to display to call in the Form and View, so that data is pass when user input the data in the input field. Form class Code_Form(forms.ModelForm): class Meta: model = Code fields = '__all__' field_classes = { 'json_field': JSONFormField, } class Pull_Form(forms.ModelForm): class Meta: model = Pull fields = '__all__' field_classes = { 'json_field': JSONFormField, } Here is the VIEW: def InputData(request, *args, **kwargs): form = Pull_Form(request.POST or None) if request.method == 'POST': if form.is_valid(): datafetch = form.save() messages.success(request, 'Successfully') else: messages.error(request, form.errors) return render(request, template_name, {'form': form }) Here is the HTML: Error <django.contrib.messages.storage.fallback.FallbackStorage object at 0x103f68750> {{ messages }} <form id="form1" class="post-form" role=form method="POST" action=".">{% csrf_token %} <input id="code" class="form-control" type="text" maxlength="4" required></input> <label for="code">Code</label> <button type="submit" class="btn">Save</button> </form> Looked at the logs, nothing I get back from the form, Not sure, where is the issue to stored the data -
Unnecessary queries inside Django atomic transaction block
This might seem very, very esoteric but I have a question about how queries work inside Django atomic transaction blocks. Suppose I have this model - class User(models.Model): name = models.CharField(max_length=10) I have this code inside an atomic transaction block - from django.db import transaction, connection with transaction.atomic(): user = User.objects.get(id=231) user.name = 'changed' user.save() print connection.queries print 'transaction is still not committed!!!!' The User object will have its name changed to changed only within that transaction scope. If I have another Python shell open and extract that object, the name will still have the old value. But if that is how it works, why does connection.queries have the save() query? As far as I know, connection.queries lists out those queries which have been fired to the database and have committed, right? But printing it gives me the get query, which I understand, but it also gives me the save() query, which I don't understand since the transaction hasn't actually committed. It also seems like a wastage of DB calls since the save() query fired against the DB would just be rolled back in case of an exception. -
Can't reference related many-to-many object in Django
Here are my models: class Vlan(models.Model): Name = models.CharField(max_length=20) VID = models.IntegerField(default=1) def __str__(self): return(str(self.VID) + ' ' + self.Name) class Connection(models.Model): Description = models.CharField(max_length=80) Created = models.DateTimeField('Created Date') Change_Order = models.CharField(max_length=40) Implemented_by = models.CharField(max_length=80) def __str__(self): return(self.Description) class Port(models.Model): Port_Number = models.IntegerField(default=1) Is_Pri = models.BooleanField(default=True) Switch = models.ForeignKey(Switch, on_delete=models.CASCADE) Connection = models.ForeignKey(Connection, null=True, blank=True, on_delete=models.SET_NULL) Vlans = models.ManyToManyField(Vlan, blank=True) def __str__(self): return(str(self.Port_Number)) Each connection can have one or more ports, and each port can have one or more vlans (and a vlan can be on one or more ports). I'm trying to create a list of dictionaries to render in a template. Each dictionary contains a list of port objects. Each port object contains a list of dictionaries with VLAN objects. But I can't query a set of vlans, given a port object: Here's the code: def connlist(request, Conn_id): clist = Connection.objects.all() ctx_list = [] ports =[] for c in clist: # For each coonection plist = c.port_set.all() # get a list of ports for p in plist: # for each port vlist = p.vlan_set.all() # get a set of vlans -- error! portd = {'port': p, 'vlist':vlist} ports.append(portd) ctx= {'conn': c.Description , 'ports': ports} ctx_list.append(ctx) template = loader.get_template('newcon/connlist.html') … -
How to assign a user automatically to a group on signup, using Django Allauth
So I want to assign a user on signup to a specific group. I am using Django Allauth. I found some posts on SO but I can't seem to figure it out. This is my code: from django.contrib.auth.models import Group class CustomSignupForm(SignupForm): def signup(self, request, user): role = request.session.get('user_type') group = role or "Default" g = Group.objects.get(name='Premium') user.groups.add(g) user.save() return user However this is not working, the user does not get assigned to the group "Premium" after signup. Any help is appreciated. -
Storing sser info from HTML forms to postgresql
I want to store the user input from the html form, for example first and last name. And store these in my postgresql database. I created the html file: <form > First Name: <input type="text" name="fname"> Last Name: <input type="text" name="lname"> <input type="submit" name=""> </form> I have created the model: class User(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) I have also connected the postgre database in the settings.py file. I am bit confused about how to connect the frontend and database. I think I need to add the model to the views.py and get the POST request to get the user input and store in the models. Please nudge me in the right direction. Thanks -
use datetime objects to filter queryset in Django (truncate to days)
I have a question regarding filtering with datetime. I have a following code: def filter_by_transaction_date(self, queryset): if self.user_filter.from_date: queryset = queryset.filter(created_at__gte=self.user_filter.from_date) if self.user_filter.to_date: queryset = queryset.filter(created_at__lte=self.user_filter.to_date) return queryset where queryset is obviously a queryset, created_at = models.DateTimeField(auto_now_add=True), self.user_filter.from_date== models.DateTimeField(null=True, blank=True) self.user_filter.to_date = models.DateTimeField(null=True, blank=True) What in this case filtering does it that check whether or not created_at field contains between 2 datetimes, that is we basically operate timestamps here. Issue. For example if object is created 26 august 13-45 and self.user_filter.to_date is 26 august 03-00, then this object would be filtered out. What I want is to filter them based on days only. For example if object is created 26 august 13-45 and self.user_filter.to_date is 16 august 03-00 – both datetimes are still belong to one date , which is 26 august. I want to use only days and somehow truncate hours, minutes, seconds, etc on both created_at and ( self.user_filter.from_date , self.user_filter.to_date) and compare only year, month and day. Target result ; object is created 26 august 13-45 and self.user_filter.to_date is 26 august 03-00, we truncate time, keep only date we compare 26 august <= 26 august -True, object gets inside filter... Sorry for entangled explanation, if so Thanks... -
Passing Values Between Views in Django
Simple scenario - firstview has a form (firstform) which has a field 'reference'. In secondview, there is a separate form (secondform) which also has a field 'reference'. I would like to initialize the value of 'reference' in secondview to be = the value of 'reference' in firstview. Am I able to do this without passing that parameter through the URL? I am using python 2.7 for reference. This is what I've tried. It doesn't seem to work this way and I am getting a "does not exist" error which I know just mean that I'm not actually getting that value. views.py def firstview(request): if request.method == "POST": form = FirstForm(request.POST) #this form contains 'reference' if form.is_valid(): form.save() return redirect('secondview') def secondview(request): form = SecondForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() ... reference_id = request.POST.get('reference') #this is how Im trying to get reference from the firstview form = SecondForm(initial={ 'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist" error }) .... return render(request, 'manifest_readonly.html', context) -
Unable to get user object from token DRF
Using the following: from rest_framework.authtoken.models import Token user = Token.objects.get(key='token string').user I only get username from it when I print(user). Trying to iterate through it as if it were an object doesn't work either. Am I missing something? -
How to use Django's CSRF protection in axios for different host?
I am working on ReactJS project as frontend and Django as backend and having trouble with CSRF protection! I am using Django CORS headers and I have done all set up correctly. It works as long as I have localhost to access both front and back ends. My frontend is running on localhost:3006 and backend us running on localhost:8899 port. So frontend is setting csrftoken cookie and sending it with post request. I am using axios.create() with withCredentials = true and it works fine. Now when my co-worker is running same frontend code from his system, trying to connect to backend that is running on my machine, he is getting 403 csrf cookie not found! At this time, he is running his frontend on localhost:3006, his own localhost and connecting to backend of my-ip:8899. So I believe that we would have this problem too on production when we will have www.example.com serving frontend and api.example.com serving backend as cookies of frontend host wont get sent to api host! My cors header settings in django, # Origin white list CORS_ORIGIN_WHITELIST = [ 'http://localhost', 'http://127.0.0.1', 'http://192.168.1.165', 'http://192.168.1.165:3006', ] CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', ) # Allowed methods CORS_ALLOW_METHODS = ( 'DELETE', 'GET', … -
Django next page in pagination on form submission
def listing(request): contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page page = request.GET.get('page') contacts = paginator.get_page(page) return render(request, 'list.html', {'contacts': contacts}) Let's say in each page I have a form, and when the form submitted I need to go to the next page. I first tried to add a hidden field in the form, and manually calculate the next page, and put into HTTPResponseRedirect, but then I lose the pagination. So what should be my strategy? Do I need to create a seperate view for form action, or should I use listing as form action and check wheter it is a GET/POST method, I am kind of lost here. -
Manipulate python django dictionary content
I am developing a simple weather application using Django. I am able to display city name, temp, wind speed, description of condition, and add/delete cities. When a city is added, the web app displays a card with that City name and all of those weather information described above. Being a rower, I would like to add a "safeToRow" section to a cities card. That section will take in the temperature and wind of the city from the python dictionary and assign it to two variables. Then run those variables through some simple if and else if conditions to determine is it's safe to row and finally returning the final value of safeToRow. Views.py def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=APIKEY' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] safeToRow = "" for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'wind' : r['wind']['speed'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) temp = r['main']['temp'] wind = r['wind']['speed'] def row(temp, wind, safeToRow): if temp < 32: return safeToRow == "No" elif temp > 40 and wind < 15: return safeToRow == "No" elif temp < 40 and … -
How to customize django-ratelimit 403 forbidden page
I'm using django-ratelimit 2.0 for rate limiting my views. I want different custom 403 forbidden page for different views. For example if it is a sign up view. It should give message try after 1minutes. If it is a forgot password view then message should be try after 12 hours. Basically I want different rate limit message for different views. -
Django ORM: Reverse relation query multiple model from single single models
I am in trouble querying reverse relation, I learned a lot about select_related and prefetch_related, yet I failed to achieve this. At first see my models: from django.db import models import uuid class Person(models.Model): alias = models.UUIDField(primary_key=True,default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=20) class Appointment(models.Model): patient = models.ForeignKey(Person, related_name="patient_for_appointment", on_delete=models.CASCADE) data = models.CharField(max_length=20) class Sales(models.Model): customer = models.ForeignKey(Person, related_name="customer_for_sales", on_delete=models.CASCADE) amount = models.FloatField() class Prescription(models.Model): patient = models.ForeignKey(Person, related_name="Patient_for_prescription", on_delete=models.CASCADE) details = models.CharField(max_length=100) I am trying to filter Person Model to check if the person has any prescription, sales, and appointment I want to get these all with single query like the person. will filter it with a person alias (primary key) I can filter it with separate query like patient_alias = '53fsdfsdf-fdsfds-df-fdf' queryset = Appointment.objects.filter( patient__alias=patient_alias ) But I don't want this, coz, it has a performance issue. I don't want this with separate query. I want to query only Person model to check if a person has Appointment, prescription or Sales like Person.objects.filter(alias='a person alias) Can anyone please help me to achieve this? Much appreciated -
Can you manage two discrete forms with formset?
I am a little unclear on whether two separate forms can be handled in the same view via formsets. For example, consider these two models: class Task(models.Model): title= models.CharField(max_length=30) approvers = models.ManyToManyField( get_user_model(), through='TaskStep') class TaskStep(models.Model): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL) task = models.ForeignKey(Task, null=True, on_delete=models.SET_NULL) Is it possible to render a single form that edits both the task model instance and associated task steps together, which I can update in a single submit? I know I can use inlineformset_factory to display the TaskStep child options, but there isn't much documentation on it. If I pass the following in a view: def manage_tasks(request, task_id): task = Task.objects.get(pk=task_id) TaskStepInlineFormSet = inlineformset_factory(TaskStep, Task, exclude=('',)) if request.method == "POST": formset = TaskStepInlineFormSet(request.POST, request.FILES, instance=task) if formset.is_valid(): formset.save() # etc This only appear displays the TaskStep objects and not the parent Task? -
django get_or_create depending on result from a custom manager method
I am trying to implement a safe method of creating instances of the model Bar. I have a custom manager method to search for any nearby existing Bar instances based on a x, y pair of coordinates: Bar.objects.circle_search(x, y, radius) These x, y values typically come from Foo. Upon creating a Foo instance it should then be associated via a foreign key with an existing Bar instance if Foo.x, Foo.y are within radius of Bar.x, Bar.y. If no Bar instances are found then create one. Each Bar instance has x, y columns that are defined by the Foo that created it. I had something simple like: bar = Bar.objects.circle_search(foo.x, foo.y, radius) if bar is None: # fill some kwargs bar, created = Bar.objects.get_or_create(**kwargs) however there is an obvious race here where two nearby foo's could create separate Bar instances that are close to each other (there shouldn't be any Bar instances within radius of each other). Is there anyway to chain/insert the circle_search method to be used as the get part of get_or_create? i.e. in plain English - get a Bar that matches the circle_search, if not then create one. # something like? Bar.object.get_or_create(circle_search(foo.x, foo.y, radius), **kwargs) The problem is … -
django-rest-framework- accepting id for submitted foreign key field
I have the following models: class Parent(models.Model): name = models.CharField() class Child(models.Model): name = models.CharField() parent = models.ForeignKey(Parent, on_delete=models.CASCADE) with serializer: class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ('id', 'name', 'parent',) read_only_fields = ('id',) and ModelViewSet: class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer permission_classes = (IsAuthenticated,) queryset = Child.objects.all() paginator = None If I query the api, I get a json structure that looks like: { "id": 1, "name": "Child Name", "parent": 3 } Which is exactly what I want. However, if I try to PUT the same data back, I get the error: ValueError: Cannot assign "3": "Child.parent" must be a "Parent" instance. How can I make a submission like this work? I should be able to submit my data in the same way I receive it from the API. -
How to get length of TextField in Django
I'm trying to get length of TextField instance by wrapping it into len(), but it's not working for me, says: Expected type 'Sized', got 'TextField' instead. class Entry(models.Model): text = models.TextField() def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." -
How to update ImageFiled with default image?
Hello I have a Profile model When user creates a Profile, I set an default image to image1 field and then the user can upload a new image in place of default. Now I need to implement in views.py function the update of user uploaded images with default image again, so when the user need to delete an image I put default-image instead. Thanks a lot models.py class Profile(models.Model): image1 = models.ImageField( default='default-image.jpg', upload_to='images', blank=True) views.py def update_image1(request): if request.method == 'POST': image1 = request.user.profile.image1 -
Django - Is it possible to create models (then migrate them) through a webpage?
I would like to know if there are examples or is it possible to design a webpage in which you can create a database (postgres) while the server is up (the app and page is for creating databases) thanks