Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: get_or_create()[0] raises a multiple-return error
I thought I understood that get_or_create() returns a tuple, therefore assigning [0] at the end should pick the first object in the query result. However, it raises an error like the following: MultipleObjectsReturned at /admin/hr/clientcontact/add/ get() returned more than one ClientDepartment -- it returned 4! (I do have 4 objects in the ClientDepartment model.) Below is the code for ClientContact model where I used get_or_create()[0]. class ClientContact(Person): def get_default_client_department(): return ClientDepartment.objects.get_or_create()[0].id department = models.ForeignKey( 'ClientDepartment', on_delete=models.RESTRICT, default=get_default_client_department, ) def company(self): return self.department.company I would appreciate any help and the explanation. Thank you. -
Django forms stop form processing on ValidationError
I'm designing a Django form with recaptcha and custom cleaning method for address field. I want to stop form processing on first ValidationError in other words I don't want to execute clean_address method if recaptcha is bad. For recaptcha I using django-recaptcha. My form: from django import forms from captcha.fields import ReCaptchaField from .models import Server, Category from .utils.status_manager import ServerStatus class AddServerForm(forms.ModelForm): captcha = ReCaptchaField() categories = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'checkbox'}), error_messages={ 'required': 'You need to select server type' }, choices=[(c.pk, c.name) for c in Category.objects.all()] ) def clean_address(self): address = self.cleaned_data['address'] server = Server.objects.filter(address=address).exists() if server: raise forms.ValidationError("Server is on the list") if not ServerStatus(address).is_server_on(): raise forms.ValidationError("Server is offline") return address class Meta: model = Server fields = ['address'] View: class AddServer(LoginRequiredMixin, FormView): template_name = 'add_server.html' login_url = '/users/discord/login' form_class = AddServerForm def form_invalid(self, form): errors = get_form_errors(form) for error in errors: messages.add_message(self.request, messages.ERROR, error) return super(AddServer, self).form_invalid(form) def form_valid(self, form): server = form.save() self.success_url = f'/servers/{server.id}' return super(AddServer, self).form_valid(form) For now on ValidationError or if recaptcha is bad form still processes. -
Django DRF - Patch request object in viewset?
We are using oauth2 and perform force_login() in our tests simulate authentication. However in our modelviewset, we now want to override create() to check for some specific authorization (in the requests object eg request.auth['MYROLES']) permissions we would get in our access tokens. I cannot work out how I can patch the request object to have the expected attribute to ensure our test can work without failing due to missing object attributes. Any ideas? -
how to fetch two models at the same time in django
i want to fetch two model in same html but unable to get both only getting one i am using class based view in django here is my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() print(category_list) return render (request, 'home.html', {'category_list': category_list }) def get (self, request): subcategory_list = Subcategories.objects.all() return render (request, 'home.html', {'subcategory_list': subcategory_list}) i guess i cannot call get function two time in cbv i have to make both of the model in same function help will be appreciated thank you -
Are there alternative methods to using hashrouter to make page urls work? (Django Backend + React Frontend)
I am using a React JS frontend and Django Backend, and I was wondering if there are any solutions, other than hashrouter, when using urls with BrowserRouter, once I npm run build the frontend code. I've heard that using hashrouter has a negative impact on the SEO of the website. E.g. I want urls to be http://localhost:8000/products instead of http://localhost:8000/#/products (HashRouter). Any help would be much appreciated. Thanks -
Django - unable to create build API
Well, I'm trying to get to 'http:// 127.0.0.1:8000/api/files/", but getting a mistake, that: Using the URLconf defined in WTF_2.urls, Django tried these URL patterns, in this order: admin/ graphql/ Start/ The current path, api/file/, didn’t match any of these. I understand what is this about, but can't really find where I did the mistake. My 'File' model from 'Start/models.py: class File(models.Model): class Meta: ordering = ['-publish_date'] title = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) ... ... My 'urls.py' from 'Start/urls.py': from django.urls import path from .views import FileView app_name = 'Start' urlpatterns = [ path('Start/', FileView.as_view()), ] And my 'urls.py' from 'mainproject/urls.py': from django.contrib import admin from django.urls import path, include from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), # graphiql = true указывает графену сделать доступным graphiql интерфейс path('graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))), # api интерфейс path('Start/', include('Start.urls')) ] -
How can I get Posts related to the user in Django?
class ShowProfilePageView(DetailView): model=User template_name="users/profile.html" paginate_by = 5 def get_context_data(self, *args, **kwargs): users=User.objects.all() nested_posts = {} context = super(ShowProfilePageView,self).get_context_data(*args, **kwargs) page_user = get_object_or_404(User, id=self.kwargs['pk']) context['page_user'] = page_user return context I am able to get the id but not the posts related to that id. what i am able to retrieve is the user's name, profile description, and profile image. -
OpenCV read image from Reactjs base64
Hello i'm currently working with react js for frontend and django for backend to do some image processing. But i'm struggling with upload an image from base64 react js to opencv python. This is my code in React.js to upload image and convert it to base64 handleImageSubmit = async (e) => { e.preventDefault() let image = await this.convertBase64(this.state.imageSrc) console.log(image) axios.post("/image/", { image }).then((res) => { // this.setState({ imageDst: res.data }) console.log(res.data.data) }).catch((err) => console.log(err)); } convertBase64 = (file) => { return new Promise((resolve, reject) => { const fileReader = new FileReader() fileReader.readAsDataURL(file) fileReader.onload = () => { resolve(fileReader.result) } fileReader.onerror = (error) => { reject(error) } }) } And this is my code in django views : @api_view(['GET', 'POST']) def image(request): sbuf = StringIO() sbuf.write(base64.b64decode(request.data['image'])) pimg = Image.open(sbuf) img_array = np.array(pimg) cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR) print(img_array) return JsonResponse({"data": "data"}) When i'm decode base64 image there is an error like this Invalid base64-encoded string: number of data characters (184641) cannot be 1 more than a multiple of 4 How to upload an image, process the image to opencv python and give the image back to the react (frontend)? Thank you! -
How to insert an ad in between paragraphs on Django site?
I would like to place ads randomly in between paragraphs on the blog post page. I want to do it dynamically as I can't insert an ad when creating a post. The blog post content was saved in Django Text or HTML field. For example, this is a paragraph {{ here is an ad }} this is another paragraph please give me a solution. -
Can get cleaned_data when customyzing LoginView in django
Beginner with Django 3.2. I'm trying to add a Recaptcha V3 from Google on my login screen. I'am using django-recaptcha3 well configured The logo is showing on my login page When debugging the json response when calling ReCaptchaField.clean is OK ! The problem is that the form is not validated "'CustomAuthenticationForm' object has no attribute 'cleaned_data'" Here is my code : In urls.py from django.urls import path from .views import CustomLoginView urlpatterns = [ path('login', CustomLoginView.as_view(), name='login'), ] In Forms.py from django.contrib.auth.forms import AuthenticationForm from snowpenguin.django.recaptcha3.fields import ReCaptchaField class CustomAuthenticationForm(AuthenticationForm): captcha = ReCaptchaField() In Views.py from django.contrib.auth.views import LoginView from django.views import generic from django.contrib.auth.forms import AuthenticationForm from .forms import CustomAuthenticationForm class CustomLoginView(LoginView): def post(self, request, *args, **kwargs): if request.method == "POST": form = CustomAuthenticationForm(request.POST) if form.is_valid(): captcha_score = form.cleaned_data['captcha'].get('score') print("SCORE" + str(captcha_score)) return super().post(self, request, *args, **kwargs) form_class = CustomAuthenticationForm template_name = 'accounts/login.html' request.POST gives <QueryDict: {'csrfmiddlewaretoken': ['TGoQaJTZACp4MbwB3iGVVdL4IHbqWDQaIhE1ldb9M8fkpjSRDHV7l1A1tTb62f3B'], 'g-recaptcha-response': ['03AGdBq270w7Z23MTavtAHLAUNSY9IWKuVpFZe0eueIiXimW6BvhTeWKANQQIFj43m903GA-cUA-dXZm7I6br.......5Z9vdM6RY9v-Kk1ZLX1uwH5nSoc7ksWUQuA00w0T8'], 'username': ['remi@XXXXXe.fr'], 'password': ['vXXXXX']}> which is normal. form.is_valid() is failing and I suspect form = CustomAuthenticationForm(request.POST) to be the problem but I don't know how to do. Thanks a lot for your help, -
Hosts file working for custom subdomains but not custom domains
I am developing a multi tenant app and need to modify my etc/hosts file to test the different URLs tenants might use. Some will use a sub domain like tenant1.mysite.com and others will use entirely their own URL like tenant2.com (to mask the fact it's a whitelabel site and pretend its their own). In my hosts file I have: 127.0.0.1 mytenantsdomain.com 127.0.0.1 localhost 127.0.0.1 thor.localhost 127.0.0.1 potter.localhost 127.0.0.1 testtenant.com localhost, thor.localhost, potter.localhost all work as expected when adding :8000 to them. i.e. they connect to the local development server and show expected tenant-specific content. But, mytenantsdomain.com and testtenant.com both give ERR_CONNECTION_REFUSED - I'm guessing its for the lack of the port :8000 tbh. I have tried a few fixes like flushing the cache with the below but nothing has worked. sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder Anybody know what else I can try to get them all working? -
{% if user.is_authenticated %} for specific user only
i am using : {% if user.is_authenticated %} to check if people are logged in, so i can set the navbar links depending on logged in or not. I want to make navbar links special for admin user. So there has to be a check not just if het user is authenticated, but also if that authenticated user is Admin. I was thinking about something like {% if user(Admin).is_authenticated %) but that didn't work. Somebody got an idea? -
Django corruption when the server is reloaded
The Django server listens on files and tries to restart itself. But, every time, it fails by returning this error in the console : double free or corruption (out) Abandon (core dumped) When the only scripts modified are written in HTML, CSS and JS, this error doesn't appear, so it seems to come from the server. This error appeared when my application becomes more and more advanced. As the error message returned is not very explicit (no file name, no line number), I can't know which part of my application I could publish on StackOverFlow. -
I try to install spacy in django
when i try to install spaCy in django in cmd it give me this error enter image description here enter image description here enter image description here -
Writing correct views to display restaurant food menus
I am creating a webapp for a new restaurant and want to display the different food menus for people to view and owner to be able to update and delete items from the menu when appropriate. I have a model for the menus and the items on the menu """ A Menu represents a collection of categories of food items. For example, a restaurant may have a Lunch menu, and a Dinner menu. """ class Menu(models.Model): name = models.CharField(max_length=246, unique=True,) slug = models.SlugField(max_length=24, unique=True, help_text='The slug is the URL friendly version of the menu name, so that this can be accessed at a URL like mysite.com/menus/dinner/.') additional_text = models.CharField(max_length=128, null=True, blank=True, help_text='Any additional text that the menu might need, i.e. Served between 11:00am and 4:00pm.') order = models.PositiveSmallIntegerField(default=0, help_text='The order of the menu determines where this menu appears alongside other menus.') class Meta: verbose_name = 'menu name' def __str__(self): return self.name """ A Menu Category represents a grouping of items within a specific Menu. An example of a Menu Category would be Appetizers, or Pasta. """ class MenuCategory(models.Model): menu = models.ForeignKey(Menu, null=True, help_text='The menus that this category belongs to, i.e. \'Lunch\'.', on_delete=models.SET_NULL) name = models.CharField(max_length=32, verbose_name='menu category name') additional_text = … -
django-filters: Preclean filterset field
I have django model and django-filters FilterSet: class MyModel(models.Model): name = models.CharField() class MyFilterSet(FilterSet): name = filters.CharFilter(lookup_expr='icontains', min_length=3) class Meta: model = MyModel fields = 'name', In name can be passed bad symbols such as [-()\"#/@;:<>{}`+=~|.!?,]. I need to remove them from name before validators are being ran. How can preclean name field in filterset class? -
Deployed Django project does not load static files
I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load. Here is the relevant part of the settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") #STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "static"), #] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' LOGOUT_URL = 'logout' AUTH_USER_MODEL = 'account.CustomUser' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') The error message I get is the following in the console: "GET /static/images/logo.png HTTP/1.1" 404 1808 However, when checking the file path in the console I have the following: root@melius:/django/melius/static/images# In this folder the files are present. Where is my mistake? -
How do I check if there are items in the database Django
Disclaimer, I've just started with Django a couple of days ago so I'm still quite new to it, patiance please. Alright so I have two different models in my models file. One of them is the Order with certain order attributes and the other one is Counter, an assistant model so to say. The idea is that I need to check the database if an order exists, if it doesn't, i need to give Counter the value of 1 as this will be the first order, then the value needs to be assigned to the code of the Order model. On the other hand, if an order does exist, then increment a counter by 1. Here's my approach and it's getting me this error as the value of code: <django.db.models.query_utils.DeferredAttribute object at 0x04996280> Here is the simplified version of the models. Also quick question, am I right to do this part on the models file? Should I do it on the serializer or views or it doesn't really change anything. Thanks in advance. class Counter(models.Model): def count(self): self.value = 0 for order in Order.objects.all(): self.value += 1 return self.value @property def names(self): return "P+ %s + %s" % (self.value, Order.code_year) … -
Django Remote User Authentication
I am using Django to build a data analysis webpage for our corporate. Currently, I am using the default Django server as the domain of my webpage. However, I am new to Django. In the webpage I want to do two things: In the navigation bar on the website, I want the username shown. Anyone using the corporate network or in the Active Directory of the corporate is authenticated to use the webpage, and once they visit it, their username is shown at the top of the page. I want to embed a Spotfire file in the webpage. However, I don't want the embedded Spotfire to ask for login, I want it directly shown to the user. I hope you can help me. -
How to add an image editor (cropper plugin) to my python project?
trying tot follow: https://medium.com/geekculture/implement-cropping-feature-on-your-website-in-under-10-min-cropper-js-46b90d860748 trying to implement a cropping feature to my beginner app, user is asked to upload an image and will be given the option to crop the image, having a hard time understanding how forms work with django, Specially with crispy forms. app Idea: soccer cards collector aapp, where user adds teams and each team page will have list of players with pics,etc... difference from medium article code: I am implementing a one to many relationship with the teams model where each team can have more than one pic uploaded URLS.py path('', views.home, name="home"), path('about/', views.about, name="about"), path('teams/', views.teams_index, name="teams_index"), path('teams/<int:team_id>/add_fixture/', views.add_fixture, name='add_fixture' ), path('teams/create', views.TeamCreate.as_view(), name="teams_create"), path('teams/<int:team_id>', views.teams_detail, name="teams_detail"), path('teams/<int:pk>/update', views.TeamUpdate.as_view(), name="teams_update"), path('teams/<int:pk>/delete', views.TeamDelete.as_view(), name="teams_delete"), path('teams/<int:team_id>/assoc_card/<int:card_id>/', views.assoc_card, name="assoc_card"), path('cards/', views.cards_index, name="index"), path('cards/<int:card_id>/', views.cards_detail, name="detail"), path('cards/create/', views.CardCreate.as_view(), name="cats_create"), path('cards/<int:pk>/update/', views.CardUpdate.as_view(), name="cards_update"), path('cards/<int:pk>/delete/', views.CardDelete.as_view(), name="cards_delete"), path('teams/<int:team_id>/crop', views.crop, name="crop"), views.py def crop(request, team_id): team = Team.objects.get(id=team_id) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) # Gets the uploaded data and maps it to the ProfileForm object if form.is_valid(): # Checks if the uploaded data is valid or not new_crop = form.save(commit=False) new_crop.team_id = team_id new_crop.save() form.save() # Saves the uploaded data into our Database model return redirect('details') # Makes … -
Django NoReverseMatch Error. Please guys, kindly assist with this django error on keyword arguments '{'slug': ''}' not found
please I need help with this Django error. I have searched and done things I learnt, yet, I couldn't decipher the problem Model.py from django.db import models from django.urls import reverse # Create your models here. class Notes(models.Model): note_topic = models.CharField(max_length=200, blank=False) note_body = models.TextField(null=True, blank=True) slug = models.SlugField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.note_topic def get_absolute_url(self): return reverse('notebooks:note-detail', kwargs={'slug' : self.slug}) ``` view.py from django.utils import timezone from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Notes class NotesView(ListView): model = Notes template_name = 'notes.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['notes'] = Notes.objects.all() return context class NotesDetailView(DetailView): model = Notes template_name = 'note-detail.html' context_object_name = 'note' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['time'] = timezone.now() return context ``` urls.py for the app from django.contrib import admin from django.urls import path, include urlpatterns = [ path('notes/', include('notebooks.urls', namespace='notes')), path('admin/', admin.site.urls), ] note.html the notebook app home page {% extends 'base.html' %} {% block title %} List of Notebooks {% endblock title %} {% block content %} <div class="col-7 mt-4"> <div class="list-group"> <button type="button" class="list-group-item list-group-item-action active" aria- current="true"> List Of Notebooks </button> {% for item in object_list … -
How to download zip file coming as django response through ajax post request?
so ,after my ajax post request my Django view return a zip file as response.I want to download that zip file as soon as response came . But i don't know what to do . I go through many answer but not worked for me. Right now zip file downloading but when i open it's corrupted. My django response zip file type is <class '_io.BufferedReader'>. Ajax Code of Post request function upload(url) { let pdf_file = $('#file_input').get(0).files[0]; let form_data = new FormData(); form_data.append("file", pdf_file); jQuery.ajax({ url: url, type: "POST", data: form_data, enctype: 'multipart/form-data', contentType: false, processData: false, success: function (response) { var binaryData = []; binaryData.push(response); var link = document.createElement('a'); link.href = window.URL.createObjectURL(new Blob(binaryData, {type: "application/zip"})) link.download = 'sample.zip'; document.body.appendChild(link); link.click(); }, error: function (response) { loading_btn.classList.add("d-none"); upload_btn.classList.remove("d-none"); } }); } ajax Response ** Django View ** @csrf_exempt def upload_file(request): if request.is_ajax() and request.method == 'POST': zip_file = open('/home/deftbox/PycharmProjects/pdf_data_Extractor/test.zip', 'rb') return FileResponse(zip_file) -
How can i solve this error that i enccountered while deploying django on iis
I am getting the error below. Could someone tell me why. Running python 3.8 Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\Lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = import(module_name, fromlist=[name_list[0][0]]) File ".\analytics_suite\wsgi.py", line 16, in application = get_wsgi_application() File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\biu\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: -
Typing warnings on Django HttpRequest GET param retrieval in PyCharm
I currently encounter a warning in PyCharm when I try to retrieve a value from the GET dictionary of the Django HttpRequest object. I have always used the code below but I am trying to add type checks in my source code. from django.http import HttpRequest def parse_request(request: HttpRequest): request.GET.get('mykey') Warning: Parameter 'key' unfilled I am using Python 3.9.6 Django 3.2.4 PyCharm 2021.1 -
Not a valid origin for the client for google auth
I am making django, react and google auth with this introduction https://iamashutoshpanda.medium.com/google-login-with-django-react-part-1-c189bc69a999 my App.js import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Grid from "@material-ui/core/Grid"; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import GoogleLogin from "react-google-login"; import axios from "axios"; // get env vars const googleClientId = process.env.REACT_APP_GOOGLE_CLIENT_ID; const drfClientId = process.env.REACT_APP_DRF_CLIENT_ID; const drfClientSecret = process.env.REACT_APP_DRF_CLIENT_SECRET; console.log("googleClientId:" + googleClientId); //correct console.log("drfClientSecret:" + drfClientSecret); //correct console.log("drfClientId:" + drfClientId); //correct const baseURL = "http://localhost:8008"; const handleGoogleLogin = (response) => { axios .post(`${baseURL}/auth/convert-token`, { token: response.accessToken, backend: "google-oauth2", grant_type: "convert_token", client_id: drfClientId, client_secret: drfClientSecret, }) .then((res) => { const { access_token, refresh_token } = res.data; console.log({ access_token, refresh_token }); localStorage.setItem("access_token", access_token); localStorage.setItem("refresh_token", refresh_token); }) .catch((err) => { console.log("Error Google login", err); }); }; const App = () => { return ( <div className="App"> <GoogleLogin clientId={googleClientId} buttonText="LOGIN WITH GOOGLE" onSuccess={(response) => handleGoogleLogin(response)} render={(renderProps) => ( <button onClick={renderProps.onClick} disabled={renderProps.disabled} type="button" class="login-with-google-btn" > Sign in with Google </button> )} onFailure={(err) => console.log("Google Login failed", err)} /> </div> ); }; export default App; Now I have this error, when loading the browser Not a valid origin for the client: http://localhost:3000 has …