Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django unittest, how to mock same class inside the view?
views.py def order(request, pk): products = JsonManager('FastProducts').target_data products_prices = JsonManager('FastProductsPrices').target_data tests.test_views class OrderApiTestCase(APITestCase): def setUp(self) -> None: self.user = User.objects.create_user('john', 'john@snow.com', 'johnpassword') def test_order(self, ): self.client.login(username='john', password='johnpassword') TARGET_CHOICES = ( ('FastProducts', 'FastProducts'), ('FastProductsPrices', 'FastProductsPrices'), ) class JsonManager: def __init__(self, target: str): assert target in dict(TARGET_CHOICES), f'`JsonManager` Unrecognized target: "{target}"' self.target = target self.target_data = [] self._read_target_data() def _read_target_data(self): with open(self.target_data_path) as r: self.target_data = json.loads(r.read()) How can i mock JsonManager class call with static object? It is possible to mock same class two times with different objects and input parameters? -
Google Cloud Platform - Django - Scheduled task to remove expired data
I have a Django application connected to Cloud Run at Google Cloud Platform. I am in need to schedule a task to run everyday. The task should go through a table in the database and remove rows that exceed todays date. I have looked in to Cloud functions, however, when I try to create one, it appears to only support Flask, and not Django. Any ideas on how to precede to make this scheduled function and access the database? -
German as default language in Django but admin in English
I need to have German as a default language (due to existing urls without prefix) but need to have admin in English - since I don't know German. Can someone help me with that, please? Using Django 3.2.12 and Django CMS 3.9.0 -
Teg p don't overlap with the picture
index.html {% extends 'main/base.html' %} {% load static %} {% block title %} {{title}} {% endblock %} {% block content %} <link rel = 'stylesheet' href="{% static "main/css/index.css" %}"> <body> <div class="grid-wrapper"> <header class="grid-header"> <img class="circles" src="{% static "main/img/main8.jpg" %}" alt="main pic"> <p>Предоставим качественное образование, <br> поможем понять школьную программу, <br> улучшить оценки и <br> подготовиться к экзаменам</p> </header> </div> </body> {% endblock %} index.css .grid-wrapper { display: grid; grid-template-columns: 1 fr; grid-template-rows: 1 fr; grid-template-areas: 'header header'; } .circles { display: block; margin-left: auto; margin-right: auto; } header { position: relative; width: 100%; } p { color: red; text-align: center; position: absolute; width: 100%; text-align: center; } Else tegs in index.css work right. When I created the other file with the same code (but without Django), it all worked out. I tried to write .grid-header p and header p and .grid-wrapper p, but nothing helped. With the help of <p> I tried to put the text on the picture -
How to return a Jsonresponse in a CreateView? Django
I'm trying to get all the users who has the group 'decoration' into a form field. I'm using JsonResponse to get the list in realtime when the user start to type. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['...'] def get_form(self, form_class=None): form = super().get_form(form_class) if 'term' in self.request.GET: qs = User.objects.filter(groups__name='decoration', username__icontains=self.request.GET.get('term')) titles = list() for product in qs: titles.append(product.username) form.fields['culture'] = titles return JsonResponse(form, safe=False) return form I know this is not the correct way according the doc, I should make the mixin outside: https://docs.djangoproject.com/en/4.0/topics/class-based-views/mixins/ But I' dont know how to implement a json response properly into my CreateView, I've been trying for the last days and with no luck. Any help would be grateful! -
Update list of data in a custom way
I have a scenario and want to know the best possible way to handle it. I have a user who has n number of addresses. addressList (id) for example (which I get at frontend) - addresses=[1,2,3,4] Once I fetch all the addresses to the frontend, the user can delete one or n number of addresses. Note - The delete is only removing the address object from the list (at frontend) and not permanently delete it from the database. so here, addressList now can be - addresses=[1,4] Also, the users add n number of new addresses the new addressList may be - addresses=[1,4, {newAddressDetail}, {newAddressDetail}] Not this updated data(addresses) is sent over to the backend for the update process. Would like to know how to handle this scenario best at the backend ? Things are - delete all the previously saved addresses which are not received currently. Not to alter the previously saved addresses which are received currently. create new addresses which are not in the database. It is not advised to delete an address from the database when the user removes it from the frontend. The address is not editable at the frontend and the data which I have shown … -
is it possible to redirect to another page with id from the previous page?
So as you can see on a page I have Shop name and it's adress. Moreover I have edit function on views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoLibrary, id=id) # * pass the object as instance in form form_shop = VideoLibraryForm(request.POST or None, instance=obj_shop) # * save the data from the form and # * redirect to detail_view if form_shop.is_valid(): form_shop.save() return HttpResponseRedirect('/main/') context['form_shop'] = form_shop return render(request, 'update/update_shop.html', context) urls.py: ... path('list_view/', views.list_view, name='list_view'), path('shop/<id>/update', views.update_shop, name='update_shop'), The image is different page ('lilst_view') and the issue is - I need to place a button on this page and redirect to update page in order to edit certain shop name for example. To do this as I suppose I need to get somehow id of the object. Does anybody know how to do it? -
How to link an ID generated URL to the <a href> tag
I am making my own portfolio website using Django.. So the idea is: Make posts containing websites that i've developed. All these posts will be displayed in a page called "Projects" and then you can access a single project to read about it. Every project i upload have an ID, so i used this code to acess each project page: # Single project page path('projects/<int:post_id>/', views.project, name='project'), Then in my PROJECTS page i have a simple(for now) HTML code to show all my projects and link them to the single project page. What i want to know is how to LINK this ID generated URL in this code: <ul> {% for project in projects %} <li><a href="#">{{ project }}</a></li> {% empty %} <li>No project have been added yet.</li> {% endfor %} </ul> I tried using: <li><a href="{% url 'main_portfolio/projects/<int:post_id>/' %}</a></li And some other things but nothing i try is working. -
Is there any option for locking user by there email and IP instead of username and IP by using django-axes ? Or any alternative methods are available?
Is there any option for locking user by there email and IP instead of username and IP by using django-axes ? Or any alternative methods are available? Am using django administration by email and password instead of username and password. -
React: NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name
I'm using React and Dj-Rest-Auth for my authentication. I was able to set up the login page, registration page and the email confirmation page. But when i try to set up the Password Reset page i get this error every time i submit an email address inside the reset password form: django | django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Does anyone know why this happens and how it can be fixed? This is how i set it all up: urls.py # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")), # DRF auth token path("auth-token/", obtain_auth_token), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')) ] reset.js import { useState } from 'react'; import { Formik, Field, Form } from 'formik'; import axios from "axios" import { API } from '../api' export function Reset() { const [loading, setLoading] = useState(false) const [success, setSuccess] = useState(false) function handleSubmit(values, { resetForm }) { setLoading(true) axios.post(API.auth.passwordReset, values) .then(res => { resetForm() setSuccess(true) }) .finally(() => setLoading(false)) } return ( <div> {success && "You will receive a verification email."} {loading && "Loading..."} <Formik initialValues={{ email: '', }} onSubmit={handleSubmit}> {({ errors, touched }) => ( <Form> <Field name="email"> … -
How to read a csv file and execute a batch prediction from each row of data using DJANGO
here is the content of my csv file, I want to calculate the prediction of each row from column CC102,CS111,MATH103 "ID No.","CC102","CS111","MATH103" "bg201802133","2","1.25","1" "bg201802356","3","1.50","2" and this is how I fetch my data from an html form to views.py to predict data: CC102 = request.POST['CC102'] CS111 = request.POST['CS111'] MATH103 = request.POST['MATH103'] prediction = model2.predict([[CC102,CS111,MATH103]]) studentID = request.POST['studentID'] -
How to output valid lat-long GeoJSON from WKB using django.gis.geos.GEOSGeomety?
I have a database that has geometry attributes in the WKB format: 010400000001000000010100000035553113AC38F64062B44D0A97951A41 I am using django.gis.geos GEOSGeometry in order to get the MultiPoint coordinates: goem = "010400000001000000010100000035553113AC38F64062B44D0A97951A41" x = GEOSGeometry(geom) print(x.json) //output { "type": "MultiPoint", "coordinates": [ [ 91018.754685719337431, 435557.760062044602819 ] ] } I also have a flyto map function that works with latitude and longitude but does not work with the format presented above: //working version latitude = 51.91648 longitude = 4.45246 map.flyTo([latitude, longitude], 11.5, { animate: false, duration: 0 // in seconds }); //not working version. How is possible to translate these 2 coordinates in latitude and longitude // coordinateA = 91018.754685719337431 // coordinateB = 435557.760062044602819 // // map.flyTo([coordinateA, coordinateB], 11.5, { // animate: false, // duration: 0 // in seconds // }); Is there any way to compute the latitude and longitude based on the coordinates that come out of GEOSGeometry? -
Hi, may you help me solve this, I tried to configure postgresql for my django project so I could build a search engine , it says authentication failed
command-line installation of postgresql -
Having problem with django makemigration model.py file(message after running django : can;t import the name self)
when i run the manage.py file this is the message i ge: (base) abu@lenovo:~/Desktop/paris_sportif$ python3 manage.py makemigrations ImportError: cannot import name 'self' from 'typing_extensions' (/home/abu/anaconda3/lib/python3.9/site-packages/typing_extensions.py) Here is my code -
Is there a Djangonic way to get Django objects from a list defaulting to all() if the list is empty?
For example something like MyModel.objects.filter(some_value___in=[1,2], ignore_null_some_value=True) would return MyModels with some_values 1 or 2, but MyModel.objects.filter(some_value__in=[], ignore_null_some_value=True) would return all instances of MyModel? My best effort so far is to do a second db query earlier to make sure the list is populated, e.g.: values = <list> or MyModel.objects.values_list('some_value', flat=True)) MyModel.objects.filter(some_value__in=values) But this feels inefficient. -
Django Celery django.db.utils.OperationalError
Hi I'm having a really strange problem with celery. I have a model like this class MyUser(models.model): email = models.CharField(max_length=255, unique=True, blank=False, null=False) ..... user_code = models.PositiveIntegerField(default=get_user_code, unique=True, blank=False, null=False) def get_random_num(): return random.randint(10000, 999999) def get_user_code(): # Check if some user with this code already exists code = get_random_num() while MyUser.objects.filter(user_code=code).exists(): code = get_random_num() return code So django is not complaining on this, but for some reason when I start celery I have errors like this: django.db.utils.OperationalError: could not receive data from server: Bad file descriptor Django schedule tasks will not run, other celery tasks run just fine (example: sending emails). So django is not complaining on this but Celery does. If I just remove this lines of code, celery is not showing any errors. while MyUser.objects.filter(user_code=code).exists(): code = get_random_num() Why is Celery complaining on this? Did someone already faced this issue? Is there some clean way to avoid this? -
How to send http request to a device with specific IP from Django view?
I have a device with ESP32, I need to send request with data to this device from Django API. For example, I have wifi parameters, I want to change it at api and send to this device. My wifi configuration view: class WiFiParametersView(APIView): permission_classes = [permissions.AllowAny] def post(self, request, charger_id): form = WiFiConfigForm(request.POST) if form.is_valid(): data = {"wifi_ssid": "wifi_name", "wifi_pass": "password"} // send to device id here, smth like send_request("https://ip_adreess:port", data) return Response("wifi parameters setting", status=status.HTTP_200_OK) def get(self, request, charger_id): form = WiFiConfigForm() return render(request, "wifi_config.html", context={'form': form}, status=status.HTTP_200_OK) -
How can I save a django Model Form in views for the logged in user
I am working on a project in Django where I have an Education(models.Model) with a OneToOneField to User Model as shown below: class Education(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) qualification = models.CharField(max_length=60, choices=INSTITUTE, blank=True, null=True) institution = models.CharField(max_length=40, null=True) reasons = models.CharField(max_length=100, null=True) matnumber = models.CharField(max_length=255, null=True) And a forms.ModelForm as shown below: class AddEducationForm(forms.ModelForm): class Meta: model = Education fields = ['qualification','instition', 'matnumber', 'reasons','refphone'] In my views.py file I want to save this AddEducationForm for the logged in user. Below is what I have tried but it is not saving but showing success message of save. def AddEducation(request): if request.method == 'POST': form = AddEducationForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, 'Education Added Successfully') return redirect('user-bank') else: form = AddEducationForm() context = { 'form':form, } return render(request, 'user/add_education.html', context) The system is displaying the success message that the form has been saved for the logged in user but in reality it is not (when checked using Django Admin Login). Someone should kindly help out with the solution to this problem. Remember each logged in user would save only one Education Form record. Thank in anticipation. -
How to import panel in python
I'm trying to import panel in a jupyter notebook in Hvplot but keep getting this error: ImportError: cannot import name 'url' from 'django.conf.urls' (/Users/***/opt/anaconda3/lib/python3.9/site-packages/django/conf/urls/__init__.py) Tried using techniques from StackOverflow but nothing works. What do I do? This is mycode before it breaks: import pandas as pd import numpy as np from django.urls import re_path as url import panel as pn *** it breaks here pn.extension('tabulator') import hvplot.pandas -
Can you access a parent field from a child object in Django?
tl;dr: I want to express something like [child.child_field_value, child.parent_field_value] on a Django child model and get an iterable like ['Alsatian', 'Dog'] or similar. Context: I'm trying to prepare a dict for a JSON API in Django, such that I have two models, Evaluation and its parent Charity. In the view I filter for all Evaluations meeting certain parameters, and then use a dict comp nexted in a list comp on evaluation.__dict__.items() to drop Django's '_state' field (this isn't the focus of this question, but please tell me if you know a better practice!): response = [{key:value for key, value in evaluation.__dict__.items() if key not in ['_state']} for evaluation in evaluations] But I want a good way to combine the fields charity_name and charity_abbreviation of each Evaluation's parent charity with the rest of that evaluation's fields. So far the best way I can find/think of is during the dict comp to conditionally check whether the field we're iterating through is charity_id and if so to look up that charity and return an array of the two fields. But I haven't figured out how to do that, and it seems likely to end up with something very messy which isn't isn't functionally … -
How to provide a dictionary with lists as values to Django Table2?
I would like to populate a Django Table 2 with a dictionary like this, how can I do that ? This is my code but the table has no data. views.py class MyDetailView(SingleTableMixin, generic.DetailView): model = MyModel def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dic = {'col_1': [-6.9, -7.1, -3.8], 'col_2': [-1.9, -7.9, -0.8], 'col_3': ['2022-05-03T05:00:00Z', '2022-05-03T06:00:00Z', '2022-05-03T07:00:00Z']} table_2 = MyTable(dic) context['table_2'] = table_2 return context tables.py class MyTable(tables.Table): col_1 = tables.Column() col_2 = tables.Column() col_3 = tables.Column() -
Module Not found error while accessing api package in Django
PyEnv |--Aqi |--Django |--Django_1 |--Django_Rest |--api |--Django_rest |--manage.py Error occurs in Urls.py of main django project when it tries to access the url of the api package. api is not registered as an app.How should I include the url of api here? urlpatterns = [ path('admin/', admin.site.urls), path('', include(api.urls)), ] File "/home/pradeep/Backend/PyEnv/Django/Django_Rest/Django_Rest/urls.py", line 20, in <module> from PyEnv.Django.Django_Rest import api ModuleNotFoundError: No module named 'PyEnv -
Python Django Multiple Database for User Groups
Is it possible to use different databases for different user groups ? For example, user group 'X' uses 'A' database and user group 'Y' uses 'B' database in the same app ? All the best, Semih -
Django - LogoutView - cache_control - browser's back button has the logged out user's cache
Django 2.1.7 This is for a simple blog with homepage (post list view), post detail view, and profile (post list view) When a user logs out, LOGOUT_REDIRECT_URL = '/' redirects the user to the homepage. However, when the user clicks the browser's back button, the previous page still shows all the logged out user's data. When I reload the page, it clears the cache. when the user's logged in, shows username] when the user's logged out, shows 'login' I found a similar question and their answer was to use the cache_control decorator. Django - User re-entering session by clicking browser back button after logging out @cache_control(no_cache=True, must_revalidate=True, no_store=True) @login_required Would I have to add these decorators to every single view? I do not want the @login_required decorator. AnonymousUsers should be able to view all pages without logging in. What's the best way to do this? Similar to Twitter's logout flow. (user logs out -> login page -> back button -> previous page but reloaded) urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), -
Integrating Razorpay Payment Gateway with Django causing CSRF verification failure
This question was previously asked here but I didn't have 50 reputation points to continue the discussion on that answer itself. Short version Essentially, the problem boils down to - I have an external URL that sends POST data to my Django application. I want to access this POST data but Django is giving 403 error (CSRF Token missing). Detailed version I am trying to add Hosted Payment Gateway of Razorpay to my Django Project. I have passed the URL to the following function in the callback functionality. As specified in the previous answer, I tried using the csrf_exempt decorator and adding the https://api.razorpay.com URL as CSRF_TRUSTED_DOMAINS in the settings.py file, but the issue still remains. I am still getting the 403 error from Django when the payment is successful. @csrf_exempt def course_purchase_callback(request): payment_id = request.POST.get("razorpay_payment_id") order_id = request.POST.get("razorpay_order_id") signature = request.POST.get("razorpay_signature") client = razorpay.Client(auth=(os.getenv("RZP_ID"), os.getenv("RZP_SECRET"))) verify = client.utility.verify_payment_signature({ "razorpay_payment_id": payment_id, "razorpay_order_id": order_id, "razorpay_signature": signature, }) settings.py file .. .. .. CSRF_TRUSTED_ORIGINS = ["https://api.razorpay.com"] .. .. Versions being used: Django = 4.0.3 Razorpay API = 1.3.0 What is the thing I am missing here?