Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - Adding to M2M relationship when realtionship already exist
I have an M2M relationship like this: class Foo: # foo fields... class Bar: Foos = ManytoManyField(Foo) I am trying to add a foo to the list of foos attributed to a Bar, so here's what I have: if Foo not in Bar.Foos: Bar.Foos.add(Foo) Question: is the if-judgment really necessary? Thanks -
How do you annotate with conditionals in Django?
I am trying to figure out how to use annotate with conditionals. One of my models is called Product, I want to group the objects in years and then for each year I wan to get the total profit for the year and divide it by the total cost of all products that meet a specific status. My attempt looks like below: from django.db.models.functions import Cast, Trunc from django.db.models import Case, When, Value, FloatField group_by = "year" products.annotate(group_by=Trunc("timestamp", group_by)) # Add year .values("group_by") # Group by year .annotate(profit_margin=Cast(Sum("profit") / When(status__name__in=["In Stock", "Not Sold"], then=Value(Product.cost)), default=0.0, output_field=FloatField()), FloatField) The latest error I get, besides missing parentheses is: db_type() missing 1 required positional argument: 'connection' Maybe I am overcomplicating things. Another thing, that I need to look up is how can I dynamically change group_by keyword in annotate to the value of group_by variable, in this example year. -
Django error NoReverseMatch: Reverse for 'student_update' with arguments '('',)' not found. 1 pattern(s) tried: ['students/(?P<pk>\\d+)/update/$']
Cant quite figure this one out, full error is: NoReverseMatch: Reverse for 'student_update' with arguments '('',)' not found. 1 pattern(s) tried: ['students/(?P\d+)/update/$']* models.py class Student(models.Model): student_id = models.CharField(max_length=10, primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Meta: verbose_name = "Student" verbose_name_plural = "Students" urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', HomeView.as_view()), url(r'^students/$', views.students, name='students'), url(r'courses/$', views.courses, name='courses'), url(r'registrations/$', views.registrations, name='registrations'), url(r'thanks/', views.thanks, name='thanks'), url(r'students/create/', views.student_create, name='student_create'), url(r'^students/(?P<pk>\d+)/update/$', views.student_update, name='student_update'), html file % for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.id }}</td> <td> <button type="button" class="btn btn-warning btn-sm js-update-student" data-url="{% url 'student_update' student.id %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> </tr> {% empty %} <tr> <td colspan="7" class="text-center bg-warning">No student</td> </tr> {% endfor %} -
Django css inside textfield model fieldtype
Is it possible to put css code or syling inside a DJango textfield for example a texfield for a django blog app? Thanks a lot to all. -
Django with binary request response
I've created a server that uses zmq(messaging) to communicate with clients. It's basically an api that uses messaging instead of http. I'm using protocol buffers to serialize the messages. A message is like this: Request: "CreateProject" ProjectName: "ProjectName" Data: Related binary data with the project Now the problem. My database layer is a bit brittle and I'm not sure it'll work well with changes to database in the future. I'm using sqlite as a document store. Recently I had to create a web app that used django and I fell in love with it. I want to port my app to django however I don't want to give up on protocol buffers as I'm dealing with lots of multi file uploads/downloads. I found that clients would only be able to use POST(or maybe PUT?) to send binary messages to my server and back. Is that somehow wrong? Basically all my views probably will look like this: def Someview(request): if request.POST: # Deserialize request.POST # process request here # send serialized binary protocol buffer response back I did some research but couldn't find any info on the subject. -
CreateView creating two model objects
I have created a Form, where the User sets an Alarm object. The Alarm object saves as expected to the database. However, the issue is that: another object, which contains only the information completed in the Form, also saves to the database. As I understand, form_valid() for CreateView saves the form. I have tried the two solutions suggested in another query with no success. I suspect that the issue is caused by either return super().form_valid(form) or by Alarm.objects.create() in create_alarm_object(). Views.py class AlarmCreateView(LoginRequiredMixin, CreateView): """ CreateView for User to create the Alarm object """ model = Alarm form_class = SetAlarmForm template_name = 'weather_alarm/set_alarm.html' login_url = "/login/" def form_valid(self, form): self.create_alarm_object(request, form) return super().form_valid(form) def get_success_url(self, **kwargs): return reverse("weather_alarm:active-alarm", kwargs={'pk':self.object.pk}) def create_alarm_object(self, request, form): """ Function to get User's location from IP and create Alarm object """ ... alarm_object = Alarm.objects.create( alarm_id=uuid.uuid4(), user=self.request.user, timezone=user_timezone, city=location.raw['address']['city'], country=location.raw['address']['country'], time=form.cleaned_data['time'].astimezone(pytz.timezone(user_timezone)), temp_conditional=form.cleaned_data['temp_conditional'], surf_conditional=form.cleaned_data['surf_conditional'], temp_max=form.cleaned_data['temp_max'], temp_min=form.cleaned_data['temp_min'], surf_max=form.cleaned_data['surf_max'], surf_min=form.cleaned_data['surf_min'], ) alarm_object.save() -
Django sqlite denied permissions
I'm trying to run a Django project on my raspberry pi. I'm having some trouble transferring the database that I had on the previous computer though. I tried running the server and everything ran smoothly until I attempted to log in. Django reported that it could read but not write/edit the file. I made sure all the permissions on the db.sqlite3 is set correctly, yet Django still can't modify it. It can only read it. -rwxr-xr-x 1 pi pi 200704 Aug 10 04:13 db.sqlite3 The above code is the permissions I have set for the file. When I try to log in, it also says it can't read or write. Any suggestions to fix this would be appreciated, I can also post other information if needed. Thanks -
How to make Django forms overrun
I have a Django form with some Charfields, however when a user enters a value which exceeds the width of the box, they have to scroll to see what they have wrote. Is there a way to make it so that the boxes get bigger if a longer value is entered? -
Download beanstalk instance data
I have a Django server running on Beanstalk, and due to my lack of foresight I didn't choose to use Codecommit at first or migrate away from SQLite. Now every time I deploy my app to the server using eb deploy, my data is wipe clean. Is there any way for me to download the entire code source with data input from users and all for the current instance from the Beanstalk server? If I choose the to download the code from version history, it would just return to me the the zip version of the code I deploy with eb deploy. -
Refactoring two similar loops using a python function in Django
I have two similar for loops in Django that loops through a data model, while both loops are similar in nature they access different data models and different fields. I'm having a difficult time trying to build a function and figuring out the proper arguments to pass within the functions that accommodates both loops. Please see the loops below. #Loop 1: task_list = [] toQuery = group1.task.all() for x in tasks: array = [] array.append(x.id) array.append(x.task_name) task_list.append(array) #Loop 2: student_list = [] toQuery2 = student.task.all() for x in tasks: array = [] array.append(x.id) array.append(x.student_name) task_list.append(array) -
What's the best way to render a mixture of html and plain text in Django?
On my site users can create posts with a mixture of plain text and html. I'm having trouble rendering their posts nicely. E.g., they might write: This is the first line of the post. <!-- whitespace 1 --> <ul> <li>List item 1.</li> <!-- whitespace 2 --> <li>List item 2.</li> <li>List item 3.</li> </ul> <!-- whitespace 3 --> This is the last line of the post. and I want whitespace 1 and 3 to render, but not whitespace 2. How can I do this? I've tried using a combination of linebreaks and spaceless but cannot get it to work. Thanks Jack -
Python - Multiple Inheritance in Django widgets
Okay, so this might be a very basic question related to Python more than Django. Here is the code for my two widgets that are to be used in Django forms. class MaterialTextInput(forms.TextInput): template_name = "portal/widgets/material_textinput.html" error_messages = None initial = None def __init__(self, label, attrs=None, colsize=6, padding_top=20): super(MaterialTextInput, self).__init__(attrs) self.attrs.update({"required": False, "data-required": self.attrs.get("required", False)}) self.label = label self.colsize = colsize self.padding_top = padding_top def get_context(self, name, value, attrs): attrs.update({"required": False, "data-required": attrs.get("required", False)}) context = super(MaterialTextInput, self).get_context(name, value, attrs) context['widget']['label'] = self.label context['widget']['error_messages'] = self.error_messages context['widget']['validation_error'] = self.validation_error if hasattr(self, "validation_error") else None context['widget']['colsize'] = self.colsize context['widget']['padding_top'] = self.padding_top return context def set_error_messages(self, error_messages): self.error_messages = error_messages def set_initial(self, initial): self.initial = initial class MaterialPasswordInput(forms.PasswordInput): template_name = "portal/widgets/material_textinput.html" error_messages = None initial = None def __init__(self, label, attrs=None, colsize=6, padding_top=20): super(MaterialPasswordInput, self).__init__(attrs) self.attrs.update({"required": False, "data-required": self.attrs.get("required", False)}) self.label = label self.colsize = colsize self.padding_top = padding_top def get_context(self, name, value, attrs): attrs.update({"required": False, "data-required": attrs.get("required", False)}) context = super(MaterialPasswordInput, self).get_context(name, value, attrs) context['widget']['label'] = self.label context['widget']['error_messages'] = self.error_messages context['widget']['validation_error'] = self.validation_error if hasattr(self, "validation_error") else None context['widget']['colsize'] = self.colsize context['widget']['padding_top'] = self.padding_top return context def set_error_messages(self, error_messages): self.error_messages = error_messages def set_initial(self, initial): self.initial = initial As you can … -
Explain built in User model and UserCreationForm
I understand that django comes with a User model built in and the following code works and properly saves a user to the db, I just don't understand why it works: from django.shortcuts import render from django.http import HttpResponse from .forms import UserCreationForm def index(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() return HttpResponse('Saved') else: form = UserCreationForm() return render(request, 'core/index.html', {'form':form}) what is the line form = UserCreationForm(request.POST) saying? is the (request.POST) the contents of the submitted form? and how does user = form.save() save a user to the database? I was thinking that maybe the variable had to be named user for django to recognize it as a User object but this is not the case as I changed the statement to test = form.save() and it still saved a User to my database. -
site cannot reached after nginx restart - AWS EC2
I am following the tutorial and completed it without any error, when I start nginx it showed me welcome page but after I restart nginx chrome is showing This site can’t be reached. I am accessing it by my public IP. Here is my security group of instance (Inbound) (Outbound) Here is my nginx conf file: upstream sample_project_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/home/ubuntu/django_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name <my public ip>; client_max_body_size 4G; access_log /home/ubuntu/logs/nginx-access.log; error_log /home/ubuntu/logs/nginx-error.log; location /static/ { alias /home/ubuntu/static/; } location /media/ { alias /home/ubuntu/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever … -
What's the difference between running heroku local and python manage.py
I am developing a web app and i want to have obviously local environment. However I need to setup local env configs in my .env file and when I run python manage.py runserver it doesn't seem to load my env file, although heroku local does load it. Just to make sure I understand whats happening, id love to know what is the difference. -
Django all-auth csrf token not working with React Native POST request
I am trying to set up django authentication on my react-native application and I can not get it working. I have scoured every stack overflow page and tried multiple frameworks so I think I am missing some piece of information. Here is what I currently have: function get_headers(response) { var headers_dict = {}; const headers = response.headers.map["set-cookie"][0].split(";"); for (var header in headers) { var key_value = headers[header].split("="); console.log(key_value); headers_dict[key_value[0].trim()] = key_value[1]; } return headers_dict; } views #screens/login.js sign_in(payload) { fetch('http://localhost:8000/accounts/login/', { method: 'GET', headers: { Accept: 'text/html', }, }).then((res,err) => { const response_headers = get_headers(res); fetch('http://localhost:8000/accounts/login/', { method: 'POST', headers: { Accept: 'application/json', "Content-Type": "application/json", "X-Frame-Options": "SAMEORIGIN", "X-CSRF-Token": response_headers.csrftoken, }, body: JSON.stringify({ username: payload.username, password: payload.password, csrftoken: response_headers.csrftoken, }), }).then((res) => { console.log(res); }); }); } I am using the default LoginView provided by django-allauth. This is what shows up in the logs. Forbidden (CSRF token missing or incorrect.): /accounts/login/ Do i need to be sending the CSRFMiddleware token versus the CSRFToken token Or do I need to overwrite the default login form with a custom one on the django side? Thanks -
How do I send a Django model and it's related (_set)s via Ajax?
How do I send a Django model and it's related (_set)s via Ajax? class Zoo(models.Model): id = models.AutoField(primary_key=True) details = models.TextField(blank=True) # HUGE AMOUNT OF DATA animals_json = models.TextField(blank=True) # Information on what animals are in Zoo class Animals(models.Model): id = models.AutoField(primary_key=True) zoo = models.ForeignKey(Zoo, on_delete=models.PROTECT) animal_name = models.TextField(blank=True) zoo = Zoo.objects.filter(pk=5) animals = [] for animal in json.loads(zoo.animals_json): animals.append(Animals(zoo=zoo, animal_name=animal['name'])) # Now I have a Zoo model and a list of animals. # My Zoo model has a animal_set (RelatedManager) object Now, I would like to send a JSON encoded Zoo via Ajax to front end. How do I do this? Option 1) zoo_json = serializers.serialize('json', [zoo]) return HttpResposne(zoo_json) This won't work because then I'm not sending any information about the animals. (Yes I realized it's encoded in the animals_json, but I want to just send clean objects via AJAX and not parse it with a front end loop). Something like this seems very messy as well because now the objects are seperate from one another: zoo_json = serializers.serialize('json', [zoo]) animals_json = serializers.serialize('json', animals) data_to_send_via_ajaz = {'zoo' : zoo_json, 'animals' : animals_json} return HttpResposne(zoo_json) My ideal object looks like this: zoo_model_in_json_form [ animal_model_in_json_form, animal_model_in_json_form, animal_model_in_json_form, ... ] return HttpResposne(zoo_model_in_json_form) … -
The ST_AddPoint function is implemented in GeoDjango?
Actually have a LineStringField on my model, and need actualize this field every 15 seconds, i have a total of 300 points, this represent a problem in the asynchronous performance?. -
Django - How do you process and validate multiple ModelForms using a single template?
I am new to Django and would like to take 2 of my ModelForms and place them on the same template for processing. In turn this will update the two corresponding tables. I found an answer online using MultipleFormViews but when it shows the forms on the template, it renders with 2 separate submit buttons a is not storing the data in the database. I initally tried using the Class views but had no luck since generics.CreateView was only able to take one ModelForm. If their is a better way to do this then I have no problem taking a different route. Thank you in advance! Python3.7, Django2.1, Windows10 # Requisition/Views.py from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404, render, render_to_response from django.urls import reverse, reverse_lazy from django.views import generic from .models import Requisition from django.db.models import F from django.contrib.auth.mixins import LoginRequiredMixin from items.models import ItemMaster from requisitions.forms import RequisitionForm from items.forms import ItemForm from requisitions.multiple_forms import MultipleFormsView class create_req(LoginRequiredMixin, MultipleFormsView): template_name = 'requisitions/create-req.html' success_url = reverse_lazy('home') # here we specify all forms that should be displayed forms_classes = [ ItemForm, RequisitionForm ] def get_forms_classes(self): forms_classes = super(create_req, self).get_forms_classes() user = self.request.user return forms_classes def form_valid(self, form): print("yay it's … -
Django links to other other apps
Maybe this question has been answered before in one way or another. But I need to ask because I tried to answer it myself I googled it for days but I couldn't figure it out. I have an app called reception in my Django project. I figured out everything but this. I have the link in the html directing to the right urlpattern. urlpatterns = [..., path('go_to_reception', views.reception, name='go_to_reception'), ...] And the view is like this def reception(request): return render(request, 'reception.html') now instead of reception.html I would like for it to point to the reception app. What do I need to write there. Nothing works. the reception is as follows: http://127.0.0.1:8000/admin/reception/ So how do I point to this. Please help! Thanks -
Celery sending tasks but not executing them
I've a currently running setup of Django 1.11.15, Celery 4.2 and Redis 4.0.2 on docker-compose and I detected that my periodic tasks are being properly sent by celerybeat but it seems the worker isn't running them. A simple test task: from celery.utils.log import get_task_logger from turnapp.celery import app logger = get_task_logger(__name__) @app.task def say_hello(): print("HELLO!") logger.info("HELLO!") return "HELLO!" Which I configured to run every one minute. The task is loaded and gets send every one minute, but it never runs (because I don't see the HELLO! string on my output): celeryworkerdev_1 | [2018-08-10 19:06:32,229: INFO/MainProcess] default@8516f3a70571 ready. celerybeatdev_1 | [2018-08-10 19:08:30,044: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. celerybeatdev_1 | [2018-08-10 19:08:35,051: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. celerybeatdev_1 | [2018-08-10 19:08:40,060: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. celerybeatdev_1 | [2018-08-10 19:08:45,069: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. celerybeatdev_1 | [2018-08-10 19:08:50,077: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. celeryworkerdev_1 | [2018-08-10 19:06:32,230: DEBUG/MainProcess] basic.qos: prefetch_count->4 celerybeatdev_1 | [2018-08-10 19:08:55,084: DEBUG/MainProcess] beat: Waking up in 4.91 seconds. celerybeatdev_1 | [2018-08-10 19:09:00,001: INFO/MainProcess] Scheduler: Sending due task gymnasium_say-hello (gymnasium.say_hello) celerybeatdev_1 | [2018-08-10 19:09:00,002: DEBUG/MainProcess] gymnasium.say_hello sent. id->ef0a2715-185e-49da-89a0-a9f65b4ed05a celerybeatdev_1 | [2018-08-10 19:09:00,003: DEBUG/MainProcess] beat: Waking up in 5.00 seconds. … -
Getting syntax error when passing **kwargs to django filter
I am trying to filter the database with store ID I passed via stored kwargs but getting a syntax error. Store.objects.filter(**kwargs['filter'] = filter_store) basically **kwargs['filter'] here has "id" value and filter_store has the store IDs. It should perform the following with **kwargs: Store.objects.filter(id = 4334225) Syntax Error -
Django Admin upload file when form is invalid
I have a field of type FileField in my model. In the admin, when the form is invalid, the upload file is lost and it shows the error in the admin page without the file uploaded. How do I solve this? -
Django queryset on context
So I've been working on a simple Django app for a rental company, it shows when customers come by to pick up their bicycle at which location. For the check-ins, I use a date, given by one of the emplyees to filter the records on date and pick-up location. Before, we had different pages for different pickup locations, now we would like to show two different locations in a single view and again filter these records on any given date. I used the context to add data to retrieve with another template tag. There's one thing I do not get. Whenever list "location_a_list" gets filtered by the queryset, the given date by an employee, the "location_b_list" shows all existing records for all dates. How can the queryset be applied to all context? #views.py from .forms import DateSelection class CheckInsListView(generic.ListView, FormMixin): form_class = DateSelection model = Order queryset = Order.objects.all() template_name = 'check-ins.html' context_object_name = 'location_a_list' """ Save the user given date in a session key "set_date" """ def get_context_data(self, *args, **kwargs): context = super(CheckInsListView, self).get_context_data(*args, **kwargs) user_date = self.request.GET.get("date_selection") set_date = self.request.session.setdefault('set_date', str(datetime.now().strftime("%Y-%m-%d"))) context['location_b_list'] = Order.objects.all() if user_date: # If user enters date self.request.session['set_date'] = user_date # Save given date … -
Content Not Loading Into Div Upon Click (w. jQuery )
I've been staring at this issue all morning now, and I just cannot see where my problem is. I've looked at most other "load content into div upon click" posts, and all the jQuery scripts/div ID's seem to be same with what I have. Essentially, I have a card on my page with 2 links as header, "Content A" and "Content B." I'd like the card-body to change dynamically as someone clicks between Content A and Content B. I'm making the site with Django, if that makes any difference. The card is from Bootstrap. This is my code: <div class="card text-center" style="width: 800px;"> <div class="card-header"> <ul class="nav nav-pills card-header-pills"> <li class="nav-item"> <a class="nav-link" href="#actionA" style="color:#1DA1F2" id="actionA">Show Content A</a> </li> <li class="nav-item"> <a class="nav-link" href="#actionB" style="color:#1DA1F2" id="actionB">Show Content B</a> </li> </ul> </div> <div class="card-body" id="tweetcontent"> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <script> $("#actionA").on("click", function(){ $("#tweetcontent").load("top10pos.html"); }); </script> </div> </div> All top10pos.html has inside is just <p>Content A</p> (testing), and it's in the same directory as the HTML file with the above card code. What am I doing wrong? Everything seems to be following what most other posts said was a fix. Any help would be greatly appreciated. Thank you.