Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request <WSGIRequest: GET '/create'>
Я пытаюсь сделать страницу для создания таска, но я не могу запустить страницу (ошибка: form = TaskForm()) from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.order_by('-id') return render(request, 'main/index.html', {'title': 'Главная страница сайта', 'tasks': tasks}) def about(request): return render(request, 'main/about.html') def create(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid: form.save() return redirect('home') form = TaskForm() context = { 'form': form } return render(request, 'main/create.html', context) Я могу получить эту форму, но когда я публикую, я получаю: request <WSGIRequest: GET '/create'> -
Remove AUTH user from right sidebar in DJANGO JAZZMIN admin panel
enter image description here Hello there! I want to remove Auth user from left side bar as show in picture above. Is it possible? -
I am new in django having problem to migrate my database
My Error: Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Python39\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: database "telusko" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Md. Tarek Aziz\Desktop\django\telusko\manage.py", line 21, in <module> main() File "C:\Users\Md. Tarek Aziz\Desktop\django\telusko\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python39\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 29, in execute return super().execute(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\commands\sqlmigrate.py", line 37, in handle loader = MigrationLoader(connection, replace_migrations=False) File "C:\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in __init__ self.build_graph() File "C:\Python39\lib\site-packages\django\db\migrations\loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Python39\lib\site-packages\django\utils\asyncio.py", line 26, … -
401 Error in React and django-rest-framework app
First of all I got this useState which takes data from input: const Checkout = ({cart, totalPrice, code}) => { const [values, setValues] = useState({ email: '', city:'', adress:'', postalCode:'', phone:'', firstName:'', lastName:'', message:'', price: totalPrice, code: code, shipmentFee:0, shipmentMethod:'', lockerId:'', cart:cart, }); Then I submit it with generateOrder(values) function: export const generateOrder = (order) => { return fetch(`${url}/orders/generate-bank-transfer-order/`,{ method:"POST", body:order }) .then((response) => { return response.json(); }) .catch((error) => console.log(error)) }; It points to this url in urls.py: path('generate-bank-transfer-order/',generate_bank_transfer_order, name="generate-bank-transfer") And this is a view I use, for now I just want it to return submited data so I can test if it works: @csrf_exempt def generate_bank_transfer_order(request): if request.method == "POST": body = request.body return JsonResponse({"test":body}) All I get is 401 Unauthorized and I have no idea how to fix it. Any ideas? -
Counting sum of values, based on unique values
I am not sure if the title is clear enough, so I'll do my best to explain what I want and what the problem is. What I have I have a graph that get's filled with data from a query. Every day of the month has a value that is grouped by day, for example: day 1 = 5, day 2 = 6, day 3 = 8 etc. This works with the following code, for 1 subscription: data_usage = DataUsage.objects \ .filter(subscription_id=subscription_id) \ .filter(created_at__month=today.month) \ .annotate( created_date=TruncDay('created_at') ).values('created_date') \ .annotate( subscription_id=Max('subscription_id'), data_usage=Max('data_usage'), created_at=Max('created_at') ).values( 'subscription_id', 'data_usage', 'created_at' ) The image below is a correctly filled graph with the code above: What I need I need this same graph but this time with the values from every subscription. So basically the code has to give me the same output, but with the sum of 'data_usage' of all subscriptions for that day. Only the highest and thus latest value for every subscription should be used. I have tried 10's of solutions that did not work for me, the current code does not work: data_usage = DataUsage.objects \ .filter(created_at__month=today.month) \ .annotate( created_date=TruncDay('created_at') ).values('created_date') \ .annotate( subscription_id=Max('subscription_id'), data_usage=Sum('data_usage'), created_at=Max('created_at') ).values( 'data_usage', 'created_at' ) What's … -
django http response 204 redirecting to blank page only in safari
I have a view button that triggers a javascript function. The JS function is made to display a modal popup and then redirect to a URL that returns HTTP 204 response. return HttpResponse(status=204). this is the js code function count(){ image_popup.style.display = "block"; document.body.style.overflowY = "hidden"; window.location.href = "/image_info/view_count"; } This code is working fine in chrome and firefox but in safari, 204 response is redirecting to a new blank page. In other browsers, the 204 response is not redirecting the page and displaying the modal popup just fine. -
request <WSGIRequest: GET '/create'>
''' def about(request): return render(request, 'main/about.html') def create(request): form = TaskForm … context = { 'from': form } return render(request, 'main/create.html', context) ''' -
module not found pythonanywhere
I have deployed my site on pythonanywhere. the link to the site is AbuTheRayhan.pythonanywhere.com but the server says Something went wrong :-( Something went wrong while trying to load this website; please try again later. If it is your site, you should check your logs to determine what the problem is. On error log Error running WSGI application ModuleNotFoundError: No module named 'streamer' File "/var/www/abutherayhan_pythonanywhere_com_wsgi.py", line 14, in <module> application = get_wsgi_application() wsgi.py code is import os import sys path = '/home/AbuTheRayhan/video_uploader_with_django/streamer/video_streamer/video_streamer' if path not in sys.path: sys.path.insert(0, path) os.environ['DJANGO_SETTINGS_MODULE'] = 'streamer.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() the problem is here(os.environ['DJANGO_SETTINGS_MODULE'] = 'streamer.settings' ). What they exactly want me to write here? -
Does "null=True" store "NULL" or "empty values" in DB? (Django)
When I wrote this code below to create django models, I thought "NULL" is stored in DB if "null=True" intuitively thinking: # Here models.CharField(max_length=100, null=True) But, when I checked the django documentation about null, it says: If True, Django will store empty values as NULL in the database. So, as the documentation says, "empty values" is stored in DB instead of NULL if "null=True"? -
how to prevent saving data in save_model in admin.py?
I am trying to override django UserAdmin save_model method in admin.py In some case I want to ignore saving data. Am I missing something in else section. here is my code: def save_model(self, request, obj, form, change): obj.owner = request.user.id if request.POST.get('code') != '41798': super(ProductAdmin, self).save_model(request, obj, form, change) else : self.message_user(request, "ignore save", messages.SUCCESS) .... ??? -
Why django import export is not working in my django project?
I am working in django project and I want admin to import data from excel file to database of model Entry. But it is not working properly . here is my admin.py from django.contrib import admin from .models import Entry from import_export.admin import ImportMixin from .resources import EntryResource class EntryAdmin(ImportMixin, admin.ModelAdmin): resource_class = EntryResource admin.site.register(Entry, EntryAdmin) the error is : Cannot assign "'vijay'": "Entry.user" must be a "CustomUser" instance. my csv file: Id,User,Member,Member Id,Email Address,State,K No,Board,Last Date,Amount vijay,team,team54f4d,teamcarbon006@gmail.com,rajasthan,5f4d5f4d,jval, 2022-03-13,54451 -
Axios not sending csrf token to django backend even after trying all suggested configs
The function that handles my signup make api requests with axios. Below are the configs that I have made lerning from SO. react import axios from "axios"; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; export const signup = ({ name, email, password, password2 }) => async (dispatch) => { const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ name, email, password, password2 }); try { const res = await axios.post(`${host}/api/account/signup/`, body, config); dispatch({ type: SIGNUP_SUCCESS, payload: res.data, }); dispatch(login(email, password)); } catch (err) { dispatch({ type: SIGNUP_FAIL, }); dispatch(setAlert("Error Authenticating", "error")); } }; settings.py CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_HTTPONLY = False CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"] CORS_ALLOW_CREDENTIALS = True Even after all the above configs I am getting this error in django Forbidden (CSRF cookie not set.): /api/account/signup/ [13/Mar/2022 14:41:50] "POST /api/account/signup/ HTTP/1.1" 403 2870 Please help me to rectify this error -
Casting a video from Django to Angular
I am building a web application in which I have to upload a video to the server and then, after some analysis, casting it to the frontend which is an Angular application. I can see how to perform the upload, but I cannot find a tutorial or some advice on how to do this. The server is built with Django and django-rest-framework. Thanks for your help! -
Is there a way to access the tenant with same domain instead of subdomain Django-tenants?
Info: I want to make multi tenant app using django.I have installed django-tenants for a multitenancy SaaS app. django-tenants resolve tenants like tenant1.mysite.com Each tenant access with subdomain. i want to access the tenant into the same domain like mysite.com/tenant1/ instead of subdomain. I would like to access tenants using mysite.com/tenant1/, mysite.com/tenant2/. -
Django:Model class firts_app.models.Topic does not declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am trying to populate models using populate script. I have set up models,and did migrations. I have tried every solution that I found on internet so far, but it did not work. It gives : "RuntimeError: Model class first_app.models.Topic doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() populate_first_app.py import os from django.conf import settings settings.configure() os.environ.setdefault("DJANGO _SETTINGS_MODULE",'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage,Topic from faker import Faker fake_object=Faker(); topics=['Search,''Social','Marketplace','News','Games'] genders=['Male','Female'] def add_topic(): t=Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t; def populate(N=5): for entry in range(N): fake_topic=add_topic().top_name; fake_name=fake_object.company(); fake_url=fake_object.url(); webpage=Webpage.objects.get_or_create(topic=fake_topic,name=fake_name,url=fake_url)[0] if __name__=='__main__': print('populating script'); populate(20); print('populated') models.py from django.db import models class Topic(models.Model): top_name =models.CharField(max_length=264,unique=True); def __str__(self) : return self.top_name; class Webpage(models.Model): topic=models.ForeignKey(Topic,on_delete=models.CASCADE) name=models.CharField(max_length=264,unique=True) url=models.URLField(unique=True) def __str__(self) : return self.name; class AccessRecord (models.Model): name=models.ForeignKey(Webpage,on_delete=models.CASCADE); date=models.DateField() def __str__(self) : return str(self.date) … -
Apache - Hosting two Django projects issue - One project is very slow / unaccessible
I'm hosting two Django projects on my Ubuntu 20.04 server using Apache, with two different domains. djangoproject1 is hosted on example1.com:8000 djangoproject2 is hosted on example2.com:8000 However I'm having a strange issue where only one of the two is accessible at a time. Both sites work perfectly when the other one is disabled (using "a2dissite"). But when both are enabled, only one will work and the other one loads forever until time out. djangoproject1.conf <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName example1.com ServerAlias www.example1.com DocumentRoot /var/www/djangoproject1 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/djangoproject1/static <Directory /var/www/djangoproject1/static> Require all granted </Directory> Alias /static /var/www/djangoproject1/media <Directory /var/www/djangoproject1/media> Require all granted </Directory> <Directory /var/www/djangoproject1/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject1 python-home=/var/www/djangoproject1/venv python-path=/var/www/djangoproject1 WSGIProcessGroup djangoproject1 WSGIScriptAlias / /var/www/djangoproject1/project/wsgi.py </VirtualHost> djangoproject2.conf (similar to djangoproject1.conf) <VirtualHost *:8000> ServerAdmin webmaster@localhost ServerName example2.com ServerAlias www.example2.com DocumentRoot /var/www/djangoproject2 ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/djangoproject2/static <Directory /var/www/djangoproject2/static> Require all granted </Directory> Alias /static /var/www/djangoproject2/media <Directory /var/www/djangoproject2/media> Require all granted </Directory> <Directory /var/www/djangoproject2/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djangoproject2 python-home=/var/www/djangoproject2/venv python-path=/var/www/djangoproject2 WSGIProcessGroup djangoproject2 WSGIScriptAlias / /var/www/djangoproject2/project/wsgi.py </VirtualHost> The apache logs shows the following error multiple times: (11)Resource temporarily unavailable: mod_wsgi (pid=1498191): Couldn't create worker thread … -
Learning backend: which language?
So I have been programming for a few years now. I know HTML, CSS, Python, some JavaScript and some Java. I have made a few static websites and want to try making webapps. I need to choose the way I want to learn it first (I'll probably learn the other options later). My three obvious possibilities (I think) are: Flask Django Node.js I think all three are pretty versatile and good. Should I learn Node.js or write backend with Python? If I use Python, should I learn Flask or Django? Thanks a lot! -
Get queryset from another CBV
I have two CBV's: one is the main view that is used to display the queryset, the second is a view that is only used for processing the data for exporting it into a file; it only returns a file to download. What I'm trying to achieve is to access the queryset from main view in the processing view. Here is my example: Main View: class EmployeesView(LoginRequiredMixin, FilterView): template_name = 'Employee/employees.html' model = Employee filterset_class = EmployeesFilter def get_queryset(self): order_by = 'emp_name' if self.request.GET.get('sort'): order_by = self.request.GET.get('sort') # Get URL parameter from dashboard and show results according to that. if self.kwargs and self.kwargs['ref']: ... query_set = Employee.objects.filter(visa_status='Pending Processing').order_by(order_by) else: query_set = Employee.objects.all().order_by(order_by) filter = self.filterset_class(self.request.GET, query_set) return filter.qs Processing View: class ExportEmployeesData(LoginRequiredMixin, TemplateView): def get(self, request, *args, **kwargs): emp_view = EmployeesView() employees = emp_view.get_queryset() .... .... response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename={date}-employees_data.xlsx'.format( date=datetime.now().strftime('%d-%m-%Y, %H-%M-%S-%p'), ) return response The problem is that whenever the EmpoyeesView's get_queryset() is accessed from ExportEmployeesData, I get an error saying 'EmployeesView' object has no attribute 'request'. Here's a full traceback: Traceback (most recent call last): File "F:\Projects\HR_EmployeeDB\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "F:\Projects\HR_EmployeeDB\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Drf: how to throttle a create request based on the amount of request's made in general and not per user
I was making an attendance system in which teachers and permitted students can take attendance of their class, I want it to be once per day and if the student has already taken the attendance the teacher should not be able to. attendance model class Attendance(models.Model): Choices = ( ("P", "Present"), ("A", "Absent"), ("L", "On leave"), ) Student = models.ForeignKey( User, on_delete=models.CASCADE, blank=False, null=True) leave_reason = models.CharField(max_length=355, blank=True, null=True) Date = models.DateField(blank=False, null=True, auto_now=False, auto_now_add=True) Presence = models.CharField( choices=Choices, max_length=255, blank=False, null=True) def __str__(self): return f'{self.Student}' -
Django All Auth Google Login Prevent extra page
I have enabled google login in my Django web application. right now what happens is, when i click on login the url is as follows: it takes me to this page (please find the image below) which i want to prevent but can't figure out how do i. here is the image Please assist. -
Proper way to rollback on DB connection fail in Django
This is more of a design question than anything else. Until recently I have been using Django with SQLite in my development environment, but I have now changed to PostgreSQL for production. My app is deployed with Heroku, and after some days I realized that they do random maintenance to the DB and it goes down during a few minutes. For example, having a model with 3 tables, one Procedure which each of them point to a ProcedureList, and a ProcedureList can have more than one Procedure. A ProcedureUser which links a ProcedureList and a user and sets some specific variables for the user on that ProcedureList. Finally there is a ProcedureState which links a Procedure with its state for an specific user. On my app, in one of the views I have a function that modifies the DB in the following way: user = request.user plist = ProcedureList.objects.get(id=idFromUrl) procedures = Procedure.objects.filter(ProcedureList=pList) pUser = ProcedureUser(plist, user, someVariables) pUser.save() for procedure in procedures: pState = ProcedureState(plist, user, pUser, procedure, otherVariables) pState.save() So what I'm thinking now, is that if Heroku decides to go into maintenance between those object.save() calls, we will have a problem. The later calls to .save() will fail … -
Can we upload multiple files at once in Django Admin site
I have a class named city. For this city, I have a filefield variable to upload the files. But I need to upload multiple files all at once in a single field in the Admin site (localhost:8000/admin). Could you please guide me with a sample code to get a clear idea about the implementation or suggest to me the implementation plan of doing it? -
Site on django doesn't load static
My site on django doesn't load static files html: {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/dist/css/bootstrap.css' %}"> <script src="{% static 'jquery/dist/jquery.min.js' %}"></script> <script src="{% static 'bootstrap/dist/js/bootstrap.min.js' %}"></script> files: from terminal: [13/Mar/2022 03:36:26] "GET / HTTP/1.1" 200 24975 [13/Mar/2022 03:36:26] "GET /static/bootstrap/dist/css/bootstrap.css HTTP/1.1" 404 1758 [13/Mar/2022 03:36:26] "GET /static/jquery/dist/jquery.min.js HTTP/1.1" 404 1751 [13/Mar/2022 03:36:26] "GET /static/bootstrap/dist/js/bootstrap.min.js HTTP/1.1" 404 1760 [13/Mar/2022 03:36:26] "GET /media/cache/77/1c/771c04f6935d264617dd3dec309a41d0.jpg HTTP/1.1" 404 1773 What could be be the reason of this? -
How do I output text from the python terminal to my website using django
I am making a messaging website using django. at the moment the messages I send and receive print in the terminal. does anyone know how to output those messages in the website. (if you need some of the code just ask) -
for loop of ListView not iterating through data in Django
code which not working this code is not working, i don't know what is wrong in my code. Views.py