Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have error in Django project when I deploy to elastic beanstalk everything is ok but when I go to my server it gives me internal server error
I need help with my Django project when I deploy to elastic beanstalk everything is ok but when I go to my server it gives me an internal server error I do not know where the error is because everything looks fine here is my server and my code settings.py import os from json.tool import main from pathlib import Path # from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent from datetime import timedelta # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-jkkab)y!n*=e1w9w%1939+cqkj0-_cm(evbc65&-s%qede_9z&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['roshbaw-env.eba-f9y6i6ns.us-west-2.elasticbeanstalk.com'] # Application definition INSTALLED_APPS = [ 'main', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework_simplejwt.token_blacklist' # 'storages', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'new_lms.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'new_lms.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'RBCLASSDBEB', 'USER': 'admin', 'PASSWORD':'12341234', 'HOST':'mydb.caw7sl9jtojs.us-west-2.rds.amazonaws.com', 'PORT':'3306', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
To fix them run 'python manage.py makemigrations --merge
Actually I've created some tables foe employee management system like Employeedetails,intern details,department,designations,teams,etc.. with Django Rest Framework .I've also migrated it in Mysql database and have created all needs of serializers and views and urls required. the urls also running perfectly in my localhost machine. But when it sent to deployment to the server, my DevOps team keeps running an error in Docker as shown below. I even merged the migration as per the error shown, still my system shows "No conflicts detected to merge". Somebody help me out from this Head Scratching. This is the error thrown, I dont know which code to attach here because everything works fine in my laptop, that's why I attached the error message #8 20.76 [notice] A new release of pip available: 22.2.2 -> 22.3.1 #8 20.76 [notice] To update, run: pip install --upgrade pip #8 21.53 CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0003_remove_employee_team_id_employeedetails_team_id_and_more, 0006_alter_employeedetails_created_at_and_more in EmployeeDetails). #8 21.53 To fix them run 'python manage.py makemigrations --merge' -
How to select row by distinct column and max datetime?
Trying to get the last records I inserted in database based on DateTime and distinct column SocialMedia_ID but I get the following error DISTINCT ON fields is not supported by this database backend when it reaches to the below line: accountsTwitter = StatsTwitter.objects.all().order_by('DateTime').distinct('SocialMedia_id') I want to mention that below SQL query is working, and I need to convert it to django. SELECT * FROM stats_Twitter WHERE DateTime IN (SELECT MAX(DateTime) FROM stats_Twitter GROUP BY SocialMedia_ID) -
(django) razorpayx webhook receiving empty queryset instead of any payload
this is my webhook url i am using ngrok service for this https://061c-103-223-8-94.in.ngrok.io/intg/rzpwhook/ when i try to change any payout status. i am getting empty queryset instead of any payload this is my view == @csrf_exempt def RazorWebhook(request): print('webhook alert=============',request.POST) return render(request,'intg/rzpweebhook.html') in terminal what i got : is there anything that i am missing ? -
Django - separate serializer data in single call
I have an API call to create a customer in my system. But my customer data is divided in 2 tables for reasons. class BaseUser(AbstractUser): email = models.EmailField(max_length=255, unique=True) phone_number = models.CharField() profile_img = models.ImageField() class Customer(models.Model): user = models.OneToOneField(BaseUser) first_name = models.CharField() middle_name = models.CharField() last_name = models.CharField() dob = models.DateField place_of_birth = CountryField I receive all the data in a single call and want to use the DRF serializer to create both instances with some added actions to each record after being created. Is there a way to give a set of request data to 1 serializer and another set to the other serializer? -
Service Django is not running container
I try to debug an app inside of the container and I need to run django to run tests I do that by: docker-compose exec django bash But as a result I get: service "django" is not running container #1 I don't really understand what this response means and I didn't find any information regarding that. This issue prevents me from being able to debug a code inside of the container with the database up and running. -
Django REST framework - Edit data if there is such a record, create - if not
I'm new to DRF, writing an api for later use in Vue.js . Help me understand how to make it so that when adding a nomenclature, he checks if there is one, and if there is, he edits the quantity by adding to the previous quantity. I am also interested in the question of how, when adding changes to the nomenclature, the number of positions taken was subtracted from the current number of nomenclature. Is it possible to do this by means of DRF or is it possible to implement it in Vue.js, checking and sending POST/PUT requests depending on whether there is or not? My models.py: class Nomenclature(models.Model): nameNom = models.CharField(max_length=150,verbose_name = "Название номеклатуры") numNom = models.CharField(max_length=50,verbose_name = "Номер номеклатуры",primary_key=True) quantity = models.IntegerField(verbose_name="Количество") numPolk = models.CharField(max_length=150,verbose_name = "Номер полки/места") class Changes(models.Model): numNomenclature = models.ForeignKey(Nomenclature, on_delete=models.CASCADE,related_name="chamges") quantity = models.IntegerField(verbose_name="Количество") location = models.CharField(max_length=50,verbose_name = "Место установки") fullname = models.CharField(max_length=150,verbose_name = "ФИО") appointment = models.CharField(max_length=50,verbose_name = "Назначение") def __str__(self): return '%s: %d,%s,%s' % ( self.fullname,self.quantity, self.location, self.appointment) My serializers.py class CheckSerializer(serializers.ModelSerializer): class Meta: model = Changes fields = '__all__' class NumSerializer(serializers.ModelSerializer): chamges = serializers.StringRelatedField(many=True) class Meta: model = Nomenclature fields = ('numNom','nameNom','quantity','numPolk','chamges') My views.py: class CreateNumList(ModelViewSet): queryset = Nomenclature.objects.all() serializer_class = serializers.NumSerializer … -
Initialize django Point in queryset annotate
I have a model with latitude and longitude as DecimalFields. I am trying them to Point instance of postgisand then transform to reqd CRS. I have written the queryset for that but I am getting the following error: TypeError: Invalid parameters given for Point initialization. Queryset list(Geo.objects.filter().values("latitude", "longitude").annotate(float_long=ExpressionWrapper(F('longitude'), output_field=FloatField()), float_lat=ExpressionWrapper(F('latitude'), output_field=FloatField())).annotate(wgs_84=Transform(Point(F('float_long'), F('float_lat'), srid=srid), 4236) )) Here I am trying to add a value wgs_84 which will be the transformed value in wgs84 system. The error I am getting is related to passing F('float_long'), F('float_lat') as params to Point. How can I rectify this error? -
How do I implement a plus/minus function in django forms
how do i implement this in django-form? 2/3: 2 is current picked amount of item, 3 is maximum This form does not work with the model, it will send data after clicking to the redis server -
How can I download this file and copy it into my directory path?
This is what I get as a response from the api : "{\"url\":\"https://thecloud-result.s3.amazonaws.com/2022-11-10/1638463716789.mp3\"}" My view: class ListUserSearchView(APIView): def get(self, request, link): url = config('BASE_URL') querystring = {"track_url": f'{link}'} headers = { "X-RapidAPI-Key": config('API_KEY'), "X-RapidAPI-Host": config('API_HOST') } response = requests.request("GET", url, headers=headers, params=querystring) data = response.text return Response(data) My directory path: def user_directory_path(filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> if locally return f'{filename}' what is the best way to do it ? So far I only managed to store a file that has the url inside, but I would like to store is as an audio file. Got the media file settings set up already. -
Django multitenant site with different login page for some tenants?
We want to create a multitenant website in Django but I want to have for some tenants different (HTML) login page. How to do that? I am not a Django master but when reading about Django tenants application I thought we can use middleware or a custom tenant-aware loader for finding and loading Django templates or urlpatterns I was thinking of using urlpatters in such way that the path for login would be dependent on the current tenant. urlpatterns = [ path('login/', login.currenttenant_login.urls), path('', home, name='home'), ] Is that possible. Note that only some of the tenants could have different login page. -
Django Rest Framework - Create Form in the backend? [closed]
I work on Django app, I need to create form which contain fields such as f_name, l_name, ..., etc. and send this form to user through email. there is way to create this form in backend? or which best practice to do that? I tried to create this form in the backend, but I'm not sure if that best practice or not. -
How the login, authentication, tokens works? if a user login to any application and till he logout how the requests know that the user is logged in
I'm just trying to make a small ecommerce web application by using Django, Django Rest Framework, I completed registration and login views(not used Django inbuilt authentication) just saving the users information in database and validating those details when the user login, now I'm confused that how actually login works, how the user stay connected till he log out, how the server knows that the user is still logged in, how each request knows that the user is already logged in, Once I tried login by using Django OAuth token, also simple JWT tokens, but when I used to login along with the username and password I also send the token from the postman, but users doesn't login through postman in real world, then how the tokens are handled, who passes the tokens along with the parameters while login, how tokens are passed along with the credentials in real projects, how all these handled in real projects, also what happens when user clicks on logout, what will happen in the backend when user clicks on logout, can anyone please clear this question Thanks. Please help me understanding of this concept -
How I can use one js code of a django template for different content
I am working on a web application using Django I have faced one problem in that and that's I wrote one html template in Django and in that template I also has been written the code of js for that template. I want to use that js code for all the different kinds of content that is represented using that template in the front of the user.but that js code is not working for all kinds of content similarly. Problem in brief I am making a commerical web application for a Project like amazon.in and flipkart.com and I have writen a template for a product view page for all kinds of Product that is shown using that template. I has been made a button in that product view page template. Button is Add to Cart and I have written JavaScript code in that template for add to Cart button to store the product in the cart when the user click the button. I made my cart using LocalStorage and i will store the products in it. but the problem is when I initialzed my site and click on the product and goes to the product view page and click to … -
How to add a model instance (not from db) to queryset
Let's say I have a model called Schools. And also I have a Schools instance that I don't want to store in my database. temp_school = Schools(school_id='temp_1') Also I have all schools schools = Schools.objects.all() Now, how can I add my temp_school to the schools, so that I can use it as my new queryset in my view? -
How to add an extra field in auth user model in django admin?
I want to customize my existing auth user model. I need the command or code for executing the solution? -
in vuejs styling ag-grid's cell data
what am I doing is combine some key value pairs and bold the value in that pair and put it in ag-grid rowData , my problem is bold() method adds the tag to that value it is not getting bold -
Saving a toogle switch value in Django
Hi I am just trying to save a toggle switch value onclick to save to a Boolean field in Django home.html <style> .home-container{ display:grid; grid-template-columns: 1fr 4fr; } .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } </style> <div> <label class="switch"> ** <input type="checkbox" checked>** <span class="slider round"></span> </label> </div> models.py is_active = models.BooleanField(default=False) urls.py path('engine/', views.engine, name="engine"), I tried several suggestions on the web but could not make it work as I am new to development. I know I need to use javascript. Please help write my views.py and javascript in home.html. -
How to search whether a value is present in a list of values in Django
In my model a list of values is stored. Now a user can enter a list of values and if any of the values is present in the table then that record should be fetched. For e.g. a user enters [3, 63, 2, 5]. Now suppose the list that is present in the table has values [65, 5, 8, 48]. Since the input list which is [3, 63, 2, 5] has got a common value which is 5 in this case I should get this record. This is the column which is present in my model. The model name is Room. room_number = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) I don't understand how I can do this. Can someone please help me with this? I can get an individual value and run a for loop for every value present in the input list. but I don't understand how I can search whether a given value is present in the list. -
How i can split a Email in Django
Good morning I've been sitting for 5 hours on what should be a simple problem. I would be grateful if you could end my suffering. It is about a dashboard page. I want the user to be greeted with his name (Hello, ....) after he has registered with his email address. When registering, the email address is always the same, name.example@hotmail.de. I want to split the email address and display only the name, but I can only manage to display the whole email address. view.py @login_required(login_url='login') def Example_dashboard(request): form = MembersForm() current_user = request.user #current_user.split is not working! context = {'form': form, "cunrrent_user": current_user} return render(request, 'example_dashboard.html', context) html <p>Welcome, {{ current_user}} </p> <form action='' method='POST'> {%csrf_token%} {{ form }} models.py class Members(models.Model): email = models.CharField(max_length=200, null=True) passwort = models.CharField(max_length=200, null=True) forms.py class MembersForm(ModelForm): class Meta: model = Members fields = ["studiengang", "kategorien"] -
Passing value from a form to get method in django
I want to pass the value in the comment text area when the a tag is clicked.Is there any other methods to pass both the comment and rating into the get method.I saw some similar questions but the answers where suggesting to use hidden input field to pass the value.But in my case i want the rating number in the clicked tag too.so i won't be able to use the hidden input method. <form method='post'> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Review</h4><br> <div > <textarea class="textarea p-3 w-100" placeholder="Write a review" cols = "40" rows="5"></textarea> {{form.comment}} </div> </div> </div> </div> </div> <div class="container-fluid py-4"> <div class="row"> <div class="col-lg-6 mx-auto mb-lg-0 mb-4"> <div class="card"> <div class="card-body p-4"> <h4 class="font-weight-bolder">Rating</h4><br> <div class="rating rating2"> <a href="{% url 'ratings' 5 id %}" title="Give 5 stars" data-value="5" type="submit">★</a> <a href="{% url 'ratings' 4 id %}" title="Give 4 stars" data-value="4" type="submit">★</a> <a href="{% url 'ratings' 3 id %}" title="Give 3 stars" data-value="3" type="submit">★</a> <a href="{% url 'ratings' 2 id %}" title="Give 2 stars" data-value="2" type="submit">★</a> <a href="{% url 'ratings' 1 id %}" title="Give 1 star" data-value="1" type="submit">★ </a> </div> </div> </div> </div> </div> </div> </form> -
Django models with key and multiple value choices
im trying to work my way into making an api oriented webapp with Django and i wanted to create a model where i can choose a day and a time for that day. So my first thought was to make a model with an atttibute that can stored set day with a set time, this last one being of multiple choice, like a dictionary or something. My motive is to save those values as attributes in my DB but i dont really know if thats possible! Thx a lot beforehand. Something like this came to my mind: class Reservation(models.Model): reservation = ({'monday':[10,11,12,13,14,15,16,17], 'tusday':[10,11,12,13,14,15,16,17], 'friday':[10,11,12,13,14,15,16,17]}) -
DRF Swagger - Endpoint parameter doesn't match the Serializer
So I'm trying to create at REST API using DRF and Swagger for API Documentation, But I notice that Swagger UI Parameter doesn't match the given Serializer. MailSerializer.py ` from main.BusinessLayer.Model.Mails import Mails from rest_framework import serializers class MailSerializer(serializers.Serializer): class Meta: model = Mails fields = '__all__' # Mail Properties Subject = serializers.CharField(max_length = 30, allow_blank = False) Sender = serializers.CharField(max_length = 30, allow_blank = False) Recipients = serializers.CharField(allow_blank = False) ReplyToAddress = serializers.CharField(max_length = 30) Importance = serializers.CharField(max_length = 30, allow_blank = False) ApplicationId = serializers.CharField(max_length = 30, allow_blank = False) # Mail Content Body = serializers.CharField(allow_blank = False) Attachments = serializers.CharField(allow_blank = False) # Other Parameters UseDefaultHeader = serializers.IntegerField(default = 0) UseDefaultFooter = serializers.IntegerField(default = 0) def create(self, validated_data): return Mails.objects.create(**validated_data) ` @swagger_auto_schema( operation_description="", operation_summary="create a mail", request_body=MailSerializer ) def create(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response({ 'code': 200, 'success': True, 'message': '%s successfully created.' % (OBJECT_NAME), 'data': [] }, status= status.HTTP_200_OK) I tried to use @swagger_auto_schema and a request_body parameters, but still not working -
old_field = model_state.fields.pop(self.name) KeyError: when migrations
I got this error $python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/<int:pk>/edit' [name='line-bot-edit'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. shared_models.ScenarioTemplate.user_types: (fields.W340) null has no effect on ManyToManyField. Traceback (most recent call last): File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 29, in <module> main() File "/Users/whitebear/MyCode/httproot/nice_cdk/cinema-admin/manage.py", line 25, in main execute_from_command_line(sys.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py", line 149, in handle loader.project_state(), File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "/Users/whitebear/.local/share/virtualenvs/cinema-admin-mg9y4sUV/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 162, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'is_year_set' even $python manage.py migrate shows the same error. The checks I have done. $python manage.py showmigrations Every migrations are applied, but I have done python manage.py migrate --fake before error happens. in models.py is_year_set is … -
Im trying to download a file and i need to send option to my Django view from js script . Please advice
My HTML page looks something like below: The post function used is for upload the file with edited data..! Im trying to get the option value from HTML page to my Django view. <div><h3 style="text-align: center">Bulk Upload</h3></div> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="col-md-4"> <select class="form-select form-control" style="padding: 3px; border-radius: 1px;" id="option" name="option"> <option selected value="0"> Please select operation</option> <option value="1">Insert New Source Client</option> <option value="2">Update Volcker Attribute</option> </select> </div> <div class="col-md-2"> {% csrf_token %} <button id="downloadBtn" type="submit" title="Download CSV Template" onclick="export_template()" class="btn btn-primary" style="height: 34px; width: 100px" > Download </button> </div> My javascript function is defined as below: function export_template(){ let option = document.getElementById('option').value; console.log(option) if (option!=""){ window.location.href="export_template/option="+option; } } The view defined is as below where im trying to fetch "option" from JS script please advice def export_template(request, post): #option = int(request.POST.get("option")) option = int(request.POST.get("option")) if option == 2: file = open('C:/Users/Desktop/New Project (2) (1)/New Project/uploadcsv/media/bulk_upload/Update_Client_YYYYMMDD.csv', 'r') response = HttpResponse(file, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=Update__YYYYMMDD.csv' return response How to pass JS script value as parameter to my Django view..!`