Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Form is getting submitted but nothing saves in database
My form is getting submitted by in phpmyadmin nothing get saved please help. Models.py from django.db import models class Customers(models.Model): first_name=models.CharField(max_length=100) . . . address=models.CharField(max_length=100) mar_stat=models.CharField(max_length=100) class Meta: db_table="customers" Views.py def customerreg(request): if request.method=='POST': if request.POST.get('first_name') and request.POST.get('last_name') and request.POST.get('gender') and request.POST.get('dob') and request.POST.get('email') and request.POST.get('phno') and request.POST.get('designation') and request.POST.get('address') and request.POST.get('mar_stat'): saverecord = Customers() saverecord.first_name=request.POST.get('first_name') . saverecord.mar_stat=request.POST.get('mar_stat') saverecord.save() messages.success(request, "New User Registration Saved Successfully. You may close the window!") return render(request,'index.html') else: return render(request,'index.html') Index.html <form method='POST'> {% csrf_token %} <table border="7"> <tr> <td>First Name</td> <td><input type="text" placeholder="Enter First Name" name="first_name" required/></td> . . . . </select> </td> </tr> </table> <hr> <input type="submit" value="Submit"/> {% if messages %} {% for result in messages %} <b style="color: green;">{{result}}</b> {% endfor %} {% endif %} </form> </body> </html> I have tried everything and im mostly sure that my indentation is right still it throws an error. What to do? -
Twilio Whatsapp Sandbox Configuration for deploying application via AWS elastic beanstalk
enter image description here Currently I am developing a chatbot for my application with django, using a twilio trial account. The chatbot functions properly with ngrok.io, i.e. when the server is operating locally, which mean that when I send a whatsapp message to the twilio sandbox with operation of simply "python manage.py runserver", he will automatically reply me according to my script. However, as I started deploying the application using the AWS elastic beanstalk, I found that it is only possible for the sandbox to send out whatsapp message by POST request on the web application, but not capable to respond to POST request sent out from whatsapp. In what way I can deal with it? Is it related to AWS settings or Twilio settings? Some CORS related issues? Great thanks in advance. (Please forgive me if my use of language is not accurate as I am not with computer science background.) Below is part of the code that I applied. @csrf_exempt def message(request): account_sid = 'xxx' auth_token = 'xxx' client = Client(account_sid, auth_token) client_phone_number = request.POST.get('From').removeprefix("whatsapp:+852") client_phone_number.removeprefix("+852") incoming_message = request.POST.get('Body') conversation_sid = request.POST.get('conversation_sid') incoming_message = incoming_message.lower() response = MessagingResponse() #processing the incoming message to produce the text resp = … -
Django-filebrowser doesn't support forms.py?
Django-filebrowser doesn't support forms.py? Can't I use the FileBrowseField of the file browser provided by models.py in forms.py where users can write in my Django project? I couldn't find it in the official guide. -
Why with django-postman that's doesn't work with this -> url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')),
I'm new with django, I would like use django-postman, and when I put : url(r'^messages/', include('postman.urls', namespace='postman', app_name='postman')), I have this error, idk why ? NameError: name 'url' is not defined Why is it not defined ? Just for test I replace url by path but that's doesn't work, I tried to install django postman in the terminal with pip, but that's doesn't work too.I really would like have a solution for a messaging system between users for my project. -
Django : in a ManyToManyField how can I find if a relationship exists?
I'm creating a Truth System for my project PoopFacts, where people can vote for True, False, or remove their vote. I have the voting system working, but I'm trying to make the button change colors to show if they've voted for True of False already or uncasted their vote. I'm showing the "Like button" code, cause it's simpler and uses the same logic. .models PoopFact(models.Model): likes = models.ManyToManyField(User, related_name='likes') .views def home(request): poopfacts = PoopFact.objects.all().order_by('-date') context = {'form': form, 'poopfacts':poopfacts,} return render(request, 'home.html', context) The idea is pretty much something like this html {% for poopfact in poopfacts %} {% if poopfact.likes.user.exists() %} <button type="submit" class="btn btn-primary btn-block">Like</button> {% else %} <button type="submit" class="btn btn-block">Like</button> {% endif %} So if they've liked it, the button will be blue, and if they click it again it will uncast their vote and make it normal. Does anybody have a good idea to make this work? I've been trying so many things with no luck. -
Django testcase for logout API with LoginRequired mixin, but for anonymous user it is redirecting to login API with ?next= parameter
But what if I want to check without login. For example, I have one api logout which is having LoginRequired mixin, I want to test that anyone cannot hit logout if hes not logged in. So I created testcase as below. @pytest.mark.django_db def test_user_logout_logged_in_user(self, client): url = reverse('logout') response = client.get(url) assert response.status_code == 302 assertRedirects(response, reverse('login')) but I got this error, AssertionError: '/auth/login-view/?next=%2Fauth%2Flogout-view%2F' != '/auth/login-view/' Means I get ?next={something for after login api}. How do I check that redirected api is login api. My logout api is as below: class LogoutView(LoginRequiredMixin, View): """ description: This is user logout view. GET request will log out user and redirects to home page. """ def get(self, request): return LogoutService.logout_user(request=request) class LogoutService: @staticmethod def logout_user(request): logout(request) messages.success(request, ACCOUNT_LOGOUT_SUCCESS) return redirect('home') Django test for a page that redirects I tried this answer, but it is for logged-in user. I want to test for un authenticated user. -
Video link to the html video element is not shown in AWS in React and Django app. Locally it works
We are trying to show a video link by creating an video element in html/javascript. It works in local system however do not work in AWS cloud. The app is in React and Django. The content of element is var cont="https://172.31.80.50:8000/api/getVideo?fn="person1_amar.mp4" or var cont="//172.31.80.50:8000/api/getVideo?fn="person1_amar.mp4" or var cont="https://localhost:8000/api/getVideo?fn="person1_amar.mp4" Note: Request has IP address of AWS machine. Localhost works in local system with http protocol. getVideo code on server side is vid = open('frontend/inoutfiles/'+fileN, 'rb') response = FileResponse(vid) We are getting below 2 errors: 'Failed to load resource: the server responded with a status of 499 ()' Failed to load resource: net::ERR_CONNECTION_TIMED_OUT Please let us know how to resolve this issue. Thanks, Amar Joshi We tried 2-3 solutions as mentioned in description. It did not work. We expect an answer to the issue so that we can show the video from server to the frontend in React in playing form. -
Reviews showing on the reviewer's own profile page instead of the profile that it was written on
I am adding a simple review function on my Social platform Django project, where Users can write a review on another user's profile. But after posting the review, it's only showing on the profile page of the user that I'm currently signed in to. This is my models.py ` class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reviewmsg = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.reviewmsg)` views.py ` def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() reviews = user.review_set.all() if request.method == 'POST': review = Review.objects.create( user=request.user, reviewmsg=request.POST.get('reviewmsg') ) return redirect('user-profile', pk=user.id) context = {'user':user, 'rooms':rooms, 'reviews':reviews} return render(request, 'pages/profile.html', context)` excerpt from my profile page template ` <div> {% for review in reviews %} <div class="comment-sect" style="margin-top: 0.5rem;"> <div class="comment-photo" style="margin: auto;"> <a href="{% url 'user-profile' review.user.id %}"> <div class="profile-photo"> <img src="{{review.user.avatar.url}}"> </div> </a> </div> <div class="comment-info" style="width: 300px;"> <small>@{{review.user}}</small> <small>{{review.created|timesince}} ago </small> <p style="margin-bottom:0;">{{review.reviewmsg}}</p> </div> </div><!--end of comment-sect--> {% endfor %} <div class="comment-form" style="margin-top: 0.5rem; text-align:center;"> <form method="POST" action=""> {% csrf_token %} <div>Submit a Review <input type="text" name="reviewmsg" placeholder="What do you think about this User?"/> </div> </form> </div>` -
Django views not retrieving data from database
Can Anyone know what's the problem with this? i can't display the data retrieve from db even the code is ok Here is my template addCategory.html Here is my views.py Here is my model.py When I Add Category, it didn't show/display the queried data from database like this can anyone solve? -
Django: Is it possible to use a capitalization method such as capfirst in templates but instead in forms.py
In templates a usual statement such as {{field.value|capfirst}} capitalize the first letter of a string. In an input field this looks like <input type="text" name="{{field.name}}" value="{{field.value|capfirst}}"> In my template I do not define explicitly the input fields, instead I have the following: {% for field in form %} {{ field }} {% endfor %} If I do {{field|capfirst}} it won't work. All my fields are given in forms.py, for example: class MyForm(forms.ModelForm): name = forms.CharField() description = forms.CharField() class Meta: model = Project fields = ('name', 'description') How can I define capfirst in forms.py (or views.py or templatetags)? I want to keep a simple for loop in my template as shown above. As you can see I just want to capitalize the first letter of field.value to show it on the screen, no need to transfer this info to the database or store it or update, i just want to show it... is it possible? -
Cloning GITHUB project to ubuntu 22
I've had to wipe and reinstall my ubuntu server twice now due to failing and some how corrputing/locking my self out of the server when it comes to setting up the SSH. I'm going out on a whim and hoping some one who reads this knows where to find an easy to follow tutorial for cloning a project to ubuntu using SSH as they dont allow HTTP cloning now. Many thanks. -
Reverse for 'detail' with arguments '('2022/11/29/oddballers-29112022',)' not found. 1 pattern(s) tried: ['page/(?P<key>[^/]+)\\\\Z']
I'm getting error NoReverseMatch at /, here I'm trying to catch the key like this enter image description here and I can't get the key, when I take it and an error like the one above comes out The code details are like this: enter image description here enter image description here detail error like this: enter image description here thank you. what I want is to capture the key and then I make it as a parameter for the details of the article, when I catch the key but what comes out is an error.. sorry if my English is difficult to understand, I'm not good at English -
Most efficient way to migrate data from temporary Django table to main table?
I have a data engineering pipeline that is essentially doing nightly scans of data tables to populate a main table with calculations for the frontend clients to view. The pipeline takes around 6 hours to complete. Instead of deleting the main table and writing the calculations over a 6 hour period, I am instead writing the calculations to a temporary table (so the main table still has prior day's calculations while the today's calculations are generating). Once complete, I am trying to have the Django ORM essentially delete the main table and insert all of the new calculations from the temp table into the main table in a transaction. Is there an efficient way using the Django ORM to do this? Thank you! Also note that the temporary model and main model have the exact same copy of fields. -
Python Django - Trying to make a dynamic name from string to call serializer function
So I was trying to access a serializer using the serializer name, and the model query set as a parameter, using the python gettattr() function. After running the code, Django returns the following error: 'str' object has no attribute '<module 'django.db.models' from 'C:\\Python310\\lib\\site-packages\\django\\db\\models\\__init__.py'>' However I can't really understand what it means, I've been stuck on trying to access the serializer this way, as I have a dyanmic url. Anyhelp with the problem or explanation of the error would be appreciated. I was expecting the serializer to be processed normally, and return the data in the respone, I implemented it this way. @api_view(['GET']) def List_all_part(request, part): table = apps.get_model('Parts', part) model = table.objects.all() serializer = getattr(str(part.lower()), str(models)) return Response(serializer.data) -
How to implement `left outer join` with additional matching condition, with `annotate()` or something else?
We are implementing a design pattern that assembles EAV data with the entities by a series of left outer join actions in SQL query, briefly as the following: First, we have retrieved the meta data, e.g. postalcode corresponds to attribute_id of 22, phone corresponds to 23, and etc. Then, we want to construct a QuerySet by adding annotate() method calls following the meta data. And we are open to other methods other than annotate(). Like the below SQL query, the system behaviour is to repeat left outer join on the same eav_value table, however, besides the foreign key, the matching condition also requires a specific attribute_id. So, each join assembles one attribute. Our Question: We tried to assemble the first attribute appending an annotate() call to the existing QuerySet but got an error saying AttributeError: 'WhereNode' object has no attribute 'select_format'. We wonder how to fix the issue and make the prototype run. And we are also OK to use something else other than annotate() within the Django framework, not raw query. We are new to this area of Django ORM, so we appreciate any hints and suggestions. Technical Details: 1. SQL query for assembling EAV data with entities: select … -
how to display subcategories title and its items under parent category in django?
I want to display subcategories title and its items under parent category in Django e.g. I have 1 parent category then it hast 2 sub cats and then each of them has 3 sub cats. in every sub category there are 10 items. Parental category1 item1 item2 subcategory 1 item3 item4 item5 child category 1 from subcategory1 item6 item7 subcategory 2 item8 item9 item10 here is my codes: Models.py from django.conf import settings from django.db import models from django.urls import reverse from django.utils.text import slugify from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField(max_length=settings.BLOG_TITLE_MAX_LENGTH, null=True, blank=True) description = models.TextField(null=True, blank=True) class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def save(self, *args, **kwargs): value = self.name if not self.slug: self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('items-by-category', args=[str(self.slug)]) class Item(models.Model): title = models.CharField(max_length=settings.BLOG_TITLE_MAX_LENGTH) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) slug = models.SlugField( max_length=settings.BLOG_TITLE_MAX_LENGTH, ) def __str__(self): return self.title def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('item-detail', kwargs=kwargs) def save(self, *args, **kwargs): if not self.slug: value = self.title self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) Views.py from … -
MQTT async worker in Django
In my Django application, I need to connect to a MQTT broker from several locations. It will be great if I can create some kind of MQTT worker, which will run in the background/different thread and I can use this worker to publish/subscribe for messages and I don't have to create a separate MQTT connection for each function. Example: Create MQTT worker with connection details. On startup, this connection is started and handled, restarted if connection lost, etc... (maybe use Celery for this?) Create functions which is available inside my Django projects for publish and subscribe. Publish seems more straighforward, but I'm not sure about the subscribe part. I have found mqttasgi but I don't know if it will fit my needs. -
Server Error (500) Django App on AWS server
Good day, i have currently my django project running on an aws server. I have used Nginx and configured it all. The application is running, but when i try to login via the login page i have created or try to login via the admin panel it gives me a Server Error (500). I have my DEBUG=False and added my server dns to ALLOWED_HOSTS. As for the Database. I have got my SQL Database running on an Azure server and used environment variables (that i have permanently set in my ubuntu terminal) to get my password and username. I have also tried to set DEBUG to False and trying to figure out the issue when running python manage.py runserver so i could experiment with it on my localhost, but no luck. I cant access 127.0.0.1 eventhough i have added it to my Allowed hosts. How could i see what the error is? Thank you in advance -
Setting up hypertables in TimescaleDB with multiple time-series
I am about to integrate TimescaleDB in my django project, but what’s unclear to me is how timescale groups different timestamps together to form a time-series. Imagine I have multiple Drinks (coca-cola, lime-juice etc, fanta, water…). I can have a million drinks in my database. Each drink can have multiple time-series related to it. A time-series of consumption data over the years, a time-series of customer data over the years etc… Then imagine I also have food data with the same assumptions. I want to save all those data in a hypertable. I can start by creating a hypertable and inject all consumption data for Coca-Cola in the year 2018. Now i also want to store customer data for Coca-Cola too, but the time-stamps will collide. I will have 2022-12-03 multiple times. Thus timescale must have a best-practice of how to group timestamps together to from a time-series. Otherwise I could only have a single time-series in a hypertable. I see two solutions: I can save a foreign key or an object-id with the timestamp. E.g. 2022-01-01 and 5, whereas 5 is the id of coca cola object. Or I can create a meta-table which stores the meta-information about the … -
Relationships in Django - how to filter data
I've looked at a lot of entries and I know how to filter simple relationships. Unfortunately, I'm stuck and I don't know how to filter my table data when one of the tables is a branch of a certain string. models.py from django.contrib.auth.models import User class Autor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) description = models.TextField(blank=True, null=True) class Incident(models.Model): group_no = models.ForeignKey(Group, on_delete=models.CASCADE, default=1) description = models.TextField(blank=True, null=True) deleted = models.BooleanField(default=False) class Department-leader(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="leader") department = models.ForeignKey(Group, on_delete=models.CASCADE) class Group(models.Model): group_no = models.CharField(max_length=40, unique=True) active = models.BooleanField(default=True) views.py def get_author(user): qs = Autor.objects.filter(user=user) if qs.exists(): return qs[0] return None def show_all(request): show_all_records = Incident.objects.filter(deleted=False).order_by('-id')[:300] if request.user.is_authenticated: autors_list = get_author(request.user) user_list = get_user_model() logged_user = get_object_or_404(user_list, username__exact=autors_list) (...) print("Logged user: " + str(logged_user.id)) else: logged_user = "" context = { 'show_all_records': show_all_records, 'logged_user': logged_user, } return render(request, 'incident/all_records.html', context) The show_all_records variable represents all the records of the Incident table and that is ok. The second thing I would like to display are entries for the logged in person i.e. all incidents in particular departments of the leader who is logged in. If the tables were connected linearly, I would have no problem building this filter. But how … -
How to increment counter in django templates
I am trying to get the total count of infringements for each infringer. The counter is not incrementing. ( {{ a|add:"1" }} ) It outputs 1 1 1 instead of total of 3. Please assist. {% for infringer in page_obj %} <tr> <td>{{infringer.id}}</td> <td>{{infringer.created|date:"d M, Y"}}</td> <td>{{infringer.name}}</td> <td>{{infringer.brand_name}}</td> <td>{{infringer.status}}</td> <td> {% with a=0 %} {% for i in inc %} {% if infringer.id == i.infringer.id %} {{ a|add:"1" }} {% endif %} {% endfor %} {% endwith %} views.py @login_required(login_url='login') def infringerlist(request): q = request.GET.get('q') if request.GET.get('q') != None else '' ings= Infringer.objects.filter(Q(created__icontains=q) | Q(id__icontains=q) | Q(status__name__icontains=q) | Q(brand_name__icontains=q) | Q(name__icontains=q), customer=request.user.customer,) paginator = Paginator(ings, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) inc = Infringement.objects.filter(customer=request.user.customer) context= {'page_obj': page_obj, 'inc': inc} return render(request,'base/infringers_list.html', context) -
requests hang unless timeout argument given
My backend runs on openshift and makes get requests to other openshift clusters via kubernetes python client. I am having an issue where requests hang until the default timeout value is reached. I have done some tests in the pod to see if it can reach other openshift clusters and discovered the following: requests.get("some_other_cluster_api_url") will hang and return correctly in 2 mins, but requests.get("some_other_cluster_api_url", timeout=1) returns correctly in 1 second. Why does the request not return immediately in the first case? -
Does django mail output get persisted in different tests?
Does django from django.core import mail mail.output get persisted over different tests? I have different tests that does email sending and now I see that the length of mail.output is more than the number of emails I'm sending in my tests. I have done mail.output=[] in both setUp and tearDown but I can still see extra outputs. Any ideas why this might happen? -
Django as_p() method equivalent for non-form / display only use cases
I have a handful of models with 10+ fields each. During my first draft of development I am less concerned about how things look and am trying to get to the critical components of the code ASAP. I love the myForm.as_p method built into the Forms object. The main benefit is that I can alter the models as needed, make my migrations, and the as_p will show these new fields without me having to change the template. My questions is: is there an equivalent method for display only use cases? I have tried combing through the docs but have not found a thing outside of forms. The ideal would be something like a class based DetailView that in the template can use {{ object.as_p }}. Anyone know of a dynamic display function like that outside of forms? -
Pass Image data of one view obtained from POST method to other view without using any Databases
I am working on a Django project . It fundamentally contains two views. First is HomePageView. It contains a form that take image input from user(anonymous).On submitting the form, user gets redirected to the second view, ResultView. forms.py from django import forms from .models import * class ImageForm(forms.Form): image = forms.ImageField(label = 'Choose an image below.') views.py from django.views.generic import TemplateView from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from .models import * from .forms import * import base64 def HomePageView(request): if request.method == 'POST': form = ImageForm(request.POST , request.FILES) if form.is_valid(): image_object = request.FILES['image'] #or should i use : image_object = form.cleaned_data['image'] #or should i use : image_object = request.POST.get('image') request.session['image_object'] = image_object return redirect(to='ResultView') else: form = ImageForm() params = {'form': form} return render(request, 'home.html', params) home.html <form action="{% url 'ResultView' %}" method="post" enctype="multipart/form-data">{% csrf_token%} <!--- Styling ---> <div class="col-md-8 mt-4 pt-5"> <div class="container mt-5 "> <div class="row p-3 "> <div class="col-md-12 align-items-center"> {{ form.as_p }} </div> </div> <div class="row"> <div class="col-md-4 ms-3"><button type="submit" class="btn btn-outline-dark font-monospace" data-mdb-ripple-color="dark">SUMBIT</button></div> <div class="col-md-4"></div> <div class="col-md-4"></div> </div> </div> </div> </div> </div> </form> Now, I want to obtain the image that user has uploaded. Pass it to the result view, do some …