Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Super User Can't Login
I have created a few superusers and tried logging in as all of them but none of them work.The admin website just says: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive and I'm pretty sure everything I entered was correct so I don't know where the problem could be coming from. Any ideas of how to fix this? -
Django get Category all data on Cart Page?
hi i am new in Django i want to select category all data on Cart Page. So user can see related all items if he/she want to buy more products. i don't know how i can get a category all data on cart page? View.py import random import string import stripe from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.views.generic import ListView, DetailView, View from django.db.models import Q from .forms import CheckoutForm, CouponForm, RefundForm, PaymentForm from .models import Item, OrderItem, Order, Address, Payment, Coupon, Refund, UserProfile stripe.api_key = settings.STRIPE_SECRET_KEY def create_ref_code(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=20)) def search_product(request): if request.method == "GET": query_name = request.GET.get('search', None) if query_name: results = Item.objects.filter( title__icontains=query_name) return render(request, 'product.html', {"results": results}) def products(request): context = { 'items': Item.objects.all() } def is_valid_form(values): valid = True for field in values: if field == '': valid = False return valid class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } Thanks enter image description here -
Sending data with files or image using axios and Django?
I am using axios with Django to send data to server and I have a form with input of type 'file' I am trying to send the form data using axios and it saves the data but the the Image does not upload to media folder this is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'core/static'), ] I am using a core for my python code and this is my python code def on_save(self, request, *args, **kwargs): self.row = None model_form = self.form if not self.has_user_add_perm(self.row): response = message.not_has_permission() else: form = model_form(request.POST, request.FILES) form_validated = form.is_valid() if form_validated: obj = self.save_form(request, form) self.save_model(request, obj, form) response = message.save_successfully() else: response = message.check_input(form.errors.as_json()) return JsonResponse(response) def on_update(self, request, *args, **kwargs): obj = request.POST.get('updateForm') model_form = self.form obj_for_update = get_object_or_404(self.model, pk=obj) if not self.has_user_edit_perm(obj_for_update) or not self.has_user_view_perm(obj_for_update): response = message.not_has_permission() else: form = model_form(request.POST, request.FILES, instance=obj_for_update) form_validated = form.is_valid() if form_validated: obj = self.save_form(request, form) self.save_model(request, obj, form) response = message.update_successfully() else: response = message.check_input(form.errors.as_json()) return JsonResponse(response) def post(self, request, *args, **kwargs): if 'saveForm' in request.POST.keys(): try: with transaction.atomic(): return self.on_save(request, *args, **kwargs) except JsonResponseException as e: return … -
Correct way to handle .wasm.gz and .data files in Django?
I'm currently dealing with a problem in my django web application that is running locally on 192.168.0.168. I'm making use of an OCR library that makes use of .wasm.gz files and .data files. In the documentation they mention: " In some cases you need to configure your webserver to serve data and wasm.gz files.". My first idea was to add the following mimetypes in django: mimetypes.add_type("application/x-gzip", ".wasm.gz", True) mimetypes.add_type("application/octet-stream", ".data", True) I'm however still seeing the error: error wasm-instantie. It somehow can't instantiate wasm because django needs to serve the wasm.gz and .data files correctly. These have been added however to the static folder and I'm able to download them if I manually browse to the link. Does anyone have any idea what I need to do to serve these correctly? -
Object permissions in Django Rest Framework
I am trying to do something which seems so straight-forward with Django Rest Framework and object permissions but there doesn't seem to be a simple way to go about it. Here are the (simplified) models I am talking about:- class Team(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Player(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) class Invitation(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) I want to:- a) allow any authenticated user to create a Team but to prevent anyone but that user from changing or deleting that team b) allow any Player of that Team to create an Invitation for that Team but no-one else to be able to I decided to go with DjangoObjectPermissions in order to implement a). So my first problem seems to be that, in order to allow anyone to create a Team, I need to give ALL users the add_team permission which seems a bit unnecessary to me. Then I'll need to give any "normal" players I create the view_team permission on that Team but only the owner gets change_team and delete_team on that Team. Which is fine. But the bigger problem is when I try and work out permissions for the Invitation model. I can't give … -
Django Limit Access to Foreign Key without Proper Preload
I have 2 models, and I want to limit query access of some fields (the foreign key fields) from being loaded in memory, and throw an error in case someone tries to access them to avoid memory issues. class GenericItem(models.Model): name = models.Charfield(max_length=100) structure = models.TextField() class CustomItem(models.Model): name = models.Charfield(max_length=100) date = models.DateTimeField(auto_now_add=True) item_structure = models.ForeignKey(models.GenericItem) GenericItem.structure is a big text, and I want to prevent queries that want to access it from CustomItem without preloading it. Any idea how this could be done in a good manner? -
sorting search results in django
I'm have a django app with the following model. class Posts(models.Model): post = models.TextField(max_length=1500) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) likes = models.ManyToManyField(User, related_name="post_likes") category = models.CharField(max_length=50, default=None) To allow the users search for a particular blog and then display those objects I have the following view. def index(request): if request.method == "GET": search = request.GET.get("input") posts = Posts.objects.filter(category__icontains=f"{search}") else: posts = Posts.objects.all() params = {'blog': posts} return render(request, 'index.html', params) In the above view , variable search contains what user has searched for, that I'm receiving through a form. But I also want to provide a sort functionality after user has searched for a blog. Like user searches for "recipes", I need to show them all the search results and then let him sort them based on likes and recent etc. How do I do it since I'm losing search terms just after displaying the results. -
Problem with importing pisa from xhtml2pdf
I am trying the following code from an online tutorial on Django. Everything is working fine but when I import 'pisa' from xhtml2pdf, I get an error, "Import xhtml2pdf could not be resolved". What could be the issue? I have installed xhtml2pdf.Is there another python file I need to have? Please help me with resolving this issue. from django.shortcuts import render, get_object_or_404 from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report from django.views.generic import ListView, DetailView, TemplateView from .forms import ReportForm from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from sales.models import Sale, Position, CSV from products.models import Product from customers.models import Customer import csv from django.utils.dateparse import parse_date from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin class ReportListView(LoginRequiredMixin, ListView): model = Report template_name = 'reports/main.html' class ReportDetailView(LoginRequiredMixin, DetailView): model = Report template_name = 'reports/detail.html' class UploadTemplateView(LoginRequiredMixin, TemplateView): template_name = 'reports/from_file.html' @login_required def csv_upload_view(request): print('file is being') if request.method == 'POST': csv_file_name = request.FILES.get('file').name csv_file = request.FILES.get('file') obj, created = CSV.objects.get_or_create(file_name=csv_file_name) if created: obj.csv_file = csv_file obj.save() with open(obj.csv_file.path, 'r') as f: reader = csv.reader(f) reader.__next__() for row in reader: data = "".join(row) data = … -
Django Views.py setup
I'm getting a RecursionError: maximum recursion depth exceeded while calling a python object enter code here from django.conf.urls import url enter code here from . import views enter code here urlpatterns = [ enter code here # Home page enter code here path(r'^$', views.index name='index') enter code here # show all topics enter code here url(r'^topics/$', view.topics, name='topics') enter code here ] -
Is there any tool which could help me convert a raw sql query to django ORM query?
I am looking for a tool to convert my raw SQL query to Django ORM query Or could someone help me with the conversion? Raw Query: select coalesce(v1.Value1 - v2.Value2, 0) as sent from ( select sum(catch_attempt) as Value1 from test_statsbatch sb where sb.process_id = test_process.id ) as v1 cross join ( select total_skipped as Value2 from processes_processaggregatedstats sca where sca.id = test_process.process_stats_id ) as v2 -
TypeError at /candidate/1/
I used positional parameters and it is showing that Position is not Iterable as Position is Object so anybody please try to help me out of this ASAP.. views.py def candidate_view(request,pos): obj = get_object_or_404(Position,pk=3) if request.method == "POST": print("You are in ") return HttpResponse("Voted") else: return render(request, 'poll/candidate.html', {'obj': obj}) Urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from . import views urlpatterns = [ path('',views.home,name="home"), path('register',views.register,name="register"), path('login',views.view_login,name="view_login"), path('logout',views.view_logout,name="view_logout"), path('candidate/<int:pos>/',views.candidate_view,name="candidate_view"), path('positions',views.position_view,name="position_view"), path('result',views.result,name="result"), ] Position.html {% extends 'base.html' %} {% block title %}Positions{% endblock %} {%block body%} <h2>Available Position For Vote</h2> <ul> {% for i in obj %} <li><a href="{% url 'candidate_view' i.id%}">{{i.title}}</a></li> {% empty %} <p>No Positions Available</p> {% endfor %} </ul> {% endblock %} Models.py class Position(models.Model): title = models.CharField(max_length=30) def __str__(self): return self.title #This is model of candidate class Candidate(models.Model): full_name = models.CharField(max_length=30) pos = models.ForeignKey(Position, on_delete=models.CASCADE) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.pos.title) -
How a change a dash size?
I have a small size of dash How I can change a dash size or a parent div size? I used a simple usage from example and it worked normal. But I have size problem with new dash [enter image description here][1] dash app import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample') # replaces dash.Dash app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children=''' Dash: A web application framework for Python. '''), dcc.Graph( id='example-graph', figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'}, {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'}, ], 'layout': { 'title': 'Dash Data Visualization' } } )]) if __name__ == '__main__': app.run_server(debug=True) views.py from django.shortcuts import render from django.http import HttpResponse from . import plotly_app def index(request): return render(request, "index.html") some important from settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newtry', 'django_plotly_dash.apps.DjangoPlotlyDashConfig',] -
Is it posible to route requests for specific domains to different URL schemes in Django?
Is it possible to route requests for specific domains to different URL schemes in Django? For example I have domains: example.com ans secret.com. Is it possible to handle different URL schemes for different domain names? -
Comparing Between datetime field in django
I have a model named Assignment in my project This is how the Assignment model looks like class Assignment(models.Model): user = models.ForeignKey( Teacher, on_delete=models.CASCADE, related_name='assignments') unique_code = models.CharField(max_length=11, default=assignment_uniqe_id) title = models.CharField(max_length=250) deadline = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) subject = models.ForeignKey( All_Subject, on_delete=models.CASCADE, related_name='assignment_subject') classes = models.ManyToManyField(Classes) submitted_by = models.ManyToManyField(Student, blank=True) description = models.TextField(blank=True) def __str__(self): return str(self.user) + " : " + self.title And I want to check weather if the current date is greater then the deadline. Please help me out -
Overriding/extending Django Admin Login page with django-suit
I've been working on adding Okta integration to django admin and tried to extend the login page to add a new button (the okta integration itself works fine if a go to /admin/login), but when i do this: {% extends 'admin/login.html' %} {% load i18n %} {% block extrastyle %} {{ block.super }} <style> #content-main { float: none !important; } .okta_login_container { margin-top: 15px; display: flex; justify-content: center; } </style> {% endblock %} {% block content %} {{ block.super }} <div class="okta_login_container"> <a href="some-url">Or Login With Okta</a> </div> {% endblock %} Starting the server fails the following error maximum recursion depth exceeded while getting the repr of an object as it seems to not find the login.html page. overriding other pages like base.html work fine. Other important facts, django-suit is being used and it already overrides the style of the login page. -
Django: Why the User model contains custom fields declared in UserCreationForm
I was going through a django tutorial on registration and I feel like this particular code doesn't make sense. First of all, instead of writing a custom email field, which does nothing different than User email field, shouldn't we just add email to the list of fields? But my main question is about writing password1 and password2 in the fields. Now I know that these are custom fields of UserCreationForm, and are passed to the UserRegistrationForm by inheritance. And indeed, the password and re-enter password fields are visible on the html page, even if I delete those from the fields. What I don't get is why leaving them there doesn't result in an error? The user model only has a password field, which will equate the password1 field of the form through the save method: user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user But the model itself shouldn't have those fields, but yet I'm not getting an error. Any thoughts? -
Vue JS widgets in hybrid application
I have a hybrid Django/VueJS application. I combine Django templating pages with VueJS widgets because that allows to take best of the 2 different worlds. However, I face an issue when I need to place multiple VueJS widgets. When I need to embed only 1 widget, I just use to embed it. But when I have multiple widgets, I don't know what to do. Do I need to mount multiple widget separately? Is this a good practice? Here's how my main.js looks like: import Vue from "vue"; import vuetify from "./plugins/vuetify"; import router from "./router"; import AccountApp from "./AccountApp.vue"; import store from "./store/index.js"; import i18n from "./i18n"; Vue.config.productionTip = false; const accountApp = new Vue({ vuetify, router, store, i18n, render: (h) => h(AccountApp), }); accountApp.$mount("#app"); -
How to fix error in Django serializers.py fields
I'm trying to send a post request from django app using rest framework but I keep having the following output: { "user_name": [ "This field is required." ], "email": [ "This field is required." ], "company": [ "This field is required." ], "state": [ "This field is required." ], "city": [ "This field is required." ], "address": [ "This field is required." ], "phone_number": [ "This field is required." ], "password": [ "This field is required." ], "password_2": [ "This field is required." ] } I have the following blocks of code: urls.py urlpatterns = [ path("register_user/", account_register, name="register") ] models.py from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.db import models from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField from django.core.mail import send_mail class CustomManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, password, **other_fields) def create_user(self, email, user_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, … -
How can I use django rest Framework's search filter to search in multiple models
I want to search in multiple models. what can I do to achieve that. like we can do this to search in a single model. class ArtistListView(viewsets.ModelViewSet): queryset = Artist.objects.all() serializer_class = ArtistSerializer filter_backends = (SearchFilter, OrderingFilter) search_fields = ('artist_name', 'born', 'albums__album_name') but what i want to do is that like if I search for "taylor", I want to get results from artist model, album model and playlist model. with same term. how can I specify multiple and models and their fields to filter in. please help me. -
how to connect postgresql to aws RDS using Django
I am unable to connect my postgreSQL database to AWS RDS while using Django. I am not sure what i am doing wrong but i have the configuration below: Django docker-compose postgres #DJANGO Settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "dbtest", 'USER': "mastername", 'PASSWORD': "somepassword", 'HOST': 'dbtest.zmrHnee2mhLunL.us-east-2.rds.amazonaws.com', 'PORT': 5432 } } docker-compose version: "3.7" services: backend: build: ./backend container_name: backend stdin_open: true tty: true restart: "on-failure" env_file: .env volumes: - ./backend:/backend - ./backend/static:/backend/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - db_network db: image: postgres:11.5-alpine container_name: db restart: always environment: - POSTGRES_DB=dbtest - POSTGRES_USER=mastername - POSTGRES_PASSWORD=somepassword volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - db_network networks: db_network: driver: bridge volumes: postgres_data: after starting the container docker-compose up -d --build Now when i check docker-compose logs I see the traceback below: File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect backend | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) backend | django.db.utils.OperationalError: could not translate host name "dbtest.zmrHnee2mhLunL.us-east-2.rds.amazonaws.com" to address: Name or service not known security group I have been trying to debug for hours, any help would be really helpful -
ImportError : Couldn't import Django
I have installed django==3.1.4 and activated Venv on my windows machine and it works fine in myBlog project. But today when I try to run the server, got this error ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? but venv is already activated and when I do pip freeze > requirements.txt It shows asgiref==3.3.4, Django==3.1.4, django-crispy-forms==1.11.2, Pillow==8.2.0, pytz==2021.1, sqlparse==0.4.1, I also checked sys.path, It shows ['', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python38-32', 'C:\Users\user\Desktop\myBlog\venv', 'C:\Users\user\Desktop\myBlog\venv\lib\site-packages'] Please Help to fix this -
load an app from another reusable app in django
Let's say we have this file structure as in the Django tutorial website: mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py Where the polls app is not the entry point of the Django project. Instead, it's an app that is intended to be reusable, so that if we copied the polls folder to another Django project, all we will have to do to get it to work is only to add polls.apps.PollsConfig to the INSTALLED_APPS in mysite/settings.py and then do the database migration. My question is, what if, the polls app depends on another app, let's say, django_ace. In this case, the polls app will not work properly unless I add 'django_ace' as well to the INSTALLED_APPS in mysite/settings.py. But it's very inconvenient for a reusable app to require that you manually add its dependencies. So, is there any way I can load the django_ace app from within the polls app itself so that it remains reusable such that including the polls app will implicitly include the django_ace app as well? -
How to update text of the document file in the queryset?
def corrections_fn(request, file, selected_words, corrections): parser = GingerIt() user = request.user document = Document(file.file) text = '' for line in document.paragraphs: matches = parser.parse(line.text) for obj in matches['corrections']: misspelled_word = obj['text'] if misspelled_word in selected_words: correction = selected_words[misspelled_word] line.text = line.text.replace(str(misspelled_word), str(correction)) else: if corrections == 'auto': line.text = line.text.replace(str(obj['text']), str(obj['correct'])) document.save(file.file) return file In the file variable, i'm sending the Queryset which contains file(.docx). resumes = Resume.objects.filter(user=user) for resume in resumes: corrections_fn(request=request, file=resume, selected_words=selected_words, corrections="show") When i try to rewrite the file. It is showing "Unsupported Operation write" error. I searched on internet and i'm not able to find the right document to deal with this type of issue. can any help me on how to solve the issue? Thank you in advance -
Model Fields in Django
I am implementing a Custom User interface by adding two new fields in the built in User model. class CustomUser(AbstractUser): is_employee = models.BooleanField(default=False) is_contractor = models.BooleanField(default=False) I want to create two new profiles based on the values in these two fields. class Employee(models.Model): pass class Contractor(models.Model): pass if is_employee is True then create an employee and if is_contractor is True then create a contractor. In django documentation django signals are used to create this link between models using pre_save and post_save function but how can I access the field value from the user model? -
How do I display Django Rest Framework Foreign Key in Angular?
DISCLAIMER: This is gonna be a pretty long description of a problem, to which I can't seem to find sources for that could help me. So any piece of information is appreciated! I might add that I am fairly new to Angular and text script. I have set up my backend with Django and set up the Rest Framework. These are my models: models.py class Person(models.Model): name = models.CharField(max_length = 250, blank = True) job = models.ForeignKey('Job', on_delete = models.CASCADE, null = True) def __str__(self): return self.name class Job(models.Model): job_name = models.CharField(max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0, unique = True) def __str__(self): return self.job_name In the backend I have set up different job names (Doctor, Teacher, etc...). So when I create a new Person, I get to choose from one of the different jobs, which have been created prior to this. (This is exactly how I woukd want my frontend to work) Here are my serializer.py, views.py and urls.py files: serializer.py class PersonSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Person fields = ('id', 'name', 'job') class JobSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Job fields = ('id', 'job_name') views.py class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer def list(self, …