Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'id' expected a number but got 'prashant'
I'm trying to get value of user field from my employee model but it's showing above error.I would request your solution to this problem.I have mentioned my models.py & views.py for reference. models.py class Employee(models.Model): First_Name = models.CharField(max_length=200,blank=False,null=False) Last_Name = models.CharField(max_length=200) DOB = models.DateField() Primary_skill=models.TextField(max_length=1000) user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) Employee_Id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,unique=True) views.py def loginp(request): page ='login' if request.method=="POST": username = request.POST.get("Username") password = request.POST.get("Password") name = Employee.objects.get(user=username) context={'use':name} try: username = Employee.objects.get(username=1) except: messages.error(request,"Invalid Username") user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return render(request,'profile.html',context) else: messages.error(request,"Authentication Failed.Please Try again with correct credentials") context={'page':page} return render(request,'login.html',context) -
Can't get attribute 'ModelCreation' on <module '__main__
I have started to machine learning deployment using Django. I have successfully create a model and dump it using pickle file .I also dumbed Column Transformer. when I load these file in Django project column Transformer works fine but model file gives error like this . "Can't get attribute 'ModelCreation' on <module 'main" . I searched many places but I could not solve it . -
how to receive array of int's in django form modelmultiplechoicefield
here is my multiselect(vue js) value at template: .... <input type="hidden" name="related_parties" id="id_related_party" :value="[3]"> .... in the above code , :value is actually a vue js computed value , for simplicity using [3] .. in my django forms, my field is: ... related_parties = forms.ModelMultipleChoiceField( required=False, queryset=Party.objects.none()) ... in the Django form later I loop through the values received from template to create a list like below: ... for item in self.initial.get('related_parties'): "" if item.id: party_ids.append(item.id) ... afterwards i assign the queryset value in Django form like below: ... if party_ids: self.fields['related_parties'].queryset = Party.objects.filter(id__in=party_ids or None) else: self.fields['related_parties'].queryset = None ... this setup works great if its just :value="[3]" ,,, but in case of different values like "[3,2]", i end up getting validation error: "3,4" is not a valid value. do i have to use a different django field in django forms? how can i avoid the validation error in this case? -
React env could be dynamic with django?
Frontend: React Backend: django Description I use create-react-app For example, one of component is below # link is from .env <a href={link}></a> After React application is finished. I use npm run build So, link will always be same I want to thak link could be autmatically change to where I deployed on server e.g. # lab1 <a href="100.100.100.1"></a> # lab2 <a href="100.100.100.2"></a> This scenario happend if I doployed in lab1, lab2, lab3 ,labs all have their own ip. I need to change that IP in React application .env file and re-build again. So, if there are n labs, I need to re-build n times. Is this possible do not build anymore? -
Django request.data is giving wrong JSON
I send a request to the server with {"name" : "Robert"} but the request.data looks different. This works fine in runserver. But when used uwsgi in docker it gives something like, { "_content_type": "application/json", "_content": "{"name":"robert"}" } -
What is the best way to receiving data and polling it
My scenario is a webhook and a polling. Explaning... I have a view that receive a post with a json like {"status": "processing"}. And I need to make the value of this field available for another system polling the data. My idea is make a new endpoint for GET. But I no have idea of the how to make this value available? Need I create a table to save this data? Can I uses cache? -
Django model form with field not existing in model
I am using Django 3.2 I have a model like this: class BannedUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="ban_info") reason = models.PositiveSmallIntegerField(choices=BANN_REASON_CHOICES) banned_at = models.DateTimeField(auto_now_add=True) expiry_date = models.DateField(null=True, blank=True, help_text=_('Date on which ban expires')) I want to create a form that instead of asking user to select a date, simply asks the user to select the Ban duration. The form will then calculate the expiration_date in the clean() method. BAN_DURATION_3_DAYS=3 # ... BAN_DURATION_CHOICES = ( (BAN_DURATION_3_DAYS, _('3 Days')), # ... ) class BannedUserForm(forms.ModelForm): class Meta: model = BannedUser fields = ['reason', 'ban_till'] The form field ban_till is a PositiveInteger that maps to the number of days. The intention is then to calculate the expiry_date from today by offsetting the integer amount. I suppose one way would be to: create a dynamic field ban_till add field expiry_date to the form field list (but somehow prevent it from being rendered) in the form's clean() method calculate the expiry_date and update that field How to create a form to display field that does not exist in Model? My solution: class BannedUserForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['ban_till'] = forms.IntegerField(widget=forms.ChoiceField()) super().__init__(*args, **kwargs) class Meta: model = BannedUser fields = ['reason'] Is this the correct way to … -
django.db.utils.OperationalError: connection to server at "database" failed: FATAL: sorry, too many clients already
I had a spike of this error in my Django application: django.db.utils.OperationalError: connection to server at "name-of-the-db" (172.17.0.11), port 5432 failed: FATAL: sorry, too many clients already My Django app is deployed on dokku and connected to a postgres database. The connection to the db is achieved using dj-datbase-url package and the setting looks like this: DATABASES = { "default": { **dj_database_url.parse( os.environ.get("DATABASE_URL", False), conn_max_age=600 ), "ATOMIC_REQUESTS": True, } } I use daphne in front of Django, and I’m running 3 processes with daphne. What could have been causing this issue? I have read that a possible solution is to drop the conn_max_age parameter or set it to a lower value, but I’m not sold on it and don’t completely understand how it works, so any guidance is welcome. Also, I haven’t registered any abnormal traffic on my website, but I’m wondering: is this something that can happen “spontaneously”, maybe due to an incorrect setup, or could it be due to malicious activity? The most likely explanation I can think of is there is some database connection leaks around my app, but I can’t figure out how to find them. -
Django Dynamically add choices to choicefield form
I would like to dynamically add choices to the form from data pulled in views.py. this list will change frequently so I can't hard code this. I'm running a query against the AWS API, and pulling down backups. I am trying to get these backups in a list then get these in a dropdown to submit in a form. forms.py class RestoreAMIForm(forms.ModelForm): ami = forms.ChoiceField() def __init__(self, *args, **kwargs): super(RestoreAMIForm, self).__init__(*args, **kwargs) self.fields['server_name'].widget.attrs['readonly'] = True self.fields['module_name'].widget.attrs['readonly'] = True self.fields['instance_id'].widget.attrs['readonly'] = True class Meta: model = RestoreRequest fields = ['server_name', 'module_name', 'instance_id', 'ami', 'justification'] views.py amis = helper_functions.get_all_backups(instance_id, GlobalrunEnv) context['ami'] = amis just_amis = [i[0] for i in context['ami']] formatted_picker = helper_functions.iterate_over_list(just_amis) context['restore_ami_form'] = RestoreAMIForm(initial={'server_name': context['tags']['Name'], 'instance_id': context['server_details']['InstanceId'], 'module_name': context['passed_slug'], 'ami': formatted_picker, }) html <form action="{% url 'instance_details' passed_slug %}" method="post"> <p class="standout"> Revert to Snapshot:</p> <table> {{ restore_ami_form.as_table }} </table> <div class="buttonHolder"> <button name="RevertRequest" value="{{ GlobalrunEnv }}">Submit New Values</button> </div> </form> the output of format_picker is... [('1', 'ami-04e05d8b305348d89'), ('2', 'ami-0f82b7ac27bdeb246'), ('3', 'ami-0eed0d484f0d61391'), ('4', 'ami-071cfbc9eda4cae4d'), ('5', 'ami-0dc61e733721e7e7a'), ('6', 'ami-05ba2995c14da2502'), ('7', 'ami-01cb5e766d77f8ecb')] my read only fields are working. Is is possible to provide initial= values for choice fields? -
Django complex filter with two tables
I am in need of some help. I am struggling to figure this out. I have two models class Orders(models.Model): order_id = models.CharField(primary_key=True, max_length=255) channel = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.order_id) class Meta: managed = False db_table = 'orders' class OrderPaymentMethods(models.Model): id = models.CharField(primary_key=True, max_length=255) payment_type = models.CharField(max_length=75, blank=True, null=True) fk_order = models.ForeignKey('Orders', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'order_payment_methods' My goal is to count the number of orders that have a OrderPaymentMethods specific payment_type Example: orders = Orders.object.filter(Q(channel="Green_House")) method_money = orders.filter(payment_methods = "credit").count() How can I get the count based on the orders that were filtered? Thank You -
Create sub category using jquery ajax when selecting a category in Django
I have a problem that when I select a category, sub categories are not showing or showing default option only. I want to show sub-categories about what the user category selected. This is my html code <div class="container pt-5" style="height: 800px !important;"> <div class="mx-auto" style="width: 500px" ;> <form id="form" action="../message/" method="post" name="contactForm" class="form-horizontal" data-subCat-url="{% url 'ajax_load_subCats' %}"> {% csrf_token%} <div class="col-xs-8 col-xs-offset-4 mt-5"> <h2 style="text-align:center;">Contact</h2> </div> <div class="form-group"> <label class="p-2" for="title">Title</label> <input type="title" class="form-control" name="text" id="title" placeholder="Enter A Title" required="required"> </div> <div class="form-group"> <label class="p-2" for="category">Category</label> <select class="form-select" aria-label="Default select example" id="category" required> <option selected>Select a category</option> <option value="theft">Theft</option> <option value="assault">Assault</option> <option value="accident">Accident</option> <option value="fire">Fire</option> </select> </div> <div class="form-group"> <label class="p-2" for="category">Sub Category</label> <select id="subCat" class="form-select" aria-label="Default select example" required> </select> </div> <div class="form-group"> <label class="p-2" for="subject">Subject</label> <textarea type="text" class="form-control" name="subject" cols="30" rows="10" placeholder="Enter Subject" required="required"></textarea> </div> <button type="submit" class="btn btn-primary float-end mt-2">Send</button> <br /> <div class="form-group"> {% for message in messages %} <div class="alert alert-danger" role="alert"> {{message}} </div> {% endfor %} </div> </form> </div> </div> I didn't add html tags like body, head, html, so the problem is not there. This is my Jquery script $(document).ready(function(){ $("#category").change(function(){ const url = $("#form").attr('data-subCat-url'); const catName = $(this).children("option:selected").val(); console.log(url) console.log(catName) $.ajax({ url: … -
How to use some variable that call a function to put inside of HTML template in DJANGO
I need to use that function below, here is in util.py try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None ``` Then I put that in my views.py with the var "get" def getFunction(request): return render(request, "encyclopedia/index.html", { "get": util.get_entry() }) So I want to use that function in my index.html {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href="{% get %}"><li>{{ entry }}</li></a> //{% get %} doesn't work {% endfor %} </ul> {% endblock %} The only for is to show up a list with 5 items and inside of li, using entry I can display all five items (e.g: apple, banana, tomato, pear, grape) I need to use href because When I click it will to another folder/file .md that will be writed about apple for example I wanna use that function to take in my file .md If you need more informations just ask me. thank u. :) -
Get url param in django
I have this view: @login_required def newAnswer(request, id): post = Post.objects.get(id=id) form = AnswerForm(request.POST) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) obj.author = request.user obj.post = post obj.save() form.save_m2m() return redirect('main:post', id=post.id) else: return render(request, 'main/newAnswer.html', { 'form': form, 'formErrors': form.errors, 'userAvatar': getAvatar(request.user)}) else: return render(request, 'main/newAnswer.html', {'form': form, 'post': post, 'userAvatar': getAvatar(request.user)}) When i try to post without loging in, it redirects me to "/accounts/login?next=/post/answer/new/81". My question is how can i get the "next" param in my login view thanks! -
Using a websocket to send messages between two users, but only one user is sending
Highlevel I would like to redirect pairs of users to different rooms. Implementation I am doing this by connecting both matched users to a websocket. Upon connecting each user should send a message to the other user along with the roomID that I will be redirecting the users to. The current issue is that only the user who connects to the websocket last sends a message to the first user and not vice versa Desired Action This is the desired action UserA connects to the websocket UserB connects to the websocket UserA sends back to UserB, UserB's user_id, along with the roomID UserB sends back to UserA, UserA's user_id, along with the roomID This is what is currently happening UserA connects to the websocket UserB connects to the websocket UserB sends back to UserA, UserA's user_id, along with the roomID Here is my frontend code: ... connect() { const args = JSON.parse(localStorage.getItem('authTokens')) const queryString = args.refresh const path = `ws://127.0.0.1:8000/connect/testing/?${queryString}`; this.socketRef = new WebSocket(path); this.socketRef.onopen = (data) => { console.log('WebSocket open'); } this.socketRef.onerror = e => { console.log(e); }; } async sendData(data){ if(this.socketRef.readyState !== WebSocket.OPEN) { console.log('we are still waiting') this.socketRef.onopen = () => this.socketRef.send(data); const socketResp = await new … -
Null value in column "user_id" of relation "authentication_junioruser" violates not-null constraint
I'm trying to do POST request and getting error: IntegrityError at /accounts/juniorprofile/ null value in column "user_id" of relation "authentication_junioruser" violates not-null constraint DETAIL: Failing row contains (14, Ms K, Vadim, t, 99999999, , null, , 2022-10-23, , DevOps, , , set(), , null, null). Junior User is inherited from the custom User model class ListCreateUserProfile(generics.ListCreateAPIView): queryset = JuniorUser.objects.all() serializer_class = JuniorProfileSerializer views.py class JuniorProfileSerializer(serializers.ModelSerializer): location = LocationSerializer(read_only=True, many=True) language = serializers.MultipleChoiceField(choices=LANGUAGE) work_experience = ExperienceSerializer(read_only=True, many=True) education = EducationSerializer(read_only=True, many=True) course = CourseSerializer(read_only=True, many=True) class Meta: model = JuniorUser fields = ['id', 'terms_is_accepted', 'first_name', 'last_name', 'phone_number', 'telegram_nick', 'linkedin', 'location', 'profile_photo', 'date_of_birth', 'specialization', 'hard_skills', 'soft_skills', 'language', 'work_experience', 'education', 'course', 'other_info', 'portfolio_link'] serializers.py class JuniorUser(models.Model): """ This model points to an instance of User model and expands that one to determine the role of Junior User. All the class attributes was got from the technical requirements 'Registration form' """ user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="junior") first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) ... def __str__(self): return str(self.user) if self.user else '' models.py -
Social Network Login Failure For Twitter
I'm trying to integrate Django Social Authentication for Twitter everything is working fine but when I click to login with twitter it redirecting me to a page saying. Redirecting you back to the application. This may take a few moments. After that... Social Network Login Failure An error occurred while attempting to login via your social network account. Login with twitter page Social Network Login Failure page Social Network Login Failure PAGE URL: http://127.0.0.1:8000/accounts/twitter/login/callback/?oauth_token=2iC_EQAAAAABhMevAAABg4CH1lM&oauth_verifier=Yo9Yd8uuASo92R06tDU8dmoLf8fWawje what's wrong here CORRECT me! -
Django getting data in my template from session(dictionary)
how do I get the other itens from my session in django and im passing the session as a dictionary in my cart_page.html my session: {'3': {'quantity': 1, 'price': 4.0, 'totalitem': '4.00'}, '1': {'quantity': 1, 'price': 30.0, 'totalitem': '30.00'}} view.py: return render(request, 'cart/cart_page.html', {'itens': itens}) but when I do: {% for item in itens %} {{item}} {% endfor %} in my {{item}} it only has 3 and 1, how to I get the quantity and price inside it? -
Django Multiple Form on same page interact with each other
I have a page with two forms. When I click on the button Update Profile on the left Form it also send the POST request to the the second form which is not what I want. I don't want them to interact together. How can I do that? views.py @login_required(login_url='signin') def dashboard(request): global user_id data = Account.objects.filter(user=request.user) profile_data = Profile.objects.get(user=request.user) profile_form = ProfileForm(request.POST or None, instance=profile_data) addaccount_form = AddAccountForm(request.POST or None) # Update Profile Settings if profile_form.is_valid(): print("worked") profile_form.save() if request.method == "POST": if addaccount_form.is_valid(): # save account to DataBase return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/") context = { 'data': data, 'profile_form': profile_form, 'addaccount_form': addaccount_form, } return render(request, "main/dashboard.html", context) dashboard.html <form action="" method="POST"> {% csrf_token %} {{profile_form}} <button type="submit" class="updatebut">Update Profile</button> </form> <form action="" method="POST"> {% csrf_token %} {{addaccount_form}} <button type="submit" class="addbut">Add Account</button> </form> -
How do I save my Gist script tag in Ckeditor?
Quick question. I try to post the script to a Gist in Ckeditor, in my Django website. Whenever I post the < script > in the editor, it just shows up as raw code. My work around for this was editing the raw file, inserting the < script >. Which worked, except for some reason if I need to alter anything else in the code I have to reinsert it again. Any workaround for this? I was using the codeblocks feature of ckeditor, but I like the formatting of embedded gists better because it shows line numbers, etc. -
request.data is different in runserver and uwsgi
I'm sending a post request to server. I use runserver to test and I use uwsgi inside docker as well. When I use request.data to serialize the object, it works fine in run server. The output data is like [enter image description here][1] But when I use uwsgi in docker-omposer up and use the same request.data it is different. This causes it not to store in DB. [enter image description here][2] Can someone explain what is wrong here? Thanks [1]: https://i.stack.imgur.com/oFVpz.png [2]: https://i.stack.imgur.com/T6sIf.png -
Gunicorn is stuck in deadlock for python django service running in docker container
I am running a python django webhook application that runs via gunicorn server. My setup is nginx + Gunicorn + Django. Here is what the config looks like: gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The application runs perfectly for ~1 -2 million request, but after running for few hours the gunicorn shows in sleep state and then no more webhook event gets received root 3219 1.3 0.0 256620 61532 ? Sl 14:04 0:19 /usr/local/bin/python /usr/local/bin/gunicorn app1.wsgi:application --bind 0.0.0.0:8000 --timeout=0 The service is running in 4 different containers and within few hours this behavior is observed for 1 container and then it occurs for one or more containers in subsequent hours. I tried sending a signal to reload gunicorn config which is able to bring the gunicorn process into running state. What is curious is that when I run 4 django containers, for few requests it works perfectly well. But continuously receiving traffic causes this deadlock in one of the gunicorn worker's state and it keep on waiting for a trigger to start accepting traffic again while rest of the three gunicorn workers are healthy and running ! Question - Why does gunicorn worker process is going in sleep state(Sl)? How can … -
Docker and Django Postgresql issue
I am currently learning how to implement docker with Django and Postgres DB. Everytime I tried I run the following command: docker compose up --build -d --remove-orphans Although I can see all my images are started. Every time I tried to open my Django admin site, I cannot sign in using already registered superuser credentials. In Postgres DB PGAdmin all the data that are created previously are stored and saved correctly. But after closing my computer an I start Docker compose up previously saved data's are not recognized by the new start up even if the data still visible in my Postgres DB. How can I make the data to be recognized at start up? Here is my docker-compose.yml configurations: version: "3.9" services: api: build: context: . dockerfile: ./docker/local/django/Dockerfile # ports: # - "8000:8000" command: /start volumes: - .:/app - ./staticfiles:/app/staticfiles - ./mediafiles:/app/mediafiles expose: - "8000" env_file: - .env depends_on: - postgres-db - redis networks: - estate-react client: build: context: ./client dockerfile: Dockerfile.dev restart: on-failure volumes: - ./client:/app - /app/node_modules networks: - estate-react postgres-db: image: postgres:12.0-alpine ports: - "5432:5432" volumes: - ./postgres_data:/var/lib/postgresql environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} networks: - estate-react redis: image: redis:5-alpine networks: - estate-react celery_worker: build: … -
Django, Postman. Why the GET request doesn't respond with my API?
I am developing on my local and try to get view (non-programming term) of my API. My view (programming term) is simply looks like: class WeaponDetailsView(DetailView): model = Weapon template_name = 'weapons/weapon/details.html' I also try to get response via script: import requests url = 'http://127.0.0.1:8000/' res = requests.get(url).json() print(res) But this gives me the raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 2 column 1 (char 1) error. So why can't I see my APIs only, and not the html body content? And why the situation changes when I implement an API View with Django Rest Framework? I mean it returns only APIs which is grate -
How to plot Django data on a Chart.js graph?
I am so tilted, so so so tilted. Been trying to work chart.js for a while now on my website I built with Django. I want to plot two fields: Dates and Scores. Dates is a date such as 1/6/2022, score is a float. My issue is that when I pass through the python list to the script it pretends it's something disgusting. But when I copy and past the list and put it into the chart's data it's fine. It only doesn't work when it thinks it's a variable which just makes no sense at all and I can't find anywhere that is talking about this. views.py def progress(response): lessons = StudentLessons.objects.get(name=response.user.email) scores = [] dates = [] for lesson in lessons.lesson_set.all(): dates.append(str(lesson.date)) scores.append(str((lesson.accuracy+lesson.speed+lesson.understanding)/3)) context = { 'dates':dates, 'scores':scores, } return render(response, "main/progress.html", context) dates = ['2022-09-27', '2022-09-28'] scores = ['4.333333333333333', '6.0'] (from console) html that displays the correct chart <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var myChart = new Chart("myChart",{ type:"line", data: { labels: ['2022-09-27', '2022-09-28'], datasets:[{ borderColor: "rgba(0,0,0,0.1)", data: ['4.333333333333333', '6.0'] }] }, options:{ responsive: true, legend: { position: 'top', }, } }); </script> html that doesn't work <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="myChart" style="width:100%;max-width:700px"></canvas> <script type="text/javascript"> var … -
Table generating for web
I have a web app made in django which generates a school timetable. It takes around 5-10 minutes to generate one because it is for 25 classes with a lot of links to every teacher and class with separate timetables. I want to rewrite the whole app and if it's possible I want to make it run faster. I can use django and plain html/js/php. What should I use for this kind of problem or does it even matter if I don't use django or if there is a better framework for this beside these two.