Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django passing variables to Jquery
I am struggling to understand this. I have a dictionary titled alldicts that I am passing from Views in Django into the HTML. How do I then reference that dictionary to Jquery to autofill in input values in my HTML? My code in Views: mydict1 = { 'one' : 1 'two' : 2 'three' : 3 } mydict2 = { 'one' : 4 'two' : 5 'three' : 6 } mydict3 = { 'one' : 7 'two' : 8 'three' : 9 } alldicts={ 'mydict1': mydict1, 'mydict2': mydict2, 'mydict3': mydict3 } return render(request, self.template_name, alldicts) In the HTML section of my code, I have a select dropdown with the options "mydict1","mydict2", and "mydict3". Below it I have three inputs (number of inputs will be dynamic, but wanted to give a simple example) that I want to auto fill to match the selected option. (IE if I select mydict2 in the dropdown, the inputs (#one, #two, and #three) will fill to be 4,5, and 6 respectively). In html, if I try something like this, it doesn't work: $("#hselect").change(function() { var a = "{{alldicts}}"; var selectedValue = $(this).val(); $.each( a, function(idx, obj) { $.each( obj, function(key, value){ if (selectedValue == idx) { … -
Injecting Python Inside Include Tag in Django
I have urls saved in a db and I want to inject the urls into an include tag. What is the work around for this? {% include {{ graphs.file.url }} %} -
No Blog matches the given query. DB is not removing deleted objects query number
DB is not automatically removing query of deleted objects and the question is how to make it work correctly so then when I do http://127.0.0.1:8000/blog/1/ it automatically shows 1st post (now it shows as if there is no post due to history of deleted objects. And if I do http://127.0.0.1:8000/blog/6/ it works fine Here is views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def allblogs(request): blogs = Blog.objects return render(request, 'blog/allblogs.html', {'blogs': blogs}) def detail(request, blog_id): try: question = get_object_or_404(Blog, pk=blog_id) except Blog.DoesNotExist: raise Http404("Question does not exist!!!") return render(request, 'blog/detail.html', {'questions': question}) -
Remove events from cell in FullCalendar. Place at the bottom of calendar in an event wrapper/container
I am using FullCalendar to embed in my website because it seems the easier option than trying to figure out how to make one from scratch. Is there a way to remove the events from the cell altogether and make it look something like this where if you click on the date the event shows at the bottom calendar with event at the bottom when clicked I am not sure on how to even begin doing this because I have very little experience with Jquery. Can Someone please help me or give me advice on what I could do instead? I've tried many different things, but none worked out. Thank You kindly. -
Django - Admin page login automatically even when trying to login in non-admin page
When I login in one of the non admin page (page which I created through LoginView Class in Django), it also automatically tries to authenticate admin login page and if the user is superuser, the admin page gets logged in even when the superuser does not want to login to the admin page and when a non super user logs in, again it tries to login in the admin page only to not get authorized. -
How to get data from dynamic models in Django
Hi Friends i have created models using django-dynamic-models library and able to create fields and data for new table. But unable to get data from dynamic table. I am using Django 2.2.6 version and python version is 3.6. If you have any solution, please help me. Please see the below code. With below test table has been created. But i want to retrieve data from this table same as from django tables. Tried with Test.objects.filter(), but not working. from dynamic_models.models import ModelSchema, FieldSchema car_schema = ModelSchema.objects.create(name='test') Car = car_schema.as_model() car_model_field = FieldSchema.objects.create(model_schema=car_schema, name='model', data_type='character') car_year_field = FieldSchema.objects.create(model_schema=car_schema, name='year', data_type='integer') # # # `as_model()` must be called again to regenerate the model class after a new field is added Car = car_schema.as_model() Car.objects.create(model='Chevrolet', year=1997) # assert Car.objects.filter(model='Chevrolet').count() == 1 -
Multiple images upload Django with dropzone
I want create django app with multiple upload images with dropzone I have 2 models: class Post(models.Model):user = models.ForeignKey(User) title = models.CharField(max_length=128)body = models.CharField(max_length=400) class Images(models.Model):post = models.ForeignKey(Post, default=None) image = models.ImageField(upload_to=get_image_filename,verbose_name='Image') My forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'body', ) class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('image', ) My views.py: def post(request): ImageFormSet = modelformset_factory(Images,form=ImageForm, extra=3)#without extra if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES,queryset=Images.objects.none()) if postForm.is_valid() and formset.is_valid(): post_form = postForm.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: image = form['image'] photo = Images(post=post_form,image=image) photo.save() messages.success(request,"Posted!") return HttpResponseRedirect("/") else: print postForm.errors, formset.errors else: postForm = PostForm() formset = ImageFormSet(queryset=Images.objects.none()) return render(request, 'index.html',{'postForm': postForm, 'formset': formset},context_instance=RequestContext(request)) How create add post page with dropzone??? Please help me -
How to retrive Useres selected object and use it later on in calculations
I am trying to calculate how much of chosen food a dog should get based on some variables. A User can choose a food type from database and click Select. The moment he does, I would like to get the 'calories_per_kg' based on his choosing, to calculate the dosage. I don't know how. Please help. What I have now: urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('dogs', views.results, name="results"), path('add_dog', views.AddDogView.as_view(), name="add_dog"), path('dogs/<int:id>', views.DogInfoView.as_view(), name="dog_info"),] models.py class DogForm(forms.Form): name = forms.CharField(max_length=20) age = forms.IntegerField() weight= forms.IntegerField() height = forms.CharField(max_length=2, widget=forms.Select(choices=HEIGHT)) dog_variable = forms.IntegerField(widget=forms.Select(choices=DOG_VARIABLE)) class DogFoodDry(models.Model): brand = models.CharField(max_length=25) name = models.CharField(max_length=100) calories_per_kg = models.IntegerField(null=False) def __str__(self): return "Brand: " + self.brand + "Name: " + self.name + "Calories_per_kg: " + str(self.calories_per_kg) forms.py class DogFoodDryForm(forms.Form): brand = forms.CharField(max_length=25) name = forms.CharField(max_length=100) calories_per_kg = forms.IntegerField() views.py: class DogInfoView(View): def get(self, request, id): form = DogFoodDryForm() dog = Dog.objects.get(id=id) foods = DogFoodDry.objects.all() rer = 70*dog.weight**0.75 dv = dog.dog_variable multiplier = None if dv == 0: multiplier = 3 elif dv == 1: multiplier = 2.5 elif dv == 2: multiplier = 1.6 elif dv == 3: multiplier = 1.8 elif dv == 4: multiplier = 2 elif dv == 5: multiplier … -
Problem with filtering and ordering data in Django-rest-framework
I have a problem in my views.py class BooksListAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer # filter_backends = (filters.OrderingFilter,) filterset_fields = ['published_date'] filter_fields = ['published_date'] search_fields = ['published_date'] ordering_fields = ['published_date'] lookup_field = 'id' and in my settings.py: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], } The problem is i want to order results with 'published_date' field as well as filter with it but when i comment out REST_FRAMEWORK and uncomment # filter_backends = (filters.OrderingFilter,) its ordering here and when i do opposite its giving only filter here. And i want both. Thanks in advance -
I don't know how to write views for Onetoonefield where I submit the details of lawyers and that is connected to model User
Can someone show me how to write the views for Onetoonefield when I submit the details I want to know which user details are that? -
FIlter instances that has the same field as instance id of which I provide in one query?
I have simple model: class User(models.Model): group_uuid = models.UUIDField(default=uuid.uuid4) Let say i have only available user_id, and I need to retrieve all the users that has the same group_uuid as user id of which I have in user_id variable. Not sure if we can utilize F or Subquery object in some ways. So we want to achieve this in one query: user = User.objects.get(id=user_id) User.objects.filter(group_uuid=Subquery(user)) This obviously is NOT making one query, but it should be possible to make it in one right? -
How to Create Staff/Superuser without code?
How can I have a dropdown menu for me to choose whether i want to add someone as a normal user, staff or super user? Im creating a django website/form This is my code for the user registration form on my django website. from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/registration.html' success_url = reverse_lazy('login') -
Why is this PUT request behaving like a PATCH?
So I'm working in this app with Django and DRF in the backend, and I'm having a problem with a certain endpoint. When making a PUT request to /api/v1/expenses/:id, if I modify the client or provider fields, as long as there is at least one client or provider, there is no problem, they can be modified all right. The request payload would look like this: { "id": 1, "type": 2, "provider": 4, "client": 6, "attachments": "[]", "tax": 1, "cost": "200.00", "withholding": "0.00", "total_cost": "242.00", "date": "2021-2-11", "description": "Factura luz sede", "created": "2021-02-11T13:51:33.218081Z", "updated": "2021-03-19T14:45:05.322533Z", "creator": 1 } However, if I leave the provider or client fields empty, and they aren't present in the request payload, they're not emptied, the response would still return whatever provider and/or client were there before. If I understand the PUT HTTP verb correctly, it should replace the resource with what's provided, right? Here is an example request to illustrate what I mean: { "id": 1, "type": 2, "attachments": "[]", "tax": 1, "cost": "200.00", "withholding": "0.00", "total_cost": "242.00", "date": "2021-2-11", "description": "Factura luz sede", "created": "2021-02-11T13:51:33.218081Z", "updated": "2021-03-19T14:43:31.780350Z", "creator": 1 } The model, stripped down to the problematic fields: class Expense(models.Model): provider = models.ForeignKey('contacts.Contact', on_delete=models.SET_NULL, related_name="expenses", … -
Get top n values of multiple columns after a group_by in django
qs = models.Stats.objects.all().values('player_id').annotate(**player_stats) I have a GROUP_BY with aggregation over multiple columns, see above. In my case that produces a result set of 8523 elements. [{'player_id': 1, 'abc': 205.0, 'def': 53.0, 'ghi': 37.0, 'jkl': 151.0, 'mno': 2.0, 'pqr': 959.0, ...}, {'player_id': 2, ...}, {'player_id': 3, ...}, ...] I want to get the top n players of different categories now, my first naive approach was to order_by that result set for every key i want o get the top n players for. qs.order_by('-abc)[:5], qs.order_by('-def)[:5] That is pretty slow because it hits the database with the full initial GROUP_BY query every time which is pretty heavy itself. In the end i just need the top 5 for each category ( abc, def, ghi ...), e.g. [{'player_id': 1, 'abc': 205.0}, {'player_id': 477, 'abc': 202.0}, {}, {}, {}] My guess is i can somehow achieve that with Djangos Window functions in a way more efficient manner, but i'm a little bit lost. -
Get Logged user, while updating Model User with UpdateView in Django
new to Django here building my first project. I´m using Django authentication and when user is logged, I show in a template panel the logged user using <li> <a style="color: wheat;" href="#"><i class="fi-torso"></i>{{user.full_name}}</a> <ul class="menu vertical" style="background-color:rgb(51,51,51); border-color: wheat;"> <li><a href="{% url 'users_app:user-logout' %}">Cerrar Sesión</a></li> </ul> </li> The thing is that logged user can modify other users attributes through UpdateView. So when I select user for updating (context user now is the user that is going to be updated), and I access Modify user template, in my panel instead of seeing logged user, I see the user that is being modify. How can I diferenciate this? I understand why this is happening, but haven´t found how to solve it -
How to check spyder versions in windows command prompt?
Please provide commands for checking Spyder IDE , Python IDLE, Atom IDE,SublimeText3 versions in windows command prompt -
JS fetching current data after posting form data
I am trying to create a single page application, but I am having problem getting the latest data after redirecting from the compose-form to the list of sent emails page. I get the previously loaded emails instead. I have to click the sent button, so as to update the list. Any solutions The html code is <h2>{{ request.user.email }}</h2> <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button> <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button> <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button> <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button> <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a> <hr> <div id="emails-view"> </div> <div id="compose-view"> <h3>New Email</h3> <form id="compose-form"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary mt-2" value="Send" id="sendButton"/> </form> </div> The JS code // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); //My added events // To initiate post request, when posting the mail document.querySelector('#compose-form').addEventListener('submit', post_email); // By default, load the inbox load_mailbox('inbox'); }); var state; function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; … -
python - django - local variable referenced before assignment django error
I am at my wit's end, I have no idea what may cause that issue. The only change I've made was add the loginquiredmixins to my class-based views. Once I started stylising the login page I seem to have broken something, but I have no idea what exactly, which is a weird idea to have, what issue could CSS or some HTML cause, right? I tried to assign the variables before the if statement and set it to null but that seems not to work properly as it throws an error regardless. I am using the basic django authentication system. The exact error I am getting is - local variable 'course' referenced before assignment Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 3.0.7 Python Version: 3.7.3 Installed Applications: ['mainpage.apps.MainpageConfig', 'quiz.apps.QuizConfig', 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\m\AppData\Local\Continuum\anaconda33\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, … -
How to get the user's username and other parameters instead of just 'id' when using django.core.serializers?
Hey guys I want to get the user's username instead of id from the below code when I use django's serializer method, also want to know the possibilities of getting their profile pictures as well. This is the code. This method is being used with django-channels for a simple chat system. def get_chat_list(self, user): try: chats = Chat.objects.by_user(user).order_by('-timestamp') chat_list = serialize('json', chats, fields=('first_user', 'second_user', 'timestamp')) payload =json.loads(chat_list) # print(payload) return payload except Exception as e: print('Exception: ', str(e)) return None How can I get the first_user's and second_user's username and profile images? Thanks in advance. -
Django subqueries & aggregates
I have three models - Patient, Prescription and Medicine. A Patient can have zero or more Prescriptions and a Prescription can have zero or more Medicines. Medicine has a duration field indicating the days for which the medicine is to be taken. If we have say, two Prescriptions with two Medicines each with durations of 15, 15 and 15, 30 respectively, then the maximum prescription duration for the 2 Prescriptions are 15 and 30 respectively. And the total medication duration for that Patient is 15 + 30 = 45. Now I want to filter the Patient queryset to find all Patients whose total medication duration is at least a certain specified value. Following is the code (using Django 3) I am trying. But, taking the above example, the total medication duration I get is 30, not 45. from django.db import models from django.db.models import Subquery, OuterRef, Max, Sum class Patient(models.Model): name = models.CharField(max_length=300) # ... class Prescription(models.Model): patient = models.ForeignKey( Patient, related_name="prescriptions" on_delete=models.CASCADE ) # ... class Medicine(models.Model): prescription = models.ForeignKey( Prescription, related_name="medicines" on_delete=models.CASCADE ) duration = models.PositiveIntegerField() # ... def get_patients_with(minimum_medication_duration=365): patient_qs = ( Patient.objects .annotate(total_medication_duration=Subquery( Prescription.objects .filter(patient=OuterRef('pk')) .values('patient__pk') .annotate(max_prescription_durations=Subquery( Medicine.objects .filter(prescription=OuterRef('pk')) .values('prescription__pk') .annotate(max_duration=Max('duration')) .values('max_duration') )) .annotate(total_medication_duration=Sum('max_prescription_durations')) .values('total_medication_duration') )) … -
Django Web Scraping
I have a Django project that I am working on, to scrape data from a website and display it on the Django page. The page however takes about 10 seconds to load, because accessing the data from another website isn't quick. My solution to this would be to create a model that stores the data, then updates itself in the background, but I don't know how to execute this. I am also open to other options, I'm pretty new at this :) This is currently what my code looks like, which is too slow: from django.shortcuts import render import requests, json def getNums(): from bs4 import BeautifulSoup import time, urllib.request, requests url = "https://www.worldometers.info/coronavirus/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") numberContainers = soup.select(".maincounter-number") spanTags = [] for container in numberContainers: spanTags.append(container.findChildren("span")) numbers = [] for container in spanTags: numbers.append(container[0].decode_contents()) return numbers def homeView(request): numbers = getNums() cases = numbers[0] deaths = numbers[1] recovered = numbers[2] context = { "cases": cases, "deaths": deaths, "recovered": recovered, } return render(request, "home.html", context) -
Running executable backgroung program inside server
I'm an intern in a laboratory in my college that works with air quality, and they want me to improve their website that runs one of the programs that air quality researchers use (I think that the program is written in RUST). The way it works right now is that the user uploads some necessary files to the webapp (that is written in Django btw) and then the webapp calls this program, that runs on the server with the uploaded files. The problem is that if the user leave or refresh the page, the background program will stop. I have never dealt with this concept of running other executables in the background of the server, so I'm having some problems understanding it all. I came across the "Celery" package for python, but it seems really hard to implement and I was wondering if there was any other ways of doing this. -
Django 3.1.7 query parameter separators
With the change in Django 3.1.7 to not allow using ; as a default query parameter separator, what is the suggestion moving forward? Is there something else that should be used instead? Where does one specify which query param separators are permitted? There are the release notes for this version. -
Use python's mock patch.object to check if a functions is called
I need to assert if a function is called @requests_mock.Mocker() def test_api_mca_payment_confirmation_call_db_log(self, mocker): mocker.register_uri('GET', requests_mock.ANY, status_code=200, text='test') with patch.object('__name__', 'db_log') as m: r = api_payment_confirmation(txn_no=900) m.assert_called_once() The problem is on the first patch.object parameter, what to put there if my db_log function is not inside any class. It works if i put a db_log function inside a class eg class Sample: @static_method def db_log(): pass And change line to patch.object('__name__', 'db_log') as m: How can i do the same thing for functions outside class -
RegexValidator didn't catch violation of regex
Django 3.1.7 class RenderedCssFile(models.Model): css_pattern = r".*-\d+\.css$" regex_validator = RegexValidator(regex=css_pattern, message=gettext("File name must follow: ") + css_pattern, ) file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[regex_validator], ) Could you help me understand why a file called 'bootstrap.css' has managed to upload? I estimated it to fail, but it uploaded. I've made a mistake somewhere. My regex: https://regex101.com/r/N5aL0C/1/ I need that only bootstrap-1.css or the like should be accepted.