Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: query of a foreign key of a foreign key
This might be stupid question and I am sure that there is a basic query for this situation, but I don't seem to get a hang of it and Google turned out to be a miss for solution. I have models: Project, primary key=project_no; Under project there are product_config models, primary key=id; Under each product_config there is a pre_config model, primary key=product_id; Under each pre_config there is a list of sub_config models, primary key=id; Now I am loading a page for project details and I pass a project_no and make a query for all product_configs: project.objects.get(project_no=project_no) product_config.objects.filter(project_no=project_no) Now I want to create a table for the list of sub_configs according to pre_config under product_config. In a shell I can query the list with: sub_config.objects.filter(product_id=product_id) How I can pass the product_id of pre_config from my product_config to query all the sub_configs? -
DJANGO: Running SQL query using cursor in project.settings.py file
In my project, I have made some setting fields within the "settings.py" file configurable by exposing them to the user via an environment file. So the user can modify the values on the .env file, and that is then used to update the setting fields within the main project settings.py file. I want to improve this by migrating some of this values to the database, so users can set their values interactively via the product's UI instead of having to modify the .env. I have taken the following approach: After the default database has been declared in the DATABASES dictionary, I isntantiate a connection.cursor() to run a raw SQL query that retrieves the settings from the database, as described in the documentation. I manipulate the results of the cursor to construct a dictionary in which keys are setting identifiers and values are the relevant values from the database, as set by the user. This dictionary is then used to assign the appropriate value to each Django setting variable (i.e. SESSION_COOKIE_AGE, MEDIA_ROOT, etc.). So at each setting variable instead of doing a getenv, I retrieve the value from the dictionary using the relevant key. I have observed the code's behavior within … -
Insert Html table to MySQL - DJANGO
i have HTML table like that : (a lot of stores that i entered myself) <form method="post" ,action="#"> {% csrf_token %} <table class="table" dir="rtl"> <thead> <tr> <th scope="col">store name</th> <th scope="col">Address</th> <th scope="col">phone-number</th> <th scope="col">Opening hours</th> <th scope="col">Navigate</th> </tr> </thead> <tr> <th scope="row">food store </th> <td>dsdadad</td> <td>03-6040242</td> <td>Monday to Saturday, 14:30-18:00</td> <td><a href="</a></td> </tr> . . . . . and a lot more rows How can i insert that table to MySQL database ? -
Recursively navigating through dictionnary in django template
I have a dictionnary of unknown depth which I want to display in my Django template. This dictionnary represents the structure of the subfolders inside of a folder. My goal is to display it with the parent subfolders before their children, which would be indented to show that they're children of that folder. So to explain with an example, if I have the following dictionnary : {'Script Hello': {'Script Hello World': {'Script Hello World 2': None, 'Script Hello World 3': None}}, 'Script Hello World 4': None, 'Script Hello World 5': {'Script Hello World 6': None}} I want it to be displayed like this : . Script Hello . Script Hello World . Script Hello World 2 . Script Hello World 3 . Script Hello World 4 . Script Hello World 5 . Script Hello World 6 I've done a small code that does the job if the depth if at most 3 (to determine what I really wanted), but couldn't find a way to make it recursive. My code is this : {% for key, values in list.items %} <li> {{ key }} <ul> {% for key,values in values.items %} <li>{{ key }}</li> <ul> {% for key,values in values.items %} … -
Django celery .delay() in requests get stucked
I have a project running on 3 different environments, on 2 environments it works on production for some reason stopped working (was working before). The code is pretty simple I have a view which runs a task in delay and should return immediately some message to the user: class PrintTaskView(View): def get(self, request): logger.debug('ABOUT TO ADD A TASK') tasks.print_task.delay() logger.debug('TASK WAS ADDED') messages.info(request, _('Print task added to queue')) return HttpResponseRedirect(reverse_lazy('admin:index')) I am so confused because this works smooth on my local machine and on the test environment while on production request gets stuck on loading after the first log has been executed. What is even more confusing is that if I run the code from the shell (manage.py shell) then the print task gets created and picked up by a worker and executed. Also celery beat tasks runs smoothly. My celery settings: # Celery CELERY_BROKER_URL = os.getenv('CELERY_BROKER_URL') CELERY_RESULT_BACKEND = os.getenv('CELERY_RESULT_BACKEND') CELERY_BEAT_SCHEDULE = { ... } website/__init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import from celery import Celery from django.conf import settings app = Celery('somename') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, related_name='tasks') Any idea or suggestion is more than welcome :) -
mp4 Upload To S3 from external S3 location or presigned url | DJANGO
Currently my client is sending me presigned url and public S3 location of a mp4 video. below is the format { "URL": "https://brytecam-bucket-1.amazonaws.com/video-url", "location": "s3://brytecam-bucket-1/movies/video.mp4" } If I open the URL in browser, it streams the video. I need to transfer this file to my s3 bucket to store it. I need to know is there any way to transfer this mp4 file to my s3 bucket by using any of means i.e S3 location or URL using django. -
getting error Authentication credentials were not provided in django rest framework
Hi Everyone i am creating login api in DRF and getting response also as i expected but i test token to other api then got error Authentication credentials were not provided, i don't know where i am going wrong please help me out.also custom user model can't possible to use because that model i have already used setting.py- this is setting file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_datatables.renderers.DatatablesRenderer', ), 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination', 'PAGE_SIZE': 100, } models.py class GmsUser(GmsBaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) user_name=models.CharField(max_length=255,null=True, blank=True, unique=True) password=models.CharField(max_length=255,null=True, blank=True) token = models.CharField(max_length=255, null=True) class Meta: db_table = "gms_users" def __str__(self): return self.user_name views.py @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def gms_user_login(request): user_name = request.data.get("user_name") password = request.data.get("password") users=GmsUser.objects.filter(user_name=user_name).values_list('id',flat=True) role=GmsRole.objects.filter(id=GmsUserRole.objects.filter(user=users[0]).values_list('role',flat=True)[0]).values_list('role',flat=True)[0] # city=GmsUserProfile.objects.filter(user=users[0]).values_list('city',flat=True)[0] try: query=GmsUserRole.objects.filter(user=users[0]).exists() except Exception as e: return Response({"message":"User not found","error":True,"code":400,"results":str(e)},status=HTTP_400_BAD_REQUEST) if user_name is None or password is None: return Response({'detail': 'Please provide both username and password'}) else: try: if query: user = GmsUser.objects.get(user_name=user_name) except GmsUser.DoesNotExist: return Response({'detail': 'Invalid UserName'}) if user.password.lower() != password.lower(): return Response({'detail': 'Invalid Password'}) user.token=get_random_string(length=50) user.save() response_data=GmsUserSignupSerializer(user).data response_data1=GmsRoleSerializer(GmsRole.objects.get(role=role)).data response_data2=GmsUserProfileSerializer(GmsUserProfile.objects.get(user=users[0])).data response_data['roles']=response_data1 response_data['user_profile']=response_data2 try: return JsonResponse({"message": "login","error":False,"code":200,"results":{'token':user.token,'user':response_data}},status=HTTP_200_OK) except Exception as e: return JsonResponse({"message": "login","error":True,"code":500,"results":str(e)},status=HTTP_200_OK) Login api Response { "message": … -
"Method \"GET\" not allowed." Django
my views.py file: from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer class TestView(APIView): def get(self, request, format=None): print("API called") return Response("You did it!", status=200) class UserView(APIView): def post(self, request, format=None): print("User created") user_data = request.data print(request.data) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(raise_exception=False): user_serializer.save() return Response({'user': user_serializer.data}, status=200) return Response({'msg': "error: no user created"}, status=400) # convert user token to user data def get(self, request, format=None): if request.user.is_authenticated == False or request.user.is_active == False: return Response('Invalid credentials', status=403) user = UserSerializer(request.user) print(user.data) return Response("Testing", status=200) my serializers.py file: from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework.settings import api_settings class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( required=True, max_length=32, validators=[UniqueValidator(queryset=User.objects.all())] ) first_name = serializers.CharField( required=True, max_length=32 ) last_name = serializers.CharField( required=True, max_length=32 ) password = serializers.CharField( required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop(password, None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model = User fields = ( 'token', 'username', 'password', 'first_name', 'last_name', 'email', 'id' ) my urls.py file: from django.urls … -
django admin Inline model is not storing id for related table
I've combine two models into one in admin panel using admin.TabularInline and following is my code that i've tried as far my knowledge. class ProdutImageTabulurInline(admin.TabularInline): model = ProductImage exclude = ['user', 'name', 'status'] @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ ProdutImageTabulurInline ] # For Do operation before save operation def save_model(self, request, obj, form, change): obj.user = request.user return super().save_model(request, obj, form, change) # https://stackoverflow.com/questions/59580458/how-can-i-access-model-instance-in-save-related-method-of-modeladmin-class def save_related(self, request, form, formsets, change): obj = form.instance obj.user = request.user super(ProductAdmin, self).save_related(request, form, formsets, change) I've hidden the User field from ProductImages since i want that it should store default user id as logged in user id. So i used save_model for product table and it store user_id as expected but i want that in products image table too, and which is not working -
Correct way to deactive user and its profile in Django
I have created a view where the logged-in user should be able to deactivate its profile. I expect then to see the change being reflected in my admin section, but it's not. Looks like the user is being deactivated but the user.profile isn't. I am puzzled since, after I did a whole project following Django docs, the way to properly manage user deactivation seems missing. I'd like to stay strict to Class-Based-Views. My actual code: # models.py # Model to handle user profiles class Profile(models.Model): """Create user profiles and manage their attributes""" user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=180, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to='social/static/social/avatars/', null=True, blank=True) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False, blank=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.username # Signal function to create a profile when a user is created @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() # views.py class ProfileInactive(View): """User can made its profile unactive""" model = models.Profile template_name = 'social/profile_delete.html' # Users can delete only their profile, or get a 404 error def get_queryset(self): owner = self.request.user return self.model.objects.filter(user=owner) def get(self, request, username): profile = get_object_or_404(models.Profile, user__username=self.kwargs['username']) return render(request, self.template_name, {'profile': profile}) def … -
Django + GUnicorn ASGI with SCRIPT_NAME
I have a django application running with a gunicorn ASGI server and a NGINX reverse proxy for serving static content. All packaged within a docker container. Now I want to serve this container behind a reverse proxy with a path prefix, e.g. "mydomain.com/djangoapp/". The problem is, that django doesn't know it's hosted under a subpath and for example the django admin application then aleays redirects to the root path "/" instead of "/djangoapp/". I already read that there are several settings which handle this problem. I tried setting the "FORCE_SCRIPT_NAME" in the django settings directly to "/djangoapp". It worked for the admin login page, but after clicking the login button it redirected to the wrong root "/". I tried setting the "SCRIPT_NAME" environment variable of the gunicorn server to "/djangoapp". It did not apply at all. I'm running now out of ideas what else to try. Does anybody else have a solution for this problem? -
Django:all instances have the same many-to-many field
I have custom user model, and this user has many-to-many field called classes. When the user creates new class I add it to the many-to-many field classes . But the problem is ,not only this user points to added classes but all users created, point to the same classes. How can I organize models such that a when I add class_instance to many-to-many field classes of single user, only this user has those classes. Here is my code models.py class Class (models.Model): key=models.CharField(max_length=256,unique=True); name=models.CharField(max_length=256); def __str__(self): return self.name; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name views.py @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def create_class(request): instance=NewUser.objects.all().filter(id=request.user.id) #getting the user from request(I want only this user to have the added class_instance) serializer=ClassSerializer(data=request.data); if serializer.is_valid(): class_instance=serializer.save(); class_instance.save(); instance[0].classes.add(class_instance); #adding the created class to many-to-many class field instance[0].save(); data={ 'id':instance.id } return JsonResponse(data) -
MySql django.db.utils.OperationalError: (1045, "Access denied for user 'userdb'@'localhost' (using password: YES)")
when I used command "python manage.py runserver ,it threw this error.And then I checked the authority of the users. -
Django DRF gettiing ValueError: Field 'id' expected a number but got 'test' error
I am trying to implement a filtering feature in my Django app. I am using DRF and I am getting the following error when I click on any option in my html template: ValueError: Field 'id' expected a number but got 'test'. I was following this post to create this page but I am not sure how to get rid of error. I tried to change the default in my migration file but it didn't help. When I change values_list('client_type__title') to values_list('client_type') everything is fine but it shows id instead of title. migration file class Migration(migrations.Migration): dependencies = [ ('testapp', '0007_team_publish'), ] operations = [ migrations.CreateModel( name='ClientType', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(default='-', help_text='max 150 characters', max_length=150)), ('body', models.CharField(default='-', help_text='max 400 characters', max_length=400, verbose_name='Description')), ('slug', models.SlugField(blank=True, default='')), ('publish', models.DateTimeField(default=django.utils.timezone.now, verbose_name='publish')), ], options={ 'ordering': ('-publish',), 'get_latest_by': 'publish', }, ), migrations.AddField( model_name='product', name='client_type', field=models.ManyToManyField(blank=True, related_name='client_type_product', to='testapp.ClientType', default='-'), ), ] models.py class ClientType(models.Model): title = models.CharField(max_length=150, default='-', blank=False, null=False, help_text='max 150 characters') body = models.CharField(verbose_name ='Description', max_length=400, default='-', blank=False, null=False, help_text='max 400 characters') slug = models.SlugField(default='', blank=True) publish = models.DateTimeField('publish', default=timezone.now) def __str__(self): return str(self.title) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField('title', max_length=400, blank=False, null=False, help_text='max 400 characters', default='') client_type … -
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! @0.1.0 serve: `vue-cli-service serve` npm ERR! vuedirectory@0.1.0 serve: `vue-cli-service serve`
I installed django with vuejs. i got this error: npm run serve > vuedirectory@0.1.0 serve djangoprojectdirectory/vuedirectory > vue-cli-service serve INFO Starting development server... ERROR TypeError: Cannot read property 'vuetify' of undefined TypeError: Cannot read property 'vuetify' of undefined at djangoprojectdirectory/vuedirectory/node_modules/vue-cli-plugin-vuetify/index.js:29:54 at djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/Service.js:268:40 at Array.forEach (<anonymous>) at Service.resolveChainableWebpackConfig (djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/Service.js:268:26) at Service.resolveWebpackConfig (djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/Service.js:272:48) at PluginAPI.resolveWebpackConfig (djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/PluginAPI.js:132:25) at serve (djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/commands/serve.js:75:31) at Service.run (djangoprojectdirectory/vuedirectory/node_modules/@vue/cli-service/lib/Service.js:262:12) at processTicksAndRejections (internal/process/task_queues.js:95:5) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! vuedirectory@0.1.0 serve: `vue-cli-service serve` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the vuedirectory@0.1.0 serve script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /root/.npm/_logs/2022-05-24T11_16_58_764Z-debug.log -
Django cache database value in view function
I'm making an app that allows user to capture Google Sheet as image and send it into our company's chat service as an alert. So I save google sheet api credentials in database, and when user clicks "Run" button in web UI, it triggers an ajax request which runs a function in views.py to start capturing. If the credentials expire, this function will refresh to get new credentials and update new values in database. But the problem is that when old credentials expires and is replaced by new credentials, function in view.py still use old credentials in database so it failed because wrong credentials. I have a main app called ggchat. I use docker, gunicorn, nginx and celery to deploy this app. My function in views.py: ... from lib.custom import capture_gs @login_required(login_url='/accounts/login/') def run_task(request): task_id = request.GET.get('task_id', None) capture_gs(task_id) ... The function capture_gs is a local package that get or update credential from database and capture google sheet as image. Below is the code for this package: from __future__ import print_function import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials import pandas as pd import numpy as np import requests from … -
Django Cripsy Form - "This field is required" - shows on load
When the page loads I am seeing the error of - "This field is required" with the input form 'Title' highlighted with the red board. I would expect that this should only show after the Save button is pressed. I can toggle the message on and off with self.helper.form_tag but the behavior seems incorrect to me, it seems as though it is trying to submit before I click save. Am I doing something wrong or is this expected behavior? If it is expected is there a way to change it to only show the warnings after Save? forms.py from django import forms from .models import Request, RequestDocument from crispy_forms.helper import FormHelper from crispy_forms.layout import Field, Div, Layout class RequestForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'title'})) rfp_No = forms.CharField(widget=forms.TextInput(attrs={}), required=False) company_Name = forms.CharField(widget=forms.TextInput(attrs={}), required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() #self.helper.form_tag = False self.helper.help_text_inline = True self.helper.layout = Layout( Div(Field('title'), css_class='col-md-12', ), Div( Div(Field('rfp_No'), css_class='col-md-6', ), Div(Field('company_Name'), css_class='col-md-6', ), css_class='row', ), ) create.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {% crispy form %} <button type="submit" class=" d-block btn btn-lg btn-success mt-4 w-50 mx-auto"> Save </button> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script … -
AttributeError: 'Request' object has no attribute 'DELETE'
I am trying to add permission for deleting an object. views.py class DeleteView(APIView): permission_classes = [IsAllowedDelete] def delete(self, request, id): obj = Mymodel.objects.get(id=id) obj.delete() return Response({"detail" : "Deleted successfully"}, status.HTTP_204_NO_CONTENT) urls.py path('remove/<int:id>', vm.DeleteView.as_view(), name='delete_view'), permissions.py class IsAllowedDelete(permissions.BasePermission): def has_permission(self, request, view): if request.method == "DELETE": print('id : ',request.DELETE["id"]) return True else: return False But I am getting the below error:- AttributeError: 'Request' object has no attribute 'DELETE' at below statement:- request.DELETE["id"] Please help me to fix this. -
transaction.atomic celery task
I have transaction.atomic celery task: @app.task( name="create_order", bind=True, ignore_results=True, ) @transaction.atomic def create_order(self: Task) -> None: try: data = MyModel.objects.select(...) # Some actions that may take long time and only use DB for SELECT queries make_order(data, ...) except SomeException as exc: raise self.retry(exc=exc, countdown=5) else: data.status = DONE data.save() @transaction.atomic decorator creates new connection with DB and holds it before any exception or COMMIT statement. But what if task raises self.retry? Connection will be closed and when the task retries django will open a new one? -
How to exclude certain DateField and CharFields in IF statement?
I'm very new to Django, being a C guy (embedded/Linux) for the most part, so I apologize for my ignorance. I've tried searching for this exact problem with no luck. I have a Django project in which I have forms. When the form is not nullable, I want to put an asterisk in the visible name so that an end user knows it is mandatory to fill in Hence, we created the following code: # we need to add a * to the label if the fields are not nullable model = self.Meta.model nullable_fields = [f.name for f in model._meta.get_fields() if f.null] for visible in self.visible_fields(): # if the field is not nullable add an asterix, # that is if the label doesn't already have one for some arbitrary reason if visible.name not in nullable_fields and not visible.label.endswith("*"): visible.label = visible.label + ' *' Now, this is working fine for most of my models. However, for certain fields which are presented as nullable still an asterisk is added (FK). Please see these models: class BU(SoftDeleteObject, models.Model): class Meta: verbose_name_plural = "Business Units" users = models.ManyToManyField( 'User', blank=True, verbose_name="Gebruikers met toegang", through='UserBu', related_name='users') class EmailTemplate(SoftDeleteObject, models.Model): cc = models.ManyToManyField( Group, related_name='cc', … -
Performing git pull operation from a django view
I am trying to perform a git pull operation when a django view is called inside the view. cmd = 'cd %s && git pull origin master' % dir_path process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() I get below error in stderr: fatal: unsafe repository ('/home/user/my_dir' is owned by someone else) To add an exception for this directory, call: git config --global --add safe.directory /home/user/my_dir I believe it is ownership related issue but not sure about the solution. It is currently running from django runserver. I have tried adding this directory to safe.directories git config --global --add safe.directory /home/user/my_dir but still see the same error -
when a certain time value comes from false back to true
I need to make it automatically when it comes leave_date(leaveted date) room_bool == True now it's all done via urls.py /get/by/<int:pk> views.py date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') reg = Registration.objects.get(rooms_id=pk) room = Rooms.objects.get(pk=pk) a = reg.leave_date.replace(tzinfo=None) >= datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').replace( tzinfo=None) if a != True: reg.room_bool = True reg.save() room.room_bool = True room.save() models.py room_num = models.IntegerField() room_bool = models.BooleanField(default=True) #if room_bool = True room is open, else closed. category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Room' #This class Registration for visitors, to open room for the them class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField() guest_count = models.IntegerField() def func(self): room = Rooms.objects.filter(room_bool=True) for i in room: if i.room_num == int(self.rooms): i.room_bool = False #this should change when adding new registration i.save() -
User() got an unexpected keyword argument 'profile_image' when creating user
i created a user registration form using from django.contrib.auth.models import User, auth but when i try to submit the form instead of creating a new user it's throws me an error like: TypeError at /register/ User() got an unexpected keyword argument 'profile_image' ? is anybody who know what's wrong with my code please ? the register template: <form action="{% url 'register' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Username</label> <input type="text" class="form-control" name="username"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">First Name</label> <input type="text" class="form-control" name="first_name"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Last Name</label> <input type="text" class="form-control" name="last_name"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Enter Your Email</label> <input type="email" class="form-control" name="email"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Password</label> <input type="password" class="form-control" name="password"> </div> <br> <div class="form-group"> <label style="font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Repeat Password</label> <input type="password" class="form-control" name="password2"> </div> <br> <div class="mb-3"> <label for="formFile" class="form-label">Profile Image</label> <input class="form-control" type="file" id="formFile" name="profile_image"> </div> <br> <a href="{% url 'login' %}" style="text-decoration: none; font-family: Arial, Helvetica, sans-serif; color: dodgerblue;">Already Have An Account</a> <br> <br> <button type="submit" class="btn btn-warning">Create</button> </form> the register view: … -
Facing ModuleNotFoundError: No module named 'django' on Apache and Django Setup
Need help and clear understanding on Django and Apache based environment setup. My setup information as follows: OS: Ubuntu 20.04 Apache2 configured with Virtual Host Django2.2 installed without sudo Python 3.8.10 Configuration from default-ssl.conf <IfModule mod_ssl.c> <VirtualHost *:443> WSGIScriptAlias /dynamic /var/project/module/wsgi.py WSGIApplicationGroup %{GLOBAL} ServerName localdev.test.com <Directory /var/www> AllowOverride None Require all granted </Directory> <Directory /var/project> AllowOverride None Require all granted </Directory> </VirtualHost> </IfModule> Now my issue is whenever I tried to access Django Admin component it throws following error in Apache error logs. [Tue May 24 04:45:17.726120 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] mod_wsgi (pid=12972): Failed to exec Python script file '/var/project/module/wsgi.py'. [Tue May 24 04:45:17.726169 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] mod_wsgi (pid=12972): Exception occurred processing WSGI script '/var/project/module/wsgi.py'. [Tue May 24 04:45:17.726247 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] Traceback (most recent call last): [Tue May 24 04:45:17.726274 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] File "/var/project/module/wsgi.py", line 16, in <module> [Tue May 24 04:45:17.726279 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] from django.core.wsgi import get_wsgi_application [Tue May 24 04:45:17.726297 2022] [wsgi:error] [pid 12972:tid 140147584620288] [client 103.179.111.50:54976] ModuleNotFoundError: No module named 'django' My setup does not use django virtual environment and also as mentioned above django … -
How to get the model default value after creating new, without call another get?
Is there any way to get default value (such as ID of type UUID) after creating a new row. Here is my model class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name= models.CharField(max_length=255) created_at = models.DateField(default=None, blank=True, null=True) class Meta: db_table="business" When I create I do this, for example from rest_framework import generics from django.forms.models import model_to_dict class Create(generics.CreateAPIView): def post(self, request) inputData = {"name":"abcdef", "created_at": datetime.datetime.now} employee = Employee.objects.create(**inputData) return JsonResponse(model_to_dict(employee), safe=False) Here is the response: { "name": "abcdef", "created_at": "2022-05-24T10:36:39.126", } So now I dont know what is the ID of the new row I just create