Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django howto include urls from app into an existant namespace
My project has a namespace 'dashboard' and I'd like to include an app (django-calendar) into it, so my urls would be like /dashboard/calendar-list. So in dashboard urls.py I added: (...) path("avoirs/", include(avoirs_urls)), path("vouchers/", include(vouchers_urls)), path("logs/", include(log_urls)), path('schedule', include('schedule.urls', namespace='schedule')), (...) So I can reverse my urls using for example: reverse("dashboard:schedule:calendar_list") It's where I came accross a pitfall: All the app code uses urls like calendar_list and not schedule:calendar_list. Same for templates using code like {% url 'calendar_list' %}. It doesn't seem reasonable to refactor all the calendar app to fit my project. Is there a way to include it in the existing namespace? What's the guideline here? Thanks to share knowledge... -
Adding Data to ManytoMany Field Django
I am creating a dynamic form using javascript. Here are the models which I am using to store the data. one_label_fields = ['text','color','date','number','email','password'] class InputFieldNames(models.Model): name= models.CharField(max_length=40) #one field inputs :text,color,date,email,number,password def __str__(self): return self.name class OneLabelInputField(models.Model): label = models.CharField(max_length =40) value =models.CharField(max_length=40) def __str__(self): return "Label: "+self.label +"| Value: "+self.value class CheckBoxLabel(models.Model): label =models.CharField(max_length=40) def __str__(self): return self.label class CheckBoxField(models.Model): group_name = models.CharField(max_length=40) labels = models.ManyToManyField(CheckBoxLabel) def __str__(self): return self.group_name class DynamicForm(models.Model): single_label_fields =models.ManyToManyField() checkboxes = models.ManyToManyField(CheckBoxField) Here is my View function def form_creation(request): if request.method == 'POST': input_types = InputFieldNames.objects.all() form = DynamicForm.objects.create() print("form cretaetd ->",form) for x in input_types: #print(x.name) input_fields = request.POST.getlist(x.name) print("INPUT FIELDS:",input_fields) label_name = 'hidden_'+x.name #print(label_name) input_field_labels = request.POST.getlist(label_name) print("LABELS OF THE RESPECTIVD FIELDS",input_field_labels) length = len(input_fields) if length: for i in range(length): field = OneLabelInputField.objects.create(label = input_field_labels[i], value=input_fields[i]) form.single_label_fields.add(OneLabelInputField.objects.get(id= field.id)) print(">>>",form) # if input_fields: # print(input_fields) # print(input_field_labels) inputs = InputFieldNames.objects.all() context={} context['inputs'] = inputs #context['one_label_fields'] = json.dumps(one_label_fields) return render(request,"dynamic_form.html",context) I have declared many to many field in the Dynamic form model,because I want to store multiple objects of SingleLabelInputField and connect its relation with Dynamic Form. Whenever I create a Dynamic form ,and submit the data, the data is saved without any … -
Uanble to connect to remote mysql phpmyadmin
I'm trying to connect to remote phpmyadmin through my Django application. 'client4': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DATABASE_NAME_5'), 'USER': 'username', 'PASSWORD': config('DATABASE_PASSWORD_PHPMYADMIN'), 'HOST': 'xxx.xx.xxx.xxx', 'PORT': '3306', }, When I run makemigrations, django.db.utils.OperationalError: (1045, "Access denied for user 'username'@'yyy.yy.yyy.yyy' (using password: YES)") This error pops. But the IP address shown here is different and unknown to me. I tried connecting to 2 different IP addresses but the same IP address keeps popping in the error. I tried to connect to a remote server using the terminal command, mysql -u root -h xxx.xxx.xx.xxx -p Led to the same error, ERROR 1045 (28000): Access denied for user 'root'@'yyy.yy.yyy.yyy' (using password: YES) with the same IP popping up again. I am unable to figure out what where this IP is coming from. I also checked my local IPs using ifconfig But this IP was not seen anywhere. Please help me out here. Thanks. -
Heroku application error logs, cannot run heroku open
I just made my first application. when I run Heroku open I get an error "Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail" what could possibly be the problem?Can a problem with DJANGO_SECRET_KEY cause such problem ? this is my logs 2021-06-11T05:06:11.906892+00:00 app[api]: Initial release by user a 2021-06-11T05:06:11.906892+00:00 app[api]: Release v1 created by user a 2021-06-11T05:06:12.046032+00:00 app[api]: Enable Logplex by user a 2021-06-11T05:06:12.046032+00:00 app[api]: Release v2 created by user a 2021-06-11T06:24:58.000000+00:00 app[api]: Build started by user 2021-06-11T06:25:45.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/67a0bf8e-56f4-41bd-b9de-b02c9ca20f13/activity/builds/b4469f36-8883-468b-95a2-aadaa03ff662 2021-06-11T06:36:08.000000+00:00 app[api]: Build started by user a 2021-06-11T06:36:39.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/67a0bf8e-56f4-41bd-b9de-b02c9ca20f13/activity/builds/254007fa-69b7-45d7-9490-5bd0643ec3cf 2021-06-11T06:37:40.559478+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user a 2021-06-11T06:37:40.559478+00:00 app[api]: Release v3 created by user a 2021-06-11T06:38:00.000000+00:00 app[api]: Build started by user a 2021-06-11T06:38:41.947391+00:00 app[api]: Running release v4 commands by user a 2021-06-11T06:38:41.947391+00:00 app[api]: Attach DATABASE (@ref:postgresql-fitted-13790) by user a 2021-06-11T06:38:41.960986+00:00 app[api]: @ref:postgresql-fitted-13790 completed provisioning, setting DATABASE_URL. by user a 2021-06-11T06:38:41.960986+00:00 app[api]: Release v5 created by user a 2021-06-11T06:38:42.248836+00:00 app[api]: Release v6 created … -
in django Mongodb Like (in mysql keyword) same in mongo db not working
Questions.objects.find({ps_tags: "/"+request.POST['txtTag']+"/"}).values() this is the code where I am using to search related words from the database but I am getting the following error. ERROR AttributeError: 'Manager' object has no attribute 'find' I want to implement code search (in MySQL if we want to search then we will use LIKE key word for matching rows from multiple rows) same like in Django MongoDB I want to implement but I am getting the above error, any solution for this? -
How does Huey call task?
I have this code here # it's not every five mins but let's overlook that for now @periodic_task(crontab(minute='*/1')) def every_five_mins(): # ... But I couldn't find where Huey calls the function. The only other place that I've used Huey is in settings.py but still I only included HUEY = { 'huey_class': 'huey.RedisHuey', 'name': DATABASES['default']['NAME'], 'results': True, 'store_none': False, 'immediate': False, 'utc': True, 'blocking': True, 'connection': { 'host': 'localhost', 'port': 6379, 'db': 0, 'connection_pool': None, 'read_timeout': 1, 'url': None, }, 'consumer': { 'workers': 1, 'worker_type': 'thread', 'initial_delay': 0.1, 'backoff': 1.15, 'max_delay': 10.0, 'scheduler_interval': 1, 'periodic': True, 'check_worker_health': True, 'health_check_interval': 1, }, } Can anyone please tell me how a task is executed? I want to know this because I want to pass in parameters into every_five_mins(), e.g., every_five_mins(argument1=argument1) but I can't do that without knowing where the function is called (otherwise argument1 is going to raise an undefined error). Thanks in advance. -
Django rest framework group objects by date
I have a Django model like below: from django.models import Model class Post(models.Model): headline = models.CharField(max_length=100) content = models.TextField() published_at = models.DateField() Requirement is to make API that group post objects by publish date (daily) and with pagination. Expected response is: { "publish_date": "2020-05-03", "posts": [ { "id": 1, "headline": "headline1", "content": "post body" }, ... ], "publish_date": "2020-05-16", "posts": [ { "id": 4, "headline": "headline2", "content": "post body" }, ... ], ... } How to make this done efficiently with Django? I don't want to iterate over dates and filter posts by that date. I tried queryset's dates and annotate methods with no successful result: from django.db.models import Subquery, OuterRef from blog.models import Post post_subquery = Post.objects.filter(published_at=OuterRef('published_at')).values('published_at') Post.objects.dates('published_at', 'day').annotate(publish_day=F('published_at'), posts=Subquery(post_subquery)).values('publish_day', 'posts') It says Cannot resolve keyword 'publish_day' into field. How should I do this via Django's ORM? -
How to create database automatically in django using settings.py or models.py
1) Pgadmin -> Create -> Database -> db_name 2) change database connection details in settings.py 3) python manage.py makemigrations (assuming we have ready-made models) 4) python manage.py migrate Is there any way to skip step 1? -
Django input CSV file to create a new table. (CSV file convert into a table in the database)
I wanted some help with a project I'm working on: So I have to take a CSV as input from the user and convert the CSV save it as a Table in the Database. So I was able to take the input from the user and save it in the MEDIA_ROOT. But now I'm unsure how to create a model without knowing the columns and so on. (I know I can get the columns from pandas(in views.py) but how to send that column details to models.py) I'm new to Django and very much confused with so many files. Please help. Note: I don't want to save the CSV file I want to convert it into a table in the database. views.py import pandas as pd from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage def home(request): return render(request, 'index.html') def upload(request): if request.method == 'POST': upload_file = request.FILES['csvfile'] fs = FileSystemStorage() fs.save(upload_file.name, upload_file) dataset = pd.read_csv('media/'+upload_file.name) colums = list(dataset.columns) return render(request, 'upload.html') models.py from assignment.settings import MEDIA_ROOT from django.db import models from django.db.models.fields import CharField class CSV(models.Model): csvfile = models.FileField(upload_to='CSV') -
How connect my admin panel (native django admin) to firebase
I'm new in django and firebase. in my project, i need to connect my admin panel (native django administration) to firebase. Please can i have a solution for this? Regards. -
Why qlite3.OperationalError: no such column: loginsignup_customusers.password While creating CustomUser and CustomUserManager?
I have just started learning Django and stuck my self in very strange condition. I have created my own CustomUser instead of available in django.contrib.auth.models for authentication purpose. I am getting some error or problems all together ,while running the program,i am trying to post all of them bellow. I know all of them are occurred due to some silly mistake which i am unable to figure out on my own 1) When ever i am trying to run python manage.py make migrations i am getting error as bellow:- You are trying to add a non-nullable field 'password' to customusers without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 2) When using python manage.py runserver is worked fine and run a emulated server on my local computer. Now when i am trying to access admin/ it shows me the following error**:-** Internal Server Error: /admin/ Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return … -
Mocking model.User using mixer through error
Im trying to add unit test for my Django project. Im using mixer to mock the models. The model looks as below from django.contrib.auth.models import User class Mytable(Model): username = models.OneToOneField(User, on_delete=models.CASCADE, db_column='username') ... ... My testcase looks like class MyTest: def test_test1(self): mock_user = mixer.blend('django.contrib.auth.models.User') stock_mock = mixer.blend('app.Mytable', username=mock_user) But im hitting "too many values to unpack" while mocking User model Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/kketan/Documents/projects/Extractor/.venv/lib/python3.8/site-packages/mixer/main.py", line 566, in blend type_mixer = self.get_typemixer(scheme) File "/Users/kketan/Documents/projects/Extractor/.venv/lib/python3.8/site-packages/mixer/main.py", line 583, in get_typemixer return self.type_mixer_cls( File "/Users/kketan/Documents/projects/Extractor/.venv/lib/python3.8/site-packages/mixer/main.py", line 47, in __call__ cls_type = cls.__load_cls(cls_type) File "/Users/kketan/Documents/projects/Extractor/.venv/lib/python3.8/site-packages/mixer/backend/django.py", line 137, in __load_cls app_label, model_name = cls_type.split(".") ValueError: too many values to unpack (expected 2) Am I mocking the models right way ? If yes is this error known ? If no can you please suggest better way ? -
Main page with host name is not opening in Django app on live server
I am hosting a Django app on managed server with passenger_wsgi.py file. Lets say my domain name is food.menu , when i visit 'https://food.menu' browser shows me Not Allowed but when i visit 'https://food.menu/Menu' then these links are accessible. foodsample> urls.py file looks like this urlpatterns = [ path('admin/', admin.site.urls), path('', include('food.Urls.WebsiteUrls'))] food> urls.py file looks like this urlpatterns = [ path('', WebsiteViews.Home, name='HomePage'), path('menusearch', WebsiteViews.Search_Menu, name='menusearch'), path('MenuQR', WebsiteViews.MenuQRCode, name='MenuQR'), path('Menu', WebsiteViews.Menu, name='Menu'), path('QRScanner', WebsiteViews.Scanner_View, name='QRScanner')] on localhost its working fine but on live server main url path('', WebsiteViews.Home, name='HomePage') with domain name is not opening. Cpanel Application Manager Setting: 1.Application Manager>Deployment Domain, i have selected my domain 'food.menu'. 2.Base Application URL Enter the application’s base URL. After you register the application, you can use this URL to access it. i wrote nothing by default its giving the domain name and a '/' after domain name, like 'food.menu/'. Any kind of help would be great. Thanks..!! -
Vue code doesn't show up with Webpack Bundle Tracker (Django)
I run both the vue and the django. I have installed webpack_loader and have it in installed apps. I have the WEBPACK_LOADER in settings.py WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'dist/', 'STATS_FILE': os.path.join(BASE_DIR, 'frontend', 'webpack-stats.json'), } } frontend is the name when creating vue. Here is some more details KeyError at / 'assets' and ModuleNotFoundError: No module named 'webpack_loader' My page source from http://localhost:8000/ looks like this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>QuestionTime</title> </head> <body> <h1>Vue JS</h1> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> <script type="text/javascript" src="http://0.0.0.0:8080/bundle.js" ></script> </body> </html> My page source from http://localhost:8080/ looks like this <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="/favicon.ico"> <title>hello-vue</title> <link href="/js/about.js" rel="prefetch"><link href="/js/app.js" rel="preload" as="script"><link href="/js/chunk-vendors.js" rel="preload" as="script"></head> <body> <noscript> <strong>We're sorry but hello-vue doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> <script type="text/javascript" src="/js/chunk-vendors.js"></script><script type="text/javascript" src="/js/app.js"></script></body> </html> -
Can I connect my Django project wigh CloudFiresotre using Pyrebase
From pyrebase doc https://openbase.com/python/Pyrebase using db = firebase.database() gives you access to Realtime DB Are there ways I can connect to CloudFirestore using Pyrebase? Thank you. -
Django rest framework ManyToManyField field filter
models class DesignerCategories(models.Model): title = models.CharField(max_length=500, default=None) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class DesignerProduct(models.Model): title = models.CharField(max_length=500, default=None) descripton = models.CharField(max_length=500, default=None) price = models.CharField(max_length=500, default=None) editions = models.CharField(max_length=500, default=None) verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) user = models.ForeignKey( to=Login, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) collection = models.ForeignKey( to=DesignerCollection, on_delete=models.CASCADE, related_name="designerproduct", null=True, blank=True ) categories = models.ManyToManyField(DesignerCategories, related_name='designerproduct', blank=True) views: class DesignerProductView(viewsets.ModelViewSet): queryset = DesignerProduct.objects.all() serializer_class = DesignerProductSerializer filter_backends = [filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend] filterset_fields = ['verified', 'user', 'collection'] search_fields = ['title', 'descripton', 'user_id__name'] How can i add DesignerCategories model title filter. And it is ManyToManyField to DesignerCategories and categories primary ley mapped to DesignerProduct Please take a look. -
Django rest framework user models permissions
I am trying to create a web app, I need there to be different types of users, Buyer and Seller. class User(AbstractUser): isBuyer = models.BooleanField(default=False) isSeller = models.BooleanField(default=False) class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username I think the models are fine (do let me know if there are better ways). Are the boolean in the User model necessary or is there another way to differentiate between them? Also since I am using the rest framework I wanted to use permission classes. Something like, from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser @api_view(['POST']) @permission_classes([IsAuthenticated, IsSeller]) def deleteProduct(req): How do I make the IsSeller permission class? -
Set max length for all fields in Django model
I have used Django to develop a web app. However, when I tried to migrate the database to mysql, error shows: _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key le ngth is 3072 bytes') I checked my model.py, all of the CharField and db_index are set to max_length equal or below 190. So I guess maybe my some of my foreign key(textfield) caused this error. How to set all of the field to a specific Max length so I could fix this error? -
Extra User Register Information can't store in database such as phoneno playergameid exclude username,password in django while using Usercreationform
[enter image description here][1]I am a beginner for django,i just finished my django course.so i want to develop mini project.In that project i want to store user register informations in model database table.but i can store only username and password while using UserCreationForm.But i want to store extra and all informations in my django model database table..please help me to solve this.. models.py ```from django.db import models class Playerinfo(models.Model): username = models.CharField(max_length=24) pubg_name= models.CharField(max_length=14) pubg_id = models.PositiveIntegerField() email_id = models.EmailField() phone_no = models.PositiveIntegerField() password1 = models.CharField(max_length=16) password2 = models.CharField(max_length=16)``` forms.py ```from bgmiapp.models import Playerinfo from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import fields from django.forms.widgets import PasswordInput class RegisterForm(UserCreationForm): username = forms.CharField(max_length=24) pubg_name= forms.CharField(max_length=14) pubg_id = forms.IntegerField() email_id = forms.EmailField() phone_no = forms.IntegerField() password1 = forms.CharField(max_length=16,widget=PasswordInput) password2 = forms.CharField(max_length=16,widget=PasswordInput) class Meta(): model = User fields = ('username','pubg_name','pubg_id','email_id','phone_no','password1','password2')``` views.py ```from django.shortcuts import render,redirect from .forms import RegisterForm from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate,login # Create your views here. def register(request): form=RegisterForm() if request.method =='POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') raw_password=form.cleaned_data.get('password1') user=authenticate(username=username,password=raw_password) login(request,user) return redirect('login') else: form=RegisterForm() return render(request,'bgmiapp/register.html',{'form':form})``` urls.py ```from django.contrib import admin from django.urls import path from bgmiapp import … -
Extra field from request in django viewset
I am working with django viewsets and i want an extra field from the request for validation. What i want is the extra field role_id which should be coming from the request. The role id if passed, i should convert the employee to user and assign the role_id to the user. Even though i am sending the role_id from request but i am unable to get it in the create or update method. Can someone please help me to know how can i fetch extra field from response serializer.py class EmployeeModelSerializer(serializers.ModelSerializer): """Employee model serializer""" address = EmployeeAddressModelSerializer(required=False) detail = EmployeeDetailModelSerializer(required=False) demographic = EmployeeDemographicModelSerializer(required=False) contact = EmployeeContactModelSerializer(required=False) nok = EmployeeNokModelSerializer(required=False) visa = EmployeeVisaModelSerializer(required=False) dbs = EmployeeDBSModelSerializer(required=False) job_detail = EmployeeJobDetailModelSerializer(required=False) preference = EmployeePreferenceModelSerializer(required=False) skills = EmployeeSkillsModelSerializer(many=True, read_only=True) user = UserModelSerializer(required=False) serializersMap = { "address": EmployeeAddressModelSerializer, "detail": EmployeeDetailModelSerializer, "demographic": EmployeeDemographicModelSerializer, "contact": EmployeeContactModelSerializer, "nok": EmployeeNokModelSerializer, "visa": EmployeeVisaModelSerializer, "dbs": EmployeeDBSModelSerializer, "job_detail": EmployeeJobDetailModelSerializer, "preference": EmployeePreferenceModelSerializer, "user": UserModelSerializer, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.context["gender"] = None self.context["title"] = None self.context["marital_status"] = None self.context["employee_status"] = None def internal_validate(self, data, field): self.context[field] = data if data == None: return data elif data.id: return data.id return data def validate_gender(self, data): return self.internal_validate(data, "gender") def validate_title(self, data): return self.internal_validate(data, … -
Google App Engine custom runtime with xmlsec setup
We are currently hosting our Django application in Google App Engine. We have a flex environment with python runtime and its working perfectly. We are adding saml auth to our application and for that we need the xmlsec package. We've been trying to change the runtime to custom and add a Dockerfile to the same folder. We see that the Dockerfile executes and the xmlsec package is being installed. But when we try to deploy the app.yaml, we get an error that we are not able to wrap our head around: Step #5: Updating service [default] (this may take several minutes)... Step #5: .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................failed. Step #5: ERROR: (gcloud.app.deploy) Error Response: [9] Flex operation projects/autonomous-tube-234620/regions/us-central1/operations/f08e56d1-aedb-492d-ab66-738e86935bd6 error [FAILED_PRECONDITION]: An internal error occurred while processing task /app-engine-flex/flex_await_healthy/flex_await_healthy>2021-06-10T18:02:14.559Z137991.in.1: [2021-06-10 15:02:21 +0000] [7] [INFO] Starting gunicorn 19.9.0 Step #5: [2021-06-10 15:02:21 +0000] [7] [INFO] Listening at: http://0.0.0.0:8080 (7) Step #5: [2021-06-10 15:02:21 +0000] [7] [INFO] Using worker: sync Step #5: [2021-06-10 15:02:21 +0000] [10] [INFO] Booting worker with pid: 10 Step #5: [2021-06-10 15:02:21 +0000] [10] [ERROR] Exception in worker process Step #5: Traceback (most recent call last): Step #5: File "/opt/python3.7/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker Step #5: worker.init_process() Step #5: File "/opt/python3.7/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, … -
Django runserver no nginx config file
I am using windows and am trying to runserver a django project that I cloned. However, when I py manage.py runserver, it gives an error stating that it found no nginx conf file. I do have the file, but I don't think I have it set up properly. I also don't have sites-enabled. I have never used nginx and have been doing research all day on it, and still am where I began. I talked with a friend about this and was told about re-routing the traffic to not hit the oauth so that it redirects to my machine, but I am not able to figure out how to do that, even after research. I want to py manage.py runserver and view the site as it is, on my localhost, but am also scared that I may possibly deploy to the web. -
Unable to save into Foreign key fields in Django with multiple table
I'm working on a project Hr Management System. I have a model with foreign key fields to office & staff. I'm trying to save staff in user & staff role wise with foreign key office name. my view def post(self, request): if request.method != "POST": messages.error(request, "Invalid Method ") else: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') address = request.POST.get('address') phone = request.POST.get('phone') image = "image" office_id=request.POST.get("office") office=Office.objects.get(id=office_id) try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=2) user.staffs.address=address user.staffs.phone=phone user.staffs.image=image user.staffs.office_id=office user.save() messages.success(request, "Staff Added Successfully!") return render(request, 'admin_template/add_staff.html') My models class Staffs(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.CharField(max_length=255, blank=True) phone = models.CharField(blank=True,max_length=20) image = models.ImageField(upload_to='uploads/user/',blank=True) office_id = models.ForeignKey(Office,on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() @receiver(post_save,sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Staffs.objects.create(admin=instance) @receiver(post_save, sender=CustomUser) def save_user_profile(sender, instance,**kwargs): if instance.user_type == 1: instance.adminhod.save() if instance.user_type == 2: instance.staffs.save() -
How to store private documents in Django on production?
What is the typical scenario of storing private files in Django on production server? I wanted to use the django-storerages package - S3 bucket, but unfortunately after integration it turned out that private files cannot be stored for more than a week. (AWS_QUERYSTRING_EXPIRE - the given X-Amz-Expires must be less than 604800 seconds). But I need to store them for the user indefinitely. How can such files be stored in a remote cloud? -
How to solve the error "Executable path is not absolute, ignoring:"
I'm currently developing an application in Amazon Linux2 using Django, Nginx, Gunicorn, and Postgresql. I have created and configured a system file for Gunicorn to work when the OS boots, But after starting gunicorn I get the following error... Jun 08 18:18:04 ip-172-31-16-86.us-east-2.compute.internal systemd[1]: [/etc/systemd/system/gunicorn.service:10] Executable path is not absolute, ignoring: gunicorn --access-logfile - --workers 3 --bind unix:/home/myname/django_project/django_project.sock ...... Jun 08 18:18:04 ip-172-31-16-86.us-east-2.compute.internal systemd[1]: gunicorn.service lacks both ExecStart= and ExecStop= setting. Refusing. I'm sure the absolute path specified in the file is correct, but I get the error. How could I solve this problem? *NOTE: Amazon Linux2 doesn't include www-data groups, so I created using groupadd command. gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=myname Group=www-data WorkingDirectory=/home/myname/django_project ExecStart=/home/myname/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myname/django_project/django_project.sock django_project.wsgi:application [Install] WantedBy=multi-user.target Directory structure home │ └─myname │ ├─django_project │ ├─django_project │ ├─manage.py │ └─django_project.sock │ └─venv └─bin └─gunicorn OS Amazon Linux2 gunicorn 20.1.0 boto 2.49.0 Django 3.2.4 django-ses 2.0.0