Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'app.user' cannot be resolved
I am running into an issue that's bizarre, I have tried to fix it but have failed, the error you there is caused by whenever I import and user this from django.contrib.auth import get_user_model commands like python manage.py migrate, python manage.py check, python manage.py runserver all run well and show no error, but when i tried to run this test, or any other test that summons "get_user_model" error will come from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): """ Tests models. """ def test_create_user_with_email_successful(self): """ Test creating a user with email is successful. """ email = "test@example.com" telephone = "1234567890" username = "testuser" first_name = "test" last_name = "user" password = "testpass123" user = get_user_model().objects.create_user( email=email, telephone =telephone, username = username, first_name = first_name, last_name = last_name, password=password, ) self.assertEqual(user.email, email) self.assertEqual(user.telephone, telephone) self.assertEqual(user.username, username) self.assertEqual(user.first_name, first_name) self.assertEqual(user.last_name, last_name) self.assertTrue(user.check_password(password)) that test will cause problem since it calls "get_user_model" take look at my user model here from django.db import models from django.contrib.auth.models import( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.conf import settings class UserManager(BaseUserManager): """ minimum fields for all users""" def create_user( self, email, telephone, username, first_name, last_name, password=None, **extra_fields): if not email: raise ValueError('You need to provide an … -
Does Django open and close connection to cache every time I call cache.delete(key)?
Consider the following code snippet: from django.core.cache import cache cache.delete('key_1') cache.delete('key_2') If i'm using an Instance of Redis as my default cache, will Django create two seperate connections to the Redis instance, for each call to .delete()? or will it keep a single connection open to fulfil both calls to .delete()? I have a circumstance where I may need to delete a lot of individual keys in one go. Ideally I would like a single connection to the Redis cache to persist, rather than take on the latency of creating a new connection each time a cache method is called. Thanks -
from where did the self.request come from?
Lately I was learning Django and Django rest framework from the official docs and i stumbled upon a method defined inside the GenericAPIView named get_queryset. Till now everything is fine but i was lost when he override this latter the code is as follow: def get_queryset(self): user = self.request.user return user.accounts.all() My question is simple, the request is not defined in the method's argument so where did it come from? -
I am new to django and testing and I'm trying to test a registration and login view
The view has IsAdminUser restriction. I am also using token authentication. This is the tests code: class TestSetUp(APITestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user_manager = UserManager() def setUp(self): self.register_url = reverse("user_urls:register") self.register_user_data = { "name": "TestUser", "email": "test_user@email.com", "number": "1213", "password": "Test@123", } self.login_url = reverse("user_urls:login") self.login_user_data = { "name": "TestUser", "password": "Test@123", } self.register_user_data_with_empty_password = { "name": "TestUser", "email": "test_user@email.com", "number": "1213", "password": "", } return super().setUp() def create_staff(self): self.user = self.user_manager.create_staff(**self.register_user_data) try: self.token = Token.objects.get(user=self.user) except Token.DoesNotExist: self.token = Token.objects.create(user=self.user) def create_superuser(self): self.user = self.user_manager.create_superuser(**self.register_user_data) try: self.token = Token.objects.get(user=self.user) except Token.DoesNotExist: self.token = Token.objects.create(user=self.user) class TestViews(TestSetUp): def test_register_with_no_data(self) -> None: res = self.client.post(self.register_url) self.assertEqual(res.status_code, 401) def test_register_with_data(self) -> None: User.objects.create_staff(**self.register_user_data) res = self.client.post(self.register_url) self.assertEqual(res.status_code, 201) def test_user_cannot_login_with_invalid_credentials(self): self.client.post(self.register_url,self.register_user_data, format='json') res = self.client.post( self.login_url, self.login_user_data, format="json") self.assertEqual(res.status_code, 401) def test_user_can_login_with_valid_credentials(self): res = self.client.post( self.register_url, self.login_user_data, format='json' ) if res.status_code != 201: raise ValueError(f"Registration failed with error: {res.data}") name = res.data["name"] password = res.data["password"] user = User.objects.get(name=name, password=password) user.is_verified = True user.save() response = self.client.post( self.login_url, self.login_user_data, format="json") self.assertEqual(response.status_code, 201) Every time I run coverage I get a 401 Error with the message ValueError: Registration failed with error: {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} I haven't tried much because I … -
Problems with custom footer in catalogue pages in geonode-project
I edited the footer.html template, in my geonode-project in order to set a custom footer, but since that footer has many elements, it does not give enough space for the dataset's result list (and other catalogue pages). The footer seems to be fixed to the bottom. How can I fix that in order to give more space to the resulsts list There is my code I edited the footer.html template in order to set a custom footer, but since that footer has many elements, it does not give enough space for the dataset's result list (and other catalogue pages). The footer seems to be fixed to the bottom. How can I fix that in order to give more space to the resulsts list There is my code <footer> <div style="display: grid; grid-template-columns: 1fr; grid-template-rows: 2fr 1fr; height:20rem; padding: 1%; background: #033E84;"> <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows:1fr;"> <div style="display: flex; justify-content: center; align-items: center;"> <div style="display: flex; flex-direction: column; color: #fff"> <span style="text-align: center; border-bottom: solid 1px; margin: 0 0 6px 0px; font-weight: 600;">Otros enlaces de interés</span> <span><a style="color: #fff;" href="https://consultacf.ineter.gob.ni/">Consulta catastro</a></span> <span><a style="color: #fff;" href="https://tramites.ineter.gob.ni/">Tramites en línea INETER</a></span> <span><a style="color: #fff;" href="https://www.ineter.gob.ni/">INETER</a></span> </div> </div> <div style="display: flex; … -
How to redirect to specific url after logging in, with geonode-project?
In geonode when an user logs in, it is automatically redirected to the Profile page. I am trying to change that and redirect to the Home (index page). In order to to that I added the following line to the settings.py" in my geonode-project folder. But the user is still redirected to the Profile page when he/she performs the authentication ACCOUNT_LOGIN_REDIRECT_URL = "/" I also tried with the following line: LOGIN_REDIRECT_URL = "/" Am I doing something wrong? According to the geonode documentation (https://docs.geonode.org/en/master/basic/settings/index.html) the ACCOUNT_LOGIN_REDIRECT_URL "allows specifying the default redirect URL after a successful login.", so why is not working? -
Django - public class?
My Django project conventionally relied on functions, where many of them would retrieve the same variables/data from the database/request data. Although this works fine, it's inefficient due to the repeared code in every view function. So, I started looking at classes instead, and it seems to be the better solution for creating objects with certain reusable data. To make the data "Public", I'm storing the class object in a Public variable when returning the request data on page load, then calling that variable on subsequent calls. Although this works, it doesn't feel like a best practice. What's the best practice to make the class "Public" so that subsequent Ajax/JS calls/requests can call the same object without recreating it (unless the page changes)? Further, how could I then create multiple instances of the class in case of multiple concurrent pages calling the same view? -
How to get label of checked inupt in css
How can I change the background-color of the label from a checked radio button. Django renders form radio inputs like this: <label for="id_form-level_0"> <input type="radio" name="form-level" value="1" required="" id="id_form-level_0"> description </label> I dont have the intention to change this, so the most commun solution input[type="radio"]:checked + label { background-color: red; } does not work. In addition the :has() selector seems not to be supported in the browsers, meaning the following code neither works. label:has(input[type="radio"]:checked) { background-color: red; } What is the correct way to adress the right label in css? -
Use __str__ children classes methods when calling parent class
I've some classes like these : class Event(models.Model): beginning = models.fields.DateTimeField(null=False, blank=True, default=date.today) end = models.fields.DateTimeField(null=False, blank=True, default=date.today) class Festival(models.Model): name = models.fields.CharField(max_length=100, blank=True) def __str__(self) -> str: return f"{self.name}" class FestivalEdition(Event): type = "festival_edition" father_festival = models.ForeignKey(Festival, default="", on_delete=models.CASCADE, related_name="edition") def __str__(self) -> str: return f"{self.festival_name} {self.year}" As you can see, only the children classes have their __str__ methods. When I use Event (by the admin interface or by shell), the name is like this <Event: Event object (1)>. How can I use the __str__ methods of the children (and children of children) classes when calling the parent class ? I've read the official documentation of Django about inheritance and this post. I tried this : class Event(models.Model): objects2 = InheritanceManager() # The __str__ of Event call the __str__ of children models def __str__(self) -> str: event_name = Event.objects2.filter(pk=self.pk).select_subclasses()[0].__str__() return f"{event_name}" It works well but only with the children but not the children of the children because I get this recursion Error in this case : RecursionError: maximum recursion depth exceeded while calling a Python object. -
Method Not Allowed (POST) in django
I use axious for requests But I get this error POST http://127.0.0.1:8000/dashbaord/Menu/editStatus 405 (Method Not Allowed) What should I do to solve this problem? myscript.js: let changeStatus = (id, place) => { axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios({ method: 'post', url: 'editStatus', data: { 'tes1': 'test', 'tes2': 'test' }, headers: { "content-type": "application/json" } }).then(function (response) { console.log('dsdsdsd') }).catch(function (error) { console.log(error) }); } urls.py path('editStatus', EditMenuItemStatus.as_view(), name="edit_status_item") views.py class EditMenuItemStatus(BaseDetailView): def post(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) -
Datables.net resize column manually resizable colimd
I know this is not a builtin but I have been searching so long for a solution. If anyone knows that would be really great!!! I HAVE TRIED A LOT of solutions but none fit the reorder and other builtins functions... -
WSGI Django Apache, AH01630: client denied by server configuration
I've seen very very similar issues but i don't see how the fixes are relevant to my issue. I have a django server running and working fine, I've setup apache for it to run there with the config file as: Alias /static /home/dev/pidjango/gamificationECM2434/mysite/static <Directory /home/dev/pidjango/gamificationECM2434/mysite/static> Require all granted </Directory> <Directory /home/dev/pidjango/gamificationECM2434/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django python-path=/home/dev/pidjango/gamificationECM2434/mysite python-home=/home/dev/pidjango/djenv WSGIProcessGroup exSeed WSGIScriptAlias / /home/dev/pidjango/gamificationECM2434/mysite/mysite Any help to figure out the issue would be great thank you :) -
Session or Token auth for Backend and two Frontend apps at different locations
I have a Django App which acts backend and some endpoint built with Django REST Framework. There are 2 pieces of frontend interacting with my Django app. I have not implemented auth/login to my app. But before i do that, i have few questions to ask. Below is a picture of the system. Both React_user is a React app BUT React_admin is a low-code app like Retool (drag & drop components to make UI connected via REST API to backend) which is sitting at differnt servers i.e physically seperated at differnt locations React_user is the app for customer where they should be able to login with username and password created by React_admin React_admin is the on who creates customers, create username, password for each customer. Think of this as walk-in account creation as there is no sign-up for customers. So, React_admin creates customer credentials from the React app managed by admin, again is sitting at differnt server. For simplicity, let's say React_admin is hosted at the office itself. To create users, i'm using basic django Users model comes out of the box.So, to create a user, there is a an endpoint made with Django REST Framwork. The endpoint is https://mapp.com/rest/create_user … -
Django Plotting Separate Models By Date Month In Highcharts
I have two models that I'm trying to plot counts of each by month on a single chart in Highcharts class Foo(models.Model): foo_user = models.ForeignKey(User, on_delete=models.CASCADE) foo_title = models.CharField(max_length=200) foo_date = models.DateTimeField() class Bar(models.Model): bar_user = models.ForeignKey(User, on_delete=models.CASCADE) bar_title = models.CharField(max_length=200) bar_date = models.DateTimeField() I get the data, combine the querysets, and sort by month foo_data = Foo.objects.annotate(month=TruncMonth('foo_date')).values('month').annotate(foo=Count('id')).order_by('-month') bar_data = Bar.objects.annotate(month=TruncMonth('bar_date')).values('month').annotate(bar=Count('id')).order_by('-month') data = chain(foo_data, bar_data) ordered_data = sorted(data, key=lambda obj: obj['month'], reverse=True) At this point I'm lost and feel like my whole approach is most likely all wrong, but I can't figure out what to do - I add the data to lists and send to the Highchart plot like so. I've gotten it to work if both Foo and Bar both have items in each month, but as soon as one one has an object in a month where the other doesn't the whole thing is throw off. chart_labels = [] foo_chart_data = [] bar_chart_data = [] for row in ordered_data: if row['month'] not in chart_labels: chart_labels.append((row['month']).strftime("%B %Y")) if 'foo' in row: foo_chart_data.append(row['foo']) else: pass if 'bar' in row: bar_chart_data.append(row['bar']) else: pass This is Highchart setup Highcharts.chart(chartContainer, { chart: {type: 'column'}, title: {text: 'Foos & Bars Created'}, xAxis: {categories: … -
Django Pass tag dynamic to div class
I have a progress bar in a table similar to this: I can pass the value "2" for the percentage, but I cannot pass the value 2 to the aria-valuenow class that sets how fill is shown the progress bar. How could I pass the dynamic value to aria-valuenow so the progress bar shows the right filling? I tried {{value.3}},"{{value.3}}", the same with only one {} and with/without % %. I really run out of imagination. {% for key,value in ctxt.items %} <tr><td>{{value.0}}</td><td>{{value.1}}</td><td> {% if value.3 %} <div class="progress align-content-center position-relative" style="height: 25px;"> <div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow= "{% value.3 %}" aria-valuemin="0" aria-valuemax="100"></div> <small class="justify-content-center d-flex position-absolute w-100">{{value.3}}%</small> </div> {% endif %} </td></tr> {% endfor %} *Another battle is to put the "2%" vertically centered and not in the top with the position-absolute commands. If you know this, really appreciated too! -
end points for calendar as PDF in Django REST Framework
Anyone know how to make an end points request(backend) creating a school calendar as a PDF in Django REST Framework? I don't know what to do when comes to generate a PDF. -
django ModelForm validation failing with newly created objects
I have a django ModelForm called AdditionalDealSetupForm with the following code: class AdditionalDealSetupForm(ModelForm): required_css_class = "required" lead_underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), label="Lead Underwriter(s):", required=False, widget=forms.SelectMultiple( attrs={"class": "lead_underwriter kds-form-control"} ), ) underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), required=False, label="Underwriter(s):", widget=forms.SelectMultiple(attrs={"class": "underwriter kds-form-control"}) ) def clean(self): pass def clean_underwriters(self): pass print(self.data.items()) class Meta: model = AdditionalDeal fields = [ "lead_underwriters", "underwriters", ] """ Labels for the fields we didn't override """ labels = {} I want to be able to create new underwriters and lead underwriters, which are both many to many fields linked to the Underwriters Model: class AdditionalDeal(TimestampedSafeDeleteModel): id: PrimaryKeyIDType = models.AutoField(primary_key=True) ModIsDealPrivateChoices = [ ("Y", "Yes"), ("N", "No"), ] # Relations deal_setup: ForeignKeyType[t.Optional["DealSetup"]] = models.ForeignKey( "DealSetup", on_delete=models.SET_NULL, null=True, blank=True, related_name="additional_deal_set", ) if t.TYPE_CHECKING: deal_setup_id: ForeignKeyIDType lead_underwriters = models.ManyToManyField( Underwriters, related_name="DealLeadUnderwriter", validators=[validate_underwriters], ) underwriters = models.ManyToManyField( Underwriters, related_name="DealUnderwriter" ) class Meta: db_table = "Additional_Deal" verbose_name_plural = "Additional Deal" unique_together = ("deal_setup",) The problem is that when the form gets instantiated its failing validation implicitly being called by django. The values that are being passed in the request object’s QueryDict look like this: request.POST: <QueryDict: {'csrfmiddlewaretoken': ['lU65eYaubaCgpTtRFQIou9yM9LdmbRt8GAD1XMowV2PdRhxfVRQAXIjRzozCNKqn'], 'cutoff_date': ['08/01/1900'], 'closing_date': ['08/15/1988'], 'deal_private': ['Y'], 'lead_underwriters': ['2'], 'underwriters': ['1', '2', 'test4']}> You can see above that … -
What is the alternative for this.props.match.params for class based views in react
import React, { Component } from 'react' import {render} from "react-dom" import { withRouter } from 'react-router-dom'; import { useParams } from 'react-router-dom' export default class Items extends Component { constructor(props){ super(props); this.state = { price:0, name: "", description: '', } const { id } = useParams(); this.getProductDetails(); } getProductDetails(){ fetch('/api/get-product' + '?id=' + id).then((response) => response.json()).then((data) => { this.setState({ price: data.price, name: data.name, }) }); } render() { return ( <div><h1>This is the Id{id}</h1></div> ) } } I tried using this.props.match.params but my page didnt render, I've used useParams() and it still doesnt work. I need to get the id from the browser and fetch information from my api is there any solution for this? -
instantiate objects and calling methods from a different class when constructing an object
This is my Django Reconciliation class from mytransactions app (below). Every time I do a Reconciliation, I also want to create a log object from a class called TransactionLog (see below) and call a method check_if_needs_consolidation() from a another app (mymoney) and class (Balance). How can I do it? Reconciliation Class, mytransactions app (models.py): class Reconciliation(models.Model): notes = models.CharField(max_length=50) account = models.ForeignKey('mymoney.Account', on_delete=models.CASCADE,) date = models.DateField(default=timezone.now) amount = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.notes TransactionLog (mytransactions app, models.py) class TransactionLog(models.Model): label = models.ForeignKey(Label, on_delete=models.CASCADE, blank=True, null=True) amount = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField(default=timezone.now, null=False) notes = models.CharField(max_length=300, blank=True) account = models.ForeignKey('mymoney.Account', on_delete=models.CASCADE) beneficiary = models.ForeignKey('mybeneficiaries.Beneficiary', on_delete=models.CASCADE) is_cleared = models.BooleanField("Cleared") def __str__(self): return str(self.beneficiary) Balance class from mymoney app, and the check_if_needs_consolidation() method I want to call: class Balance(models.Model): date = models.DateField(auto_now_add=True) account = models.ForeignKey('mymoney.account', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=15,decimal_places=2) #def check_if_needs_consolidation(month): -
How to know if the user completed login or not and close the server in youtube api and python
I want to make a web app using django and I want to make sure that the user completed login into his youtube account or not because the user may click on the button to go to the page where he can log into his account using this code flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='', timeout_seconds=40 ) and he may don't complete login process when I added timeout secondes argument it works but if the user took more than 40 seconds it raises AttributeError : 'NoneType' object has no attribute 'replace' and if the user clicks on the button to go to the page where he can log into his youtube account and He backs to the previus page and clicked on the button again it raisesOSError at /channels/ : [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted So what basicly I want to do is two things first : I want to show a success message if the user successfully logged into his account and I can make the message itself but I need a help for "when I will add it" second : I want to solve the second problem OSError at /channels/ so what … -
Add argument to Django imageField to change location
questions: I have an image_upload_handler function for my imageField's in my model. This function takes two arguments as explained on the documentation. Can I add another argument to this? I would like to use this function for multiple fields but want to change the location for the images depending on the argument. So like this: def image_upload_handler(location, instance, filename): fpath = pathlib.Path(filename) new_fname = str(uuid.uuid1()) return f"{location}/{new_fname}{fpath.suffix}" is this possible? -
Having trouble with the authentication process of logging in Facebook from my Django project
I am new to Django and I wanted to build a Django application that could allow users to log in using Facebook, so I have followed every step listed in this tutorial https://www.digitalocean.com/community/tutorials/django-authentication-with-facebook-instagram-and-linkedin Despite following the same step, I still getting errors after providing my password and click on the continue button. Here are two errors that I've encountered: URL blocked This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs. The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings. My configuration for the app in Facebook developers valid OAuth Redirect URIs: https://127.0.0.1:8000/ app domains: localhost site url: https://localhost:8000/ I tried to search for cues everywhere but found nothing in the end. Is there anyone faced this kind of issue before? How can I make it work? Urgently need help with this 🙏🙏🙏 -
Displaying images blobs on Django html templates using SaS token
I'm currently trying to get blob images to be displayed in the html of django templates using Sas but I don't see any online implementation examples. I have currently the SaS token but I don't know how to implement it to Django. I tried to manualy add the token to the end of the url: https://{account}.blob.core.windows.net/{container}/{path}.jpg/?sp=r&st=2023-03-11T17:53:36Z&se=2050-03-12T01:53:36Z&sv=2021-12-02&sr=c&sig={****} -
Is there a way to extend django's handling of bulk data that is returned from the DB?
I have implemented a custom field with a from_db_value() method and get_db_prep_value() method. These effectively act as a layer between the caller and the data in the database, and it works well. I used it to implement a lookup the data in a secondary store. The problem is that for bulk data (e.g. list(MyModel.objects.all())), my function from_db_value() will get called O(n) times, which means that if it does something costly (e.g. my use case of lookup in a secondary store) it's really inefficient. What is the best way to "capture" bulk calls and do the conversion in one go? -
Making pagination work with multiple tables in Django
I have a html page in which you can change the table displayed based on the value of a select box. The pagination does not seem to work as intended. When the page is initially loaded the pagination works fine however when changing the the table and trying to go to the next page it loads the second page of the default table. Here are the relevant parts in the template: <h1 id="tableHeader">Users</h1> <div id="template"> {% include user_table %} </div> <select class="form-select" name="view_select" id="view_select" onchange="loadTable()"> <option value="1" selected>Users</option> <option value="2">Categories</option> </select> The JavaScript function loadTable: function loadTable() { var select_value = document.getElementById("view_select").value; if (select_value == 1) { var url = "{% url 'user_table' %}"; } else if (select_value == 2) { var url = "{% url 'category_table' %}"; } else { return; } $.ajax({ url: url, type: "GET", success: function(response) { $("#template").html(response); } }); } The url.py file: path('user_table/', views.user_table, name='user_table'), path('category_table/', views.category_table, name='category_table'), The relevant views: def admin_dashboard(request): if (request.user.is_staff == False) and (request.user.is_superuser == False): return redirect('landing_page') else: if request.method == 'POST': # IF CREATE USER BUTTON CLICKED if 'create_user' in request.POST: form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() return redirect('admin_dashboard') # IF CREATE CATEGORY BUTTON CLICKED …