Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple apps and views in a single html page in Django
I am relatively new to Django and do not understand it in depth. For some reason even though everyone says that Django documentation is amazing, I do not understand it what so ever. For some reason, I am not able to integrate a model, model and a view from 2 different apps into my home.html page. What I am trying to do is to get a newsletter sign up, as a form. It is inside jobs app Jobs also include "Jobs" which I display on the home page and blog posts which I also want to display on my HTML home page. I do not see a need to create a new app as it's not a model which I will be reusing a lot and ready solutions are not to my liking due to limitations. I have tried to solve what is the problem and I finally realised that it's in the url.py file under urlpatterns. Here are my code snipets: project url.py from django.conf import settings from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static import jobs.views import blog.views import compound.views from django.conf.urls import url, include from markdownx import urls as markdownx views_home_page = … -
Delete selected multiple data to delete using django
How do I need to change or update from this code below? I just want that if the teacher select 5 students out of 50, it will delete the 5 student selected of the teacher. StudentOrderList = [] for student in request.POST.getlist('student'): StudentOrderList.append(student) i = 0 for i in StudentOrderList: for student_id in request.POST.getlist("relatedid"): StudentRelatedGroup.objects.filter(id=student_id).delete() return redirect(studentlist) return redirect(studentlist) in my case even the teacher selected only 5 students, all 50 student data deleted -
Django server inside docker is causing robot tests to give blank screens?
I have built an environment inside docker compose in order to run robot tests. The environment consists of django web app, postgres and robot framework container. The Problem I have is that I get many blank screens in different tests, while using external Django web app instance which is installed on a virtual machine doesn't have this problem. The blank screen causes that elements are not found hence so many failures: JavascriptException: Message: javascript error: Cannot read property 'get' of undefined (Session info: headless chrome=84.0.4147.89) I am sure that the problem is with the Django app container itself not robot container since as said above I have tested with the same environment but against different web app which is installed outside Docker, and it worked. docker-compose.yml: > cat docker-compose.yml version: "3.6" services: redis: image: redis:3.2 ports: - 6379 networks: local: ipv4_address: 10.0.0.20 smtpd: image: mysmtpd:1.0.5 ports: - 25 networks: - local postgres: image: mypostgres build: context: ../dias-postgres/ args: VERSION: ${POSTGRES_TAG:-12} hostname: "postgres" environment: POSTGRES_DB: ${POSTGRES_USER} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} networks: local: ipv4_address: 10.0.0.100 ports: - 5432 volumes: - my-postgres:/var/lib/postgresql/data app: image: mypyenv:${PYENV_TAG:-1.1} tty: true stdin_open: true user: ${MY_USER:-jenkins} networks: local: ipv4_address: 10.0.0.50 hostname: "app" ports: - 8000 volumes: - ${WORKSPACE}:/app … -
Converting string to IntegerChoice value?
Suppose I have an integer field in a model as follows: class Foo(models.Model): class Bar(models.IntegerChoices): PARROT = 1 MESSIAH = 2 NAUGHTY_BOY = 3 BLACK_KNIGHT = 4 bar = models.IntegerField(choices=Bar.choices, default=Bar.PARROT) How do I convert the string value to an integer to save it i.e. the same as what appears to happen if I use the field on a "forms.ModelForm" as a drop down? E.g. Take "Parrot" and return 1. record = get_object_or_404(Foo, id=1) record.bar = "Parrot" record.save() This code gives an error: Field 'bar' expected a number but got 'Parrot'. -
how to set different urls.py file bases on user in django
I have two urls file in my base project: urls.py admin_urls.py depending on the requested user, different urls will be accessed. And users are differentiated based on the request. I created a middleware file which contains: class URLHandlerMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # if not request.user.is_anonymous: if not request.user.user: if request.META['saleschannel'] == SALES_CHANNEL_IDS['a510b9']: request.urlconf = 'hyp_users_svc.admin_urls' else: request.urlconf = 'hyp_users_svc.urls' return response users are differentaiated based on this parameter saleschannel. This is my middlewares list in settings MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'hyp_users_svc.services.versioned.v1.middlewares.url_handler.URLHandlerMiddleware', ## my url middleware 'hyp_users_svc.services.versioned.v1.middlewares.error_handler.ErrorResponseMiddleware' ] But this is not working. There might be a problem with ordering of middleware, but i tried to call my middleware initially but still its not working. Thanks in advance -
Getting notimplementederror: can't perform this operation for unregistered loader type
I have build a windows application for comparing two Excel sheets using Pandas dataframe. I used dataframe.stlye.apply to highlight some columns with different colors based on data and exporting it into a new Excel file. Also, I have used pyinstaller for converting .py into .exe. **code snippet -** *save_op_file function is for applying style and save into excel.* def save_op_file(df): save_path = filedialog.asksaveasfilename(defaultextension='xlsx') writer = pd.ExcelWriter(save_path, engine='xlsxwriter') df1 = '' item_count = 0 for items in changes: pos_count = 0 for pos in items: if item_count == 0 and pos_count == 0: df1 = df.style.apply(write_style_yellow, row_idx=pos[0], col_idx=pos[1], axis=None) else: if pos_count == 0: df1 = df1.apply(write_style_yellow, row_idx=pos[0], col_idx=pos[1], axis= None) else: df1 = df1.apply(write_style_red, row_idx=pos[0], col_idx=pos[1], axis= None) item_count += 1 pos_count += 1 print('df1:') print(df1) df1.to_excel(writer, sheet_name='Sheet1', index=False) writer.save() def write_style_yellow(x, row_idx, col_idx): color = 'background-color: yellow' df_styler = pd.DataFrame('', index=x.index, columns=x.columns) df_styler.iloc[row_idx,col_idx] = color return df_styler def write_style_red(x,row_idx,col_idx): color = 'background-color: red' df_styler = pd.DataFrame('', index=x.index, columns=x.columns) df_styler.iloc[row_idx,col_idx] = color return df_styler Now, when I am running my application, it is throwing this error - * Exception in Tkinter callback Traceback (most recent call last): File "tkinter\ init .py", line 1883, in _call_ File "Excel.py", line 199, in … -
Average of time from datetime objects in Python
I have multiple datetime objects as below: dt1 = (2020, 8, 12, 11, 30, 12, 966753) dt2 = (2020, 7, 12, 11, 20, 11, 966753) dt3 = (2020, 9, 12, 11, 32, 10, 966753) I want to calculate the average of the times here, irrespective of the dates. How can I achieve that without using any scientific tool? -
custom admin home page display model objects django-jet
class CustomIndexDashboard(Dashboard): columns = 3 def init_with_context(self, context): self.children.append(modules.ModelList( _('Profiles'), models="my_app.Profiles", column=0, order=0 )) enter image description here here i try to create a custom index admin dashboard and i want to display objects of model profiles not the name of the model. So how can i dispay list of objects from model instead of model mame in django-jet admin home page? -
Django 3.1, I'm NOT getting RelatedObjectDoesNotExist error for User and Profile models
as the title reads I'm NOT getting the RelatedObjectDoesNotExist error in Django 3.1(Latest Release) I'm not using signals. I create a superuser using the (python manage.py createsuperuser) command, which, as expected, does not create a profile. models.py ''' class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) ''' views.py ''' class RegisterView(View): def get(self, request): form = UserSignUpForm() # print(form) return render(request, 'users/register.html', {'form': form}) def post(self, request): form = UserSignUpForm(request.POST) if form.is_valid(): form.save() username = request.POST.get('username') Profile.objects.create(user=User.objects.get(username=username)) return redirect('users:login-page') return render(request, 'users/register.html', {'form': form}) ''' when I use the createsuperuser command no profile is created, so I expect to get RelatedObjectDoesNotExist if I try to sign in. But I do NOT! why is that? also if I edit the database manually and remove a profile and keep the user, the user still works with no RelatedObjectDoesNotExist error! is this something that has changed with Django 3.1 ! thank you -
how do i dynamically display gallery view on django
i want to display a gallery view dynamically by adding images directly from the admin panel. This is the code,i have added site.register in admin.py gallery.html {% extends 'app/main.html' %} {% load static %} {% block content %} <div class="row container"> {% for imgs in gallery %} <div class="col-md-4"> <img class="thumbnail " src="{{gallery.imageURL}}" alt=""> </div> {% endfor %} {% endblock content %} models.py from django.db import models class Gallery(models.Model): image=models.ImageField(null=True,blank=True) @property def imageURL(self): try: url=self.image.url except: url= '' return url views.py def gallery(request): imgs=Gallery.objects.all() context={'imgs':imgs} return render(request,"app/gallery.html",context) urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('app.urls')), ] if settings.DEBUG: # new urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
after working with my api for a while i got Error: RecursionError at /elements/
I'm building a recursive django rest api and it work very well at the beginning but later after a make few more post requests and put requests I got RecursionError at /elements/ maximum recursion depth exceeded while calling a Python object Request Method: GET Request URL: http://127.0.0.1:8000/elements/ Django Version: 3.1 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded while calling a Python object Exception Location: //anaconda3/lib/python3.7/enum.py, line 530, in __new__ Python Executable: /Users/apple/Desktop/learning web stack from clonning notion.so/backend/env/bin/python Python Version: 3.7.3 Python Path: ['/Users/apple/Desktop/learning web stack from clonning ' 'notion.so/backend/mysite', '//anaconda3/lib/python37.zip', '//anaconda3/lib/python3.7', '//anaconda3/lib/python3.7/lib-dynload', '/Users/apple/Desktop/learning web stack from clonning ' 'notion.so/backend/env/lib/python3.7/site-packages'] Server time: Mon, 17 Aug 2020 13:52:03 +0000 I have three models as shown here. HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "elements": "http://127.0.0.1:8000/elements/", "styles": "http://127.0.0.1:8000/styles/", "components": "http://127.0.0.1:8000/components/" } I made few post and put requests on the elements model and now i'm getting that error only when I open it. myapp/urls.py from .views import elementsVeiwSet, stylesVeiwSet, componentsVeiwSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('elements', elementsVeiwSet, basename='elements') router.register('styles', stylesVeiwSet, basename='styles') router.register('components', componentsVeiwSet, basename='components') urlpatterns = router.urls views.py from myapp.models import elements, styles, components from .serializers import elementsSerializer, stylesSerializer, componentsSerializer from rest_framework import viewsets … -
how to get the src of iframe in django
I have created on app inside the web project. inside the model.py class ReportName(): src = models.CharField(max_length=100, blank=False) #src:str name = models.CharField(max_length=100, blank=False) #name:str width = models.IntegerField(max_length=100, blank=False) #width:int height = models.IntegerField(max_length=100, blank=False) #height:int def __str__(self): return self.src and inside the views.py def add(request): #if request.method == "POST": #rept=ReportName.objects.order_by() rept=ReportName() rept.src=request.POST['src'] rept.width=int(request.POST['width']) rept.height=int(request.POST['height']) rept.name=request.POST['name'] #context={'rept':rept} return render(request, 'report_one.html', {'src':rept.src, 'width':rept.width, 'height':rept.height, 'name':rept.name}) inside the urls.py path('add', views.add, name='add') inside the report_one.html {% extends 'base.html' %} {% block content %} src : {{ src }} width: {{ width }} height: {{ height }} name: {{name}} <iframe src = "src" width= "" height="" frameborder="0" allowfullscreen allowtransparency ></iframe> {% endblock %} inside the html file where i get these iframe attribute value {% extends 'base.html' %} {% load buttons %} {% load static %} {% load custom_links %} {% load helpers %} {% load plugins %} {% block content %} <form action = "add" method='post'> {% csrf_token %} URL: <input type="text" name="src"><br> WIDTH: <input type="text" name="width"><br> HEIGHT: <input type="text" name="height"><br> NAME OF THE REPORT: <input type="text" name="name"><br> <input type="submit"> </form> {% endblock %} MY QUESTION IS HOW I CAN GET THE VALE INSIDE THE IFRAME ??? WHAT SHOULD I USED IN FRONT SRC, … -
Django CheckConstraint won't work with ForeignKeys
I have two foreign keys that point to the same model, and I want to use a CheckConstraint to make sure they are not pointing to the same object. # 'origin' and 'warehouse' are foreignkeys to the same model constraints = [ models.CheckConstraint(check=models.Q(origin=F('warehouse')), name='origin_ne_warehouse') ] I should get an IntegrityError when creating an object that fits the conditions, but nothing happens. I tried other non-related constraints, and they worked perfectly. I know I can use validation, but I don't want to do a full clean everytime I save, and I'm using DRF as well so I want my validation to be in one place. Is there any way to get this to work without using validation? -
Implement Django middleware for response behaviour
I'm a bit confused by the middleware description in the official django docs and can't seem to wrap my head around it. When implementing class-based middleware it looks something like this (ex. from docs): class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response The middleware gets called for requests as well as for response. This is my first question: How do I implement different behavior depending on if I'm processing a request or a response? Also, and this is related, I'm a bit confused because there also seems to be an old deprecated way of writing middleware where it was possible to overwrite the methods process.request() and process_response(). I'm not sure if this way of writing middleware is inadvisable now. Usually, the Django docs are spot on but this part is a little confusing (to me). Can someone clear this up for me? -
Get err_connection_refused accessing django running on wsl2 from Windows but can curl from Windows terminal
I got the err_connection_refused when trying to accessing django running on wsl2 (http://localhost:8000) from Windows but when I use curl http://localhost:8000 from Windows terminal, it's working fine. I have tried to add a new firewall inbound rule for port 8000 but it's still not working. Is there anything else I need to take care of. Thanks a lot -
Just added event appears on screen but id doesn't exist and thus when we want to edit just added event without refresh the page, it's impossible
My problem is when event is successfully added, it shows on the screen but id is not included and thus if we want to edit an event that we just add without refreshing the page, error will appear which says id doesn't match. My success part looks like this. I can edit and delete without no problem as long as id exist but the problem appears when I try to add new event. success: function(data) { $('#calendar').fullCalendar( 'removeEvents', EventData.id ); $('#calendar').fullCalendar('renderEvent', EventData); $('#inputScheduleForm').modal('hide'); alert("予定を" + methodName + "しました。"); console.log(EventData) }, result from console.log(EventData) after I clicked add button: {id: "", title: "abcccc", start: "2020-08-21T00:00:00", end: "2020-08-21T00:00:00", allDay: true, …} What should I add in the success part to make sure after I add the event, I don't have to refresh the button to create a new id? Any idea anyone? -
How to access class variable from another class in Django?
I'm new to Python and Django. I'm trying to build a rest API. I have two classes (see below), Organization and Organizationmember. In the front-end I want to display which organization members belong to an organization. I'm using members = models.ManyToManyField(User, through='Organizationmember') now, but this gives me back the id. I want show the first_name of the organization member. Also, this way I'm creating an extra field in Organizations, but it already exist in Organizationsmember. So I'm not sure if this is the best approach. Later on I wan't to do this with more classes (i.e. Projects & Projectmembers). What would be the best approach to do this? Thx in advance! class Organization(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=50) tel_number = models.IntegerField() contact = models.CharField(max_length=50) members = models.ManyToManyField(User, through='Organizationmember') def __str__(self): return self.name class Organizationmember(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) experience = models.CharField(max_length=100) class Meta: unique_together = ('organization', 'user') def __str__(self): return f'{self.first_name} {self.last_name}' -
ConnectionAbortedError: [WinError 10053] Une connexion établie a été abandonnée par un logiciel de votre ordinateur hôte
I'm using python 3.6 Django version 3.3 Anaconda version 4.04 when i run my project i got this error bellow in image, please anyone can help me ? [enter image description here][1] 1]: https://i.stack.imgur.com/ub7oQ.png -
Implement Multiple AUTH Backend in Django
I have two apps in my django REST Api Project. One is Customer and other one is Retailer. I wanted to implement Token Authentication. I have used Knox-authentication in my app. But the issue is in my settings.py file I have registered retailer model of Retailer app as auth model. How would i do the same for the Customer app for the customer model? Can we have two auth models? Or how can i implement custom Knox authentication for both of the models. Desired Output : When retailer logs in it should get a token as well as the customer should get the same. Can anyone provide relevant information? I am a begineer to Django I can provide relevant codes for the same if needed -
index.html file Style background img url for python Django
style="background-image:url({% static 'images/home_slider.jpg' %})" Please see above code and correct me if i am wrong to writing this for loading background img in django using static load method because it is showing error in vs code.. please help me out -
how to see the table in my database after creating and migrating models in django
i tried to connect my sql cloud cluster to visual studio code and connected in settings.py as DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME':'aras', 'USER':'arasuser', 'PASSWORD':'**********', 'HOST':'mysql-numbers-0.cloudclusters.net', 'connection':'connect1', } } Later, i created a model and run migrations . but yet i am unable to see the table in my database. am i connecting it right ? -
How to add a text editor like Stack Overflow's to my website
I want to make it so users can submit articles to my website, that includes a text area with styling. It would be good if you can give me the code. I'm working with Django. Right now I have only text area. -
how to set the movies name in dropdown box by default in django?
i am trying to post the review followed by movies name by using the foreign key it gives the drop box of movies instead of setting it automatically i don't know what to do please help me views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Movies from django.contrib.auth.models import User class MoviesListView(ListView): model = Movies template_name = 'blog/home_movies.html' ordering = ['-date_released'] context_object_name = 'movies' paginate_by = 10 class MoviesDetailListView(ListView): model = Post template_name = 'blog/post_list.html' context_object_name = 'posts' paginate_by = 10 def get_queryset(self): user = get_object_or_404(Movies, name=self.kwargs.get('name')) return Post.objects.filter(name=user).order_by('-date_posted') class PostListView(ListView): model = Post template_name = 'blog/home_movies.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 class UserPostListView(ListView): model = Post template_name = 'blog/user_post.html' # app/model_viewtype.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post context_object_name = 'posts' class PostCreateView(LoginRequiredMixin,CreateView): model = Post context_object_name = 'posts' fields = ['title', 'content','name'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content', 'name'] def form_valid(self, form): form.instance.author = self.request.user … -
How to connect one Django project user in other Django project?
When we see Google apps icon in a browser there we are many different google apps, I don't have an idea are they all deployed on same server or different. when we use anyone we don't need authentication again, I have created multiple Django project and deployed them on different servers, is there any way to connect all projects user, so that when he authenticate in one server no need to authenticate on a different server. -
django problems with css
having trouble linking css to my django project, right now im just a beginner and learning how to use the framework. i dont really know whats important and what's not so i'll put the full code. i checked some tutorials and did what they did but it still didn't work i tried some stuff from the documentation and still no luck. Can someone help me out. heres the settings.py file """ Django settings for ecommerce_site project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wfudi*u9lch97-&tq*sq+_5fi0u&e3khi@iy^(tzg9znkdql)s' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store' ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] 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', ] ROOT_URLCONF = 'ecommerce_site.urls' TEMPLATES …