Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Best Practice: Processing complex dynamic form on single-page with Django
I'm looking for the most pythonic way to handle a complex form on a single-page. My "submit" page has a series of questions that, based on the user's input, will generate different forms/fields. A simplified example: --- Shift 1 --> Form #1 --- Yes -- What shift? -- | | --- Shift 2 --> Form #2 | Enter Date --- Did you work? ---| | | --- Yes --> Form #3 --- No -- Was this PTO? ---| --- No --> Form #4 I'm trying to figure out most efficient/pythonic way to handle the above. Possible Approaches: Lots of jquery, ajax, and function based views. This is my current setup, but I'd like to move it to CBV and ModelForms if possible because my current code is about 2000 lines (with 10+ ajax functions, 10+ view-handling urls, and too many input fields to count) within my template/models/views just to load/process this form. It is a complete nightmare to maintain. Single page with ModelForms embedded within a dynamic div. The form page calls a jquery load depending on your answers to the questions. For instance, if you answered "Today", "Yes", "Shift 1", I would call $("#form-embed").load("/forms/form1/") which contains the Form #1 … -
Desktop App connected to website with python
I recently started to program in Python. In my job they ask me to program a website with sign-in/login to perform multiple tasks (print a dashboard, export data, etc.) and a desktop app that connects to this website to retrive info from a particular module (We will upload files to this site and desktop app will compare that files to specified files in desktop). What is the best option to perform this task. Actually, i programmed a CRUD in Django with MySQL database (not deployed to production yet) and a desktop app in Tkinter, but as this grows i think this is not suitable. What will be better options for this task? Thanks in advance, as i say, im new to python programming -
Request.data django
Tengo un problema con django al modificar el request, necesito agregar un atributo, eh visto varios sitios y todos me dicen lo mismo, logro modificar el request pero al mandarlo al serializador, el request no se ve reflejado los cambios def create(self, request): data = json.dumps(request.data) data = json.loads(data) data['id_user_created'] = 1 serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() return ResponseData.Response(TYPECODE.NO, TYPECODE.CREATED, MESSAGE.CREATED, MESSAGE.NULL, status.HTTP_201_CREATED) return ResponseData.Response(TYPECODE.SI, TYPECODE.BAD_REQUEST, MESSAGE.BAD_REQUEST, serializer.errors, status.HTTP_400_BAD_REQUEST) Mi serializador class UserSerializer(serializers.ModelSerializer): class Meta: model = Usuario exclude = ['created_date', 'last_login','modified_date','id_user_created','id_user_modified'] def to_representation(self, instance): return { 'id':instance.id, 'state':instance.state, 'email':instance.email, 'names':instance.names, 'identify':instance.identify } def create(self, validated_data): print(validated_data) user = Usuario(**validated_data) user.set_password(validated_data['password']) #user.id_user_created = validated_data.id_user_created user.save() return user -
permission.AllowAny not working in knoxLoginView
I tried using the knoxLoginView for login with token authentication,and it was stated on knox documentation that for the loginView to work and not throw a 401 unauthorized error i have to either add permission class "AllowAny" or override the authentication class with BasicAuthentication. I tried both neither worked, the login view still throws 401 unauthorized error.The surprising thing is i saw a youtube tutorial where a guy used the permission.AllowAny and it worked, don't know why its not working for me. here's the login view code: class LoginAPI(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginAPI, self).post(request, format=None) settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'knox', 'corsheaders', 'users', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ #'rest_framework.authentication.BasicAuthentication' , 'knox.auth.TokenAuthentication', ] } -
how to convert a QuerySet to a set in django?
I have a query, name_phonenum = person.objects.value_list('first_name','phone_num') I want to convert the queryset to a set. Any idea how can do it. -
How do I enforce 2 decimal places on API response in Django?
I am making a small API server in Django. For one of my fields, I am using a decimal field which is responsible for representing $ dollar values, so I would like to have 2 decimal places at all times. But I'm struggling to have the exact format. I'm using rest_framework and my base level response is encoded as a string with the following serializer is: price = serializers.DecimalField(max_digits=10, decimal_places=2, required=True) string representation There is an option to turn off string coercion with "COERCE_DECIMAL_TO_STRING": False in settings.py, but then I face a problem that Decimal is not JSON serializable, and have to use FloatField where I cannot specify a format and end up with only 1 decimal place: price = serializers.FloatField(required=True) float representation I searched for setting up FloatField format on the serializer but did not find any related option. I believe I also tried some other serializers like this one and did not achieve the goal, which is: How do I enforce 2 decimal places on API response in Django?