Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
how to make a property function to act like a real field in the database
i want to make a (group by) which depend on some other fields , models.py class Product(models.Model): pass class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') date_time = models.DateTimeField(default=datetime.now()) @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) views.py class View(ListView): pass def get_context_data(self , *args,**kwargs): context = super().get_context_data(*args , **kwargs) context['daily'] = Order.objects.values('date_time').aggregate(days=Sum('total')) return context (Cannot resolve keyword 'total' into field. Choices are:...) is it possible to make the property function act as a field in the db ? or if there another way to achieve the same thing i trying to implement ? i also tried to views.py from .models.Order import total context['daily'] = Order.objects.values('date_time').aggregate(days=Sum(total())) but doesnt work ! thanks for any advice .. -
Many - To - Many field changes - Too many api calls
Using Django, I'm encountering the known issue with the Many-to-Many field. In the post_save_event signal/hook, the value in the Event instance for the many-to-many field: categories does not get updated with the most recent values submitted on the admin form. It always shows the old values. This is my save hook where I have a parent "Event" and each event has a field for 0 or many categories. However, the instance.categories value is not updated with most recent value. @receiver(post_save, sender=Event) def post_save_event(sender, instance, **kwargs): success = events_api.create_or_update_event(instance) I'm aware of why this happens. Basically, the many-to-many field needs to save after the parent model because the many-to-many table needs to have the primary key of events. I did the fix that i found online below. This is the signal that gets sent after the many-to-many table transaction is committed. This sort of works as a workaround but obviously this means that if the categories change on the event, the api gets called multiple times, even worse the m2m_changed signal seems to fire twice when it happens. So I end up calling the api 3 times for one update. Any work around/ hook i can use to maybe just do … -
Django ORM: queryset with SIMPLE 'order by'
I'm trying to make this simple 'group by' expression using django ORM, but I'm not sure how it would be: SELECT id, title, hotel_id, booking_id, day_number FROM `bookings_booking_item` where hotel_id IS NOT NULL AND booking_id=xxx group by booking_id, hotel_id ORDER BY id asc What I want to achieve is to get only one (the first) 'item' result per booking and hotel. Can anyone please help me, please? Thank you! -
Django bootstrap4 tab to perform action (call python function) and stay on current page
I had a quick look around and couldn't find anything really that matches this. I have a bootstrap4 navbar in my base.html template which is then inherited by all other pages on the web app. Most of the tabs are drop downs, which have options to link to other pages which is fine and working. I have one drop down which has a couple of items which are not meant to navigate to a page but rather execute an action (e.g. generate a report). I can do the report generation fine, but I am unable to find a solution that results in me staying on the same page. Base.html <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> BDE Report </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'bde_report' %}">Generate</a> <a class="dropdown-item" href="#">Download latest</a> </div> </li> url.py urlpatterns = [ path('', views.home, name='home'), path('bde_report/generate/', views.home, name='bde_report'), path('admin/', admin.site.urls), path('db_display/', views.db_display, name='db_display'), path('db_display/<str:table_name>/business_data_form', views.business_data_display, name='business_data_display'), path('db_display/business_data_form/new', views.business_data_new, name='business_data_new') ] views.py def home(request): # If the generate BDE button is pressed, return the report if request.path == '/bde_report/generate/': return generate_report() return render(request, 'home.html') With the current implementation it currently goes to the home page and generates the report, but ideally …