Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: Handling two values in one field
Intro: I have time series data that need to be stored in with the date_created, the its value. Also, each list of values will have a column where I define some constants. Example, oxygen level can be today == 95, later its goes to 80 which is bad things and I need to monitor that. My Models: class Column(models.Model): max = models.PositiveIntegerField(max_length=500, null=True, blank=True) min = models.PositiveIntegerField(max_length=500, null=True, blank=True) limit = models.PositiveIntegerField(max_length=500, null=True, blank=True, help_text='if {absolute(latest measurement - the new measurement) == limit} then you may need to be alerted') name = models.CharField(max_length=500) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='statistics', null=True, on_delete=models.SET_NULL) class Value(models.Model): object_id = models.CharField(max_length=20) name = models.CharField(max_length=50, blank=True) column = models.ForeignKey(Column, related_name='values', on_delete=models.CASCADE) field_value = models.CharField(max_length=500) field_name = models.CharField(max_length=500) seen_by = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='seen_by_users', blank=True) date_created = models.DateTimeField(auto_now=True, blank=True, null=True) problem When I deal with blood pressure that should have a field_value like 120/80 which is why I am using CharField instead of IntigerField. Also, separating them cause many complications like # 1. I should create two value # Note I already planned to do it this way but I need more ideas please. Value.objects.create(field_name='Diastole', field_value=80) Value.objects.create(field_name='Systole', field_value=120) # 2. in the view I should do `anoniation` or `aggregation` on values … -
Why Django's POST doesn't do anything - not even an error?
I'm doing an assignment for Uni from Python/Django. One of the things I have to do is to create a form where a user can create a new "tournament" on the website. Frontend doesn't matter at all. I created a model, added some tournaments from the Admin panel and that works fine. But when I try to create a new tournament from the form, and click the sumbit button, I get redirected to my home page (even though nothing specifies in the HTML or views.py that this should happen), I get no error, no data posted and no info back from the command line. models.py: class Tournament(models.Model): title = models.CharField(max_length=30) creator = models.OneToOneField(User, on_delete=models.CASCADE) players = models.ManyToManyField(User, related_name="players",) created_date = models.DateField(auto_now=True) start_date = models.DateField(auto_now=True) max_players = models.IntegerField( null=True, validators=[MinValueValidator(2), MaxValueValidator(64)]) slug = models.SlugField(unique=True, db_index=True) def __str__(self): return f"{self.title} \n {self.creator} \n {self.max_players}" Forms.py class TournamentForm(forms.ModelForm): class Meta: model = Tournament #exclude = ["slug"] fields = "__all__" views.py class TournamentView(View): def get(self, request): form = TournamentForm() print(form.errors) return render(request, "tournament_app/new_tournament.html", { "form": form }) def post(self, request): form = TournamentForm(request.POST) if form.is_valid(): print(form.errors) form.save() return redirect("/thank-you") print(form.errors) return render(request, "tournament_app/new_tournament.html", { "form": form }) The HTML file {% extends "base.html" %} … -
Can`t change Django REST Framewokr language
When i load my page in postman i have output: { "detail": "You do not have permission to perform this action." } I want to have this message in ukrainian Here is my settings.py: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('uk', _('Ukraine')), ('en', _('English')), ] # LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'uk-UA' # LANGUAGE_CODE = "es-es" My request: GET /url/to/page HTTP/1.1 Host: 127.0.0.1:8000 authorization: Bearer *here is jwt token* Accept-Language: uk-UA I did all changes stay by instruction -
How to return all the disctinct foreign keys in a Django view?
Here is my model.py: class Category(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=255, default='') def __str__(self): return "%s" % (self.name) class SubCategory(models.Model): name = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=255, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['name'] And my view.py: def home(request): context = { 'home_page': "active", 'categories': SubCategory.objects.order_by('category').distinct('category').values_list('category'), } return render(request, 'candidates/home.html', context) and my template: <ul> {% for category in categories %} <li>{{ category }}</li> {% endfor %} </ul> and instead of seing the Category names, I see their ID How can I get their names? Thanks -
Update field from None value to timestamp when click on Button
I have a simple problem: I have model Notification with fields: class Notification(models.Model): user = models.ForeignKey('User', models.CASCADE, related_name='notifications') message = models.TextField('Message') viewed_at = models.DateTimeField('Seen at', null=True, blank=True) created_at = models.DateTimeField('Created', auto_now_add=True, editable=False) And my logic is that Field viewed_at in DB is empty . But when I click on button "See it" This field will update with value timestamp now. I created function in my views: import datetime from django.http import HttpResponseRedirect from django.shortcuts import render, redirect class NotificationListView(core.ListView): permission_classes = [AllowAny] model = Notification template_name = 'auth/notifications.html' def get_queryset(self): return Notification.objects.filter(user=self.request.user) def get_context_data(self, **kwargs): context = super(NotificationListView, self).get_context_data(**kwargs) context['unviewed_list'] = Notification.objects.filter(viewed_at__isnull=True,user=self.request.user) context['viewed_list'] = Notification.objects.filter(viewed_at__isnull=False, user=self.request.user) return context def mark_as_read(request, notification_id): notification = Notification.objects.get(pk=notification_id) notification.viewed_at = datetime.datetime.now() notification.save() return HttpResponseRedirect(request.POST['next']) My urls.py: path('notification/<notification_id>/', views.mark_as_read, name='viewed-notification'), And template ListView <table class="table table-theme-3 text-left"> <tbody> {% for item in unviewed_list %} <td> {{ item.message }} <td> <td> {{ item.created_at}} <td> <span class="badge badge-error"> <a class="button button--success button--sm" href="{% url 'users:viewed-notification' %}?next={{ request.path }}"> See it </span> </td> </tr> {% endfor %} </tbody> </table> I need that when I click on See it - model Field "viewed_at" update from None value on timestamp now!)Please what I am doing wrong in my code and … -
Django conditional querysets
Alright, So I'm using a general listview showing all orders where the payment hasn't been completed yet. Let's call them outstanding orders, orders which still require some sort of payment. Orders contain one or multiple items and can contain zero or more payments. So I want to compare the total order value, compare this value with the total payment and if these or not equal to zero, show them in the list. Is there someway I can build a new queryset for items which do not meet a certain condition? views.py class OutstandingOrderListView(ListView): model = Order def get_queryset(self): queryset = Order.objects.all()[:5] for record in queryset.iterator(): # Retrieve order_total order_total = record.item_set.aggregate(total=Sum('price'))['total'] # Retrieve payment_total payment_total = record.payment_set.aggregate(total=Sum('amount'))['total'] # Compare both delta = order_total - payment_total if delta != 0: print("These guys owe you money!") # Add record to new queryset? -
Facing a bit weird CORS issues in django template. Some files from same path getting rendered but some are not
We have been using a combination of AWS Cloudfront to serve static files (hosted in S3) for our Django project. Things were running smoothly till yesterday. However now suddenly, we are facing cors issues for a few of our files. Also it looks like the way of calling is giving the issue. But I think that shouldn't be the case. When I look at the inspect, the font when called as , it is getting downloaded However, our original method of importing it under @font-face is what is giving it issues. which goes like: @font-face { font-family: 'HKGroteskPro'; font-weight:300; src: url('{% static 'landikit/fonts/HK Grotesk Pro/HKGroteskPro-Light.otf' %}'); } Have tried invalidating and giving this folder precedence on cloudfront too, but still no luck. Anyone who have faced a similar issue and can how this can be solved? -
how to use same token for reset username and reset passsword with djoser?
I use djoser in my django API just to handle reset_password and reset_username of users. I want to reset both of them in the same view. But I meet a problem because token is only valid for 1 change. I run reset_password, I receive a token and my uid. Then I can run reset_password_confirm or reset_username_confirm with this token, but I can't run the second one (the order doesn't matter). I use a piece of code of djoser to check the validity of my token. And I can see that token is unvalid after 1 change. How to change it as valid for 2 requests ? -
Is there any minimum key length is required for JWT_PUBLIC_KEY ? getting error Could not deserialize key data
i have used restframework_jwt with RS256 algorithm, and successfully created access token. But i am getting a error "Could not deserialize key data." when try to use this token as Authorization in header. i have tried changing the JWT_PUBLIC_KEY. Right now my setting is like this, settings.py JWT_AUTH = { 'JWT_PUBLIC_KEY': '-----BEGIN PUBLIC KEY-----\n'+str(SECRET_KEY)+'\n-----END PUBLIC KEY-----', 'JWT_PRIVATE_KEY': '-----BEGIN PRIVATE KEY-----\n'+str(PRIVATE_KEY)+'\n-----END PRIVATE KEY-----\n', 'JWT_ALGORITHM': 'RS256', 'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler', 'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_PAYLOAD_GET_USER_ID_HANDLER': 'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler', 'JWT_RESPONSE_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_response_payload_handler', } views.py class GetUserListView(generics.ListAPIView): authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = UserSerializer queryset = CustomUsers.objects.all() these are version i am using, { "cryptography": { "version": "2.2" }, "implementation": { "name": "CPython", "version": "3.8.10" }, "platform": { "release": "5.8.0-63-generic", "system": "Linux" }, "pyjwt": { "version": "1.7.1" } } please help me to figure out the issue. -
django Queryset filter(a__b__c=d): get hold of b for futher filtering
I am writing a method that computes a complex Django QuerySet. It starts like this qs1 = A.objects.filter(b_set__c_obj__user=user) qs1 will eventually become the result, but before it does, the method goes on with several further steps of filtering and annotation. b_set is an 1:n relationship, but I know that at most one of the c_obj can actually match. I need to reference this c_obj, because I need another attribute email from it for one of the filtering steps (which is against instances of another model D selected based on c_obj's email). user can be either a User model instance or an OuterRef Django ORM expression, because the whole queryset created by the method is subsequently also to be used in a subquery. Therefore, any solution that involves evaluating querysets is not suitable for me. I can only build a single queryset. Hmm? -
Django - ValueError cannot assign - must be a - instance
I believe I understand where my issue comes from I am just not sure how to solve it. The issue is that I am trying to save a review for a product but in the select field of the product the items which are displayed are ones they have purchased. I accomplished this by overriding the init method in my form. My issue is with this exact query it doesn't give me the product, it gives me the string that is queried (due to the str in my model). Therefore when I try to add the review to the product this error is getting thrown. My issue is I do not know how I can get the product exactly because in order to display what I want to display in the select field I have to give it that specific query. Any help is greatly appreciated form class ReviewForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('user') super(ReviewForm, self).__init__(*args, **kwargs) self.fields['product'].queryset = ShoppingCartOrderItem.objects.filter(user=self.request, ordered=True) # for item in self.fields['product'].queryset: # print(item.item) # print(self.fields['product'].queryset) class Meta: model = Review exclude = ['user', 'date'] widgets = { 'product': forms.Select(attrs={ 'class': 'form-control' }), 'rating': forms.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '5.0..' }), 'comment': forms.Textarea(attrs={ 'class': 'form-control' … -
Project ideas for django
It has now been almost a month since I started learning Django, so far I have covered up basic topics like(CRUD and ORM) projects so far (Blog, Job Portal) and delved into DRF I am also able to write API's quite a fair bit, I wanted some project ideas that can improve my knowledge and take me into intermediate level -
How to update two models through one view?
I have two models: User and Profile, and two serializers: UserSerializer, ProfileSerializer, respectively. Is it possible to update these two models using one PUT request? -
I use django to upload file
I use the django framework to implement the function of uploading files, the local test is normal, and the following errors occur after deploying to the server. My code is as follows if request.method == 'POST': file_obj111 = request.FILES.get('file111') f = open('/home/file_loca/' + file_obj111.name, 'wb') for chunk in file_obj111.chunks(): f.write(chunk) f.close() It runs normally when tested locally.When I deployed to the server, an internal error appeared. *[22/Jul/2021 17:26:20] "POST /api/analysis/fuzzy_query HTTP/1.1" 200 15 qqq Internal Server Error: /api/analysis/fuzzy_query Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/http/request.py", line 391, in read return self._stream.read(*args, *kwargs) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 40, in read result = self.buffer + self._read_limited(size - len(self.buffer)) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 28, in _read_limited result = self.stream.read(size) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 40, in read result = self.buffer + self._read_limited(size - len(self.buffer)) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/wsgi.py", line 28, in _read_limited result = self.stream.read(size) File "/usr/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer -
Access the member of other class instance
I have two class SubCtrl has the instance of MainCtrl class MainCtrl(): def __init__(self): self.pid = 100 def getSubCtrl(self): self.subCtrl = SubCtrl(self) def myFunc(self): return 99 class SubCtrl(): def __init__(self,mainCtrl): self.mainCtrl = mainCtrl self.mainCtrl.myFunc() // it works print(self.mainCtrl.pid) // it shows <aicomposer.helpers.MainCtrl object at 0x7f8a68136550 mainCtrl = MainCtrl() mainCtrl.getSubCtrl() However member method myFunc works but member variable doesn't work. Why does this happen??? I think I gave the instance of MainCtrl to SubCtrl() not class itself -
Server error on getting access token OAuth2 Django
I work with an API that is based on OAuth2 and I have this error Code: server_error, Message: No user/userId parameter returned from getauthCode API says that during authentification on their site they add some cookie that is not transferred to my redirect_uri and hence the error. So I was wondering maybe my algorithm logic isn't right because I got no other leads? def callback(request): """My redirect_uri that receives authorization code. """ get_access_token(request.GET.get("code")) # POST request for access_token get_clients_data(access_token["access_token"]) # POST request for clients data with access_token return HttpResponse('{"success" : true}') def link_request(request): """Authorization request that redirects the user to API URL for authorization. """ return redirect(get_link()) -
How to Implement Biometric Authentication on a ReactJS Web Application using a USB Fingerprint Scanner
I currently have a web application set up using ReactJS for the front-end, Django and Apache Guacamole for the back-end and MariaDB for the database. I also have a Secugen Hamster Plus Fingerprint Scanner which when plugged in to the computer, will be used for user authentication on the login page of the web application (using ReactJS). Does anyone know how I can go about writing code to retrieve fingerprint images from the scanner to store them in the database using Django models, and then compare the stored fingerprint images with the user-inputted fingerprint when he attempts to login? I have been unsuccessful in finding any working examples or documentation for reference on the Internet. -
Django redirect is appending tuple to URL when used reverse
When I use success_url = reverse_lazy('weatherdata:sample-list') The URL it redirects to is: http://localhost:8000/weather/('/weather',) Instead of the expected: http://localhost:8000/weather/ For some context. These are my modules: main/urls.py urlpatterns = [ path('weather/', include(('weatherdata.urls', 'weatherdata'), namespace="weatherdata")), path('admin/', admin.site.urls), ] weatherdata/urls.py urlpatterns = [ path('', WeatherSampleList.as_view(), name='sample-list'), path('takesample', WeatherByLocationFormView.as_view(), name='take-sample'), ] And in my weatherdata/views.py class WeatherByLocationFormView(FormView): [...] success_url = reverse_lazy('weatherdata:sample-list'), -
Gunicorn Allow All HTTP Headers
I read that the Django Development server filters Headers containing underscores as discussed here: Custom headers missing in requests to Django As I have no control over the headers and I need to receive them in the Django Application, it is mentioned that this can be done with Gunicorn. Is there a special configuration of gunicorn required such that it accepts all headers? -
raise JSONDecodeError("Expecting value", s, err.value) from None Python
I sometimes have this problem. But it's always resolved. This time impossible to find a solution. There are many post for the same subject but no resolution in my case. I am trying to get data from my api. It sometimes works(with data without none value) and with the data containing None value, it doesn't work. I think the problem is about the none values. I have this error Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 75 (char 74) Any help is appreciated. @api_view(['GET']) def edges_of_a_network(request, pk): try: roadnetwork = RoadNetwork.objects.get(pk=pk) except RoadNetwork.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) else: edges = Edge.objects.filter(network=roadnetwork) edges = str(list(edges.values("edge_id", "name", "length", "speed", "lanes"))).replace("'",'"') edges = json.loads(edges) edges = json.dumps(edges, indent=2) if request.method == 'GET': return HttpResponse(edges, content_type="application/json") screenshot -
Laravel Model default permission (View, Add, Change and Delete) same as Django default permissions
Is there a way to generate default permissions for each model in laravel, same as in django models. Example : after creating Post model, default permission will be auto created, such as : can_view_post, can_create_post, can_change_post, can_delete_post Please kindly drop your idea below. Thanks in advance. -
Something to change front-end with respect to back-end?
I want to know that is there anything that check backend for data if it is changed or not. If the data is changed then it will update frontend also without reloading the page, without any click or some event or without using setInterval method (Javascript). Please help. (Note: I am using Django as backend framework.) -
How to use jQuery on Django Media Form
i'm trying to inject extra javascript and jQuery on Django form through Media meta class. I return a form to the create.html template and rendered ok with js functions was executed but not jQuery functions. base.html for templates: ... {% block content %} {% endblock %} ... {% block javascript %} <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> ... <script type="text/javascript"> console.log('base.html js'); </script> {% endblock javascript %} create.html: {% extends "base.html" %} {% load static %} {% block javascript %} {{ block.super }} <script type="text/javascript"> console.log('create.html js'); </script> {% endblock javascript %} {% block content %} {% if form %} {{ form.media }} {% include 'form.html' %} {% endif %} {% endblock content %} form.html: {% load static %} {% for field in form %} {{ field|add_class:"form-control" }} {% endfor %} forms.py: class PlaceForm(forms.ModelForm): class Media: js = ( 'js/custom_tag_widget.js', ) custom_tag_widget.js: $(document).ready( function() { console.log('form media js'); }); I have this console output and appear an error: form.html js ReferenceError: $ is not defined base.html js crear:562:15 create.html js Anybody could help me please ? Thanks in advance. -
Django-Tables2 get current page number
I have a simple Table where I use a LinkColumn to access a view which toggles a value from true to false, unfortunately this resets my list to the first page. Now it should be possible to pass a specific page into the table object: table.paginate(page=request.GET.get("page", 1), per_page=25) return render(request, "people_listing.html", {"table": table}) How can I pass the current page number to my view? The request does not include this info and I can't seem to reference self in the Table Class (which has an attribute Page at least) Any suggestions? -
Display a variable in a Django form
I am trying to display a value from the database to a form. So if a user filled his email address, when he is connected he will see it in the email address form. I already did a post about this but I didn't get a lot of answer so I won't show my code this time but just ask you : Do you have an example of how to do it please ?