Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
To do work of mage.py in django without using it
I am making a project using amazon_kclpy in docker, i am directly running a file through docker command CMD $(amazon_kclpy_helper.py --print_command --java /usr/bin/java --properties ./code/apps/events_consumer/main.properties), in main.properties folder there is a comand to run base.py file, now i want to save data in redis, i am doing everything right, i checked it through python manage.py shell, it runs perfectly, but when i am trying by directly running, it is not saving data, also without python manage.py shell i tried to save data using only interpreter python commnd and it is also not able to save data, i want to know is there any way to do the work of manage.py file without running it. or any other method to make it work. -
bulk_update_or_create option is available in django?
I need to do a bulk create or update operation on a table , like update_or_create, is there any option available for bulk_update_or_create ? chart_data_obj = StockHistory( id=uuid, date=datetime_object, open=float(data['open']), close=float(data['close']), high=float(data['high']), low=float(data['low']), change=float(data['change']), change_percent=float(data['changePercent']), symbol_id=ticker_symbol ) chart_data_obj_list.append(chart_data_obj) StockHistory.objects.bulk_create(chart_data_obj_list) -
NoReverseMatch at /products/ "adding products to the basket"
I am fairly new and working on a project and want to just add products to the basket I have struggled with this for a few days and just don't know what to do to make it work. can anybody help me or refer me to some page that can help me? Thank You NoReverseMatch at /products/ Reverse for 'addtobasket' with arguments '('Python Tutorial',)' not found. 1 pattern(s) tried: ['productapp/\.\./basket/$'] models: class Products(models.Model): products_name = models.CharField(max_length=30) pub_date = models.DateTimeField(auto_now=True) price = models.CharField(max_length=10) note = models.CharField(max_length=200) inventory = models.IntegerField(default=1) product_pic = models.ImageField(upload_to ='images/', default='images/broken/broken.png') def __str__(self): if (self.inventory<=0): return self.products_name + ' (Out of Stock)' return self.products_name class Basket(models.Model): products = models.ForeignKey(Products, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) amount = models.IntegerField(default=1) def __str__(self): return str(self.products) urls: app_name = 'productapp' urlpatterns = [ path('products/', views.products, name='products'), path('basket/', views.basket, name ='basket'), path('', views.home, name='home'), path('../basket/', views.addtobasket, name='addtobasket'), ] views: def products(request): products_list = Products.objects.order_by('-pub_date') context = {'products_list': products_list} return render(request, 'productapp/products.html', context) def basket(request): basket_list = Basket.objects.order_by('-pub_date') context = {'basket_list': basket_list} return render(request, 'productapp/basket.html', context) def addtobasket(request, name): basket = Basket.objects.all() product = Products.objects.get(Products=name) basket.products.add(product) return HttpResponseRedirect(reverse("basket")) html: <body> <section> {% block content %} {% if products_list %} {% for product in products_list %} <div> … -
Charts.js in Django: Charts cannot appear
I am trying to create a charts app for my django project using Chart.js. I tried doing the very basic thing which I see in Youtube videos - which is to copy and paste the sample code given in https://www.chartjs.org/docs/latest/ in my file chart.html, but the chart doesn't appear when I tried running the project. I have added the script tag with the chart.js link to my base.html, so I am very confused of what went wrong. The following is my code: base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.min.js" integrity="sha512-5vwN8yor2fFT9pgPS9p9R7AszYaNn0LkQElTXIsZFCL7ucT8zDCAqlQXDdaqgA1mZP47hdvztBMsIoFxq/FyyQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <title>{% block title %}{% endblock title %}</title> </head> <body> {% block scripts %} {% endblock %} {% block content %} {% endblock %} </body> </html> chart.html {% extends 'base.html' %} {% block title %}Genre Popularity Ranking{% endblock title %} {% block scripts %} <script> $(document).ready(function(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: … -
how to keep logged in user in the current page and not to let him go to home from the address bar?
I want to keep the logged in user in the current page that he is viewing and not allow him to visit the home page again without loggin out either by pressing the backbutton provided by the browser or form the address bar. Is there any decorator that i can use, i tried to write on form a tutorial but i couldn't figure out how to keep the user in the current page. If there is any auto logout method availble please suggest me. decorators.py def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('current_page') else: return view_func(request, *args, **kwargs) return wrapper_func views.py @unauthenticated_user def index(request): return render(request, 'index.html') -
Object permissions in Django based on the value of a specific model attribute
I am trying to figure out how to setup some permisions to access and change some models in Django. I think that the built-in permissions system is not flexible enough and I am pretty sure that the answer is in Django Guardian, but I have not been able to figure out how to apply it to my case. The structure of models I have is way more complex, but I think the following simplified use case illustrates my bottleneck when setting permisions, and that if I sort that out, I should be able to apply it to the rest of the models, where needed. Let's consider the following three models: Organization: A Research organization, typically a university. User: A registered user of the web app, who can be a Contributor (default) or a Maintainer (all Maintainers are also Contributors). These two are Groups at the moment, but I am open to try other aproaches if that's better. The user will always belong to an Organization ValuableData: Some data obtained as a result of some research. It is added by Contributors and they belong to the Organization the user belonged to at the time of adding the data. It also has … -
Django: IntegrityError null value in column "user_id" of relation "" violates not-null constraint
I am trying to save data to the db but I am getting this error. I think I understand the error but am not sure how to correct it. Basically I am trying to post a review for a product and it seems like when trying to save to the DB it doesn't know which user is saving this review? I believe user_id is null for whatever reason. But honestly I could be wrong, I am kind of stuck at this point. I feel as if the easy solution is simply to set null = true in my user model but I do not want to do that. Any help is greatly appreciated models: class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) rating = models.DecimalField(max_digits=2, decimal_places=1, validators=[MinValueValidator(Decimal('0.1'))]) comment = models.TextField(validators=[MinLengthValidator(10)]) date = models.DateField(auto_now=True) def __str__(self): return str(self.user) class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('product', args=[self.slug]) def save(self, *args, **kwargs): self.slug = slugify(self.shortened_name) super().save(*args, **kwargs) def get_add_to_cart_url(self): return reverse('add_to_cart', …