Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Catch a Stolen Token Key in Django Rest Framework
Whenever I grab a token from Token, I check for client's device serial number along with key to reduce the risk of serving hijackers. See the details below. I have a custom Token model that stores device serial number of the client's mobile phone. My models.py is located under my app name called accounts class Token(rest_framework.authtoken.models.Token): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='accounts_token_user_set') logged_in_device_serial = models.CharField(max_length=36, null=False, blank=False) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'logged_in_device_serial'], name='uq_token_userloggedindeviceserial') ] My settings.py considers TokenAuthentication and IsAuthenticated REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'accounts.authentication.TokenAuthentication', ] } authentication.py is located here accounts -> authentication.py import rest_framework.authentication from .models import Token class TokenAuthentication(rest_framework.authentication.TokenAuthentication): model = Token That's how I grab my token. I always pass the key AND the device number of the caller to avoid serving stolen keys. Token.objects.get(key=..., logged_in_device_serial=...) If I return a token using the key alone Token.objects.get(key=...), I might be at the risk of serving hijackers who may have stolen keys from my customers. Instead I'm checking key's device's number that was registered with the key the first time I created the token. I think checking key and logged_in_device_serial offers an extra protection against hijackers unless hijackers manage to get the … -
Django get_absolute_url without Id
I want to use get_absolute_url, however, I don't want to use the model id as then people will know the order of that instance's creation (because Django increments ids by 1). I know that Instagram uses letters here. What are some common alternatives? Thanks! -
Failing to make a POST request from ReactJS to Django
Hello so I am working on a Django and React project I am fairly new to the domain I can't understand why this is not working, so I would love to make a POST request to my API and save the contents to the database and the after then the function that is currently working to retrieve contents in my DB will do its work to update the website. So after I made the POST request this is the response I get when I console logged: Response { type: "cors", url: "http://127.0.0.1:8000/api/upload-lecture/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false } I personally thought after getting a status code of 200 everything is fine but when I go check the database the is nothing new that was added. I even checked the with Django logs that were coming and this is what I got too: "POST /api/upload-lecture/ HTTP/1.1" 200 108 So I do not understand why the contents are not in the database. Code to my Api: Upload method: @api_view(['POST']) def videoUpload(request): serializer = LectureVideosSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Code to React:This is where I was trying to make the POST request import … -
How to upload multiple image with django rest api
I want to know how i can upload multiple image (list) in my views and get a Response like this : { "id":1, "title":"text", "roms":2, "image":[ "http:localhost:8000/media/images/houses/image1.png", "http:localhost:8000/media/images/houses/image2.png", "http:localhost:8000/media/images/houses/image3.png", ] } I have tried this way : models.py from django.db import models class House(models.Model): title = models.CharField(max_length=255) rooms = models.IntegerField() images = models.FileField(upload_to="images/houses/") def __str__(self): return self.title serializers.py* from rest_framework import serializers from .models import House class HouseSerializer(serializers.ModelSerializer): image = serializers.ListField(max_length=None,child=serializers.FileField) class Meta: model = House fields = '__all__' views.py from rest_framework import viewsets from .models import House from .serializers import HouseSerializer class HomeViewSet(viewsets.ModelViewSet): queryset = House.objects.all() serialiezer_class = HouseSerializer But it didn't work, i don't know how to write serializer and views to do this, any body help please. Thanks in advance -
Mimic Slack Groups Django
You know how in Slack, you can belong to many different groups? I have a similar structure in my Django app. In my User model: organizations = models.ManyToManyField(Organization, related_name='organizations') I am struggling to figure out how to store which organization the User is currently operating in. Similar to Slack, depending on what Organization they are in, different data will be displayed. Do I store it as a session variable? Do I make a model field for the current Group that they are in? What is best to do here? -
CSRF cookie not set [Django/AngularJS]
First of all, this is not a duplicate question. I have tried all the related posts on stackoverflow but could not find a solution. I have a Django app for the backend and and AngularJS app for the frontend. I am using djangorestframework-jwt for API authentication. I have an API endpoint that does not require any authentication and I am getting this error only for this endpoint. In my django settings I have: ALLOWED_HOSTS = ['*'] and it does not include any CSRF_COOKIE_SECURE, CSRF_COOKIE_HTTPONLY, or SESSION_COOKIE_SECURE settings. The djangorestframework-jwt settings is: JWT_AUTH = { 'JWT_SECRET_KEY': SECRET_KEY, 'JWT_ALGORITHM': 'HS256', 'JWT_VERIFY': True, 'JWT_VERIFY_EXPIRATION': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3000), 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_AUTH_COOKIE': 'refresh-token' } I noticed that in the browser cookies if there is any refresh-token key then the endpoint works just fine. The problem arises when that key is not present in the browser cookies. I set 'JWT_AUTH_COOKIE': None or removed the following lines: 'JWT_ALLOW_REFRESH': True, 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_AUTH_COOKIE': 'refresh-token' from the JWT_AUTH settings but no luck. I also tried @csrf_excempt for that endpoint but that did not work either. Interestingly, when I send the request from postman it works. Here is the request I am sending from the frontend: $http({ url: … -
Model field validation in Django
I want to validated a custom form field . I have made a model for contact us form . fields are name, subject, email and message . Now user from "DIU" company can contact us only . email must have '35-' and '@diu.edu.bd' in the email address . How can i validate this email field like this ? Please help -
Adding comment feature inside DetailView Using GenaricForeignKey
I invested lots of time to fix it but i was unsuccessful so i am hopping here i will get help from you. What i am trying to do is i want to add comments on detail page through comment form i know my post method is incomplete what should i add in this method so i get posted comments. I am using ContentTypes framework to make it reuseable. comments/models.py class GlobalComment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() published = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') # by default it will take these two parameters if u dont provide objects = GlobalCommentManager() def __str__(self): return self.body[:10] comments/forms.py class GlobalCommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) body = forms.CharField(widget=forms.Textarea) myapp/views.py class ProductDetailView(DetailView, FormMixin): model = Product form_class = GlobalCommentForm def post(self, request, *args, **kwargs): instance = self.get_object() # to get the particular product instance initial_data = { 'content_type': instance.get_content_type, # get_content_type defined in models.py as a property to get the content type of the model 'object_id': instance.id } if request.method == 'POST': global_comment_form = GlobalCommentForm(request.POST, initial=initial_data) if global_comment_form.is_valid(): print(global_comment_form.cleaned_data) global_comment_form.save() return ....missing..... return ....missing... def get_context_data(self, **kwargs): particular_product = self.get_object() # return the particular … -
Elastic Beanstalk instance profile for Secrets Manager
I am new to AWS and want to use Secrets Manager in my Django app on Elastic Beanstalk. How can I create an elastic beanstalk instance profile and use it for secrets manager? Thanks! -
'function' object has no attribute 'categories'
I want to solve this problem I am a newbie so I don't understand this problem so please help me try to solve this. I want to show related products in the product detail page I follow some tutorial but I don't understand this. models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from django.db.models.signals import post_save,pre_save # Create your models here. class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def get_related(self, instance): products_one = self.get_queryset().filter(categories__in=instance.categories.all()) product_two = self.get_queryset().filter(default=instance.default) qs = (products_one | product_two).distinct() return qs class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True,blank=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default=True) categories = models.ManyToManyField('Category', related_name='product_category',blank=True) default = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='default_category', null=True,blank=True) objects = ProductManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('products:product_detail',kwargs={'pk':self.pk}) class Category(models.Model): title = models.CharField(max_length=120, unique=True) slug = models.SlugField(unique=True) description = models.TextField(blank=True,null=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('product_categories:categories_detail',kwargs={'slug':self.slug}) -
Python createsuperuser - Django
Everything is going good in the username and email fields, they're writable, but when it comes to the password field, I'm not allowed to write anything, even if i pressed enter twice to give me the bypass password, it doesn't allow me.. What should I do to let the password field writable and enable me to create the admin user? -
oder by nulls first in descending order in django
I want to order my data in Django admin in descending order, but I want the null field which represent task that has not ended to come to the top first following the descending order of dates. for Example End date is listed like this -- -- Dec 5 ,2018 March 2,2017 and not like this Dec 5 ,2018 March 2,2017 -- -- in my view.py I have tried in this way class TaskViewset(Viewsets.ModelViewset) queryset = Task.objects.filter(end_date__isnull=True).order_by("-end_date") This limit what was return back to only data where end_date is null. How can i do this to return data including those Task that have ended while returning the not ended task first? Thanks for your help. -
Passing an html element from anchor tag to django view
I would like to know how i can pass the html link element as a string into a django view and have the information rendered on that specific view. to be clear: I have this In html {% if list_1 %} <h3 class="display-5"><u>{{ choice }}</u></h3> <div class="row justify-content-md-center row-eq-height"> {% for item in list_1 %} <div class="col-md-4"> <a id = "search_item" name = 'search_item' href="{% url 'search_stock' %}" value={{ item }} target="_blank">{{item}}</a> A django view rendered the items from a list and each item would ideally be clickable and the specific item would be passed into this view: def search_stock(request): search_item = request.POST.get('search_item') ticker_request = search_item ..... my urls.py reads as : path('search_stock', views.search_stock, name='search_stock'), The problem I think may be that the click action is not actually passing the value into the function based view and I am not sure how to work around this easily. Essentially once the information loads (each item is a link for a specific ticker), I would like the user to be able to click on that link with the ticker being passed into the search_stock function as a string in order to actually render the specific search_stock view. Much thanks now and in … -
null value in column "patient_id" violates not-null constraint DETAIL Django
I am getting this error in Django: null value in column "patient_id" violates not-null constraint DETAIL Even though my model field is: patient = models.ForeignKey(Patient, null=True, blank=True, on_delete=models.SET_NULL) What is it referring to with DETAIL? Why am I getting this error? Thanks! -
How to use url variables in class based views
I'm having problems with the url variables and the class based views, but mostly in the html or template because I don't know how to represent it, I'll show you the code so you can understand. urls.py app_name = 'app1' urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'), ] views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def get_queryset(self): ala = Post.objects.filter(stock__symbol=self.kwargs['sym']) return ala models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) Template (I'm having problems with Add Post(current) ) {% extends "app1/base.html" %} {% block body_block %} {% if stock_sym %} <h1> {{sym}} </h1> <a href ="{% url 'app1:addpost' StockNames.symbol %}">Add Post<span class="sr-only">(current)</span></a> {% if stocks %} <ul> {% for post in stocks %} <li><a href="{% url 'app1:article-detail' post.pk … -
Django Template engine, checking for time difference in Jinja2
I'm trying to check for some things before displaying my content. So right here I got some Invitation links for users to join our forum. When the ticket is sent to the user it's valid for 24 or 48 hours. So my goal is to check if the ticket is valid for now or it's expired. I have tried adding the timesince filter to my variable, but it's still not working. <td class="pt-3-half"> {% if query_time|timesince == invite.token_expires|timesince %}Not-valid {%else%}Valid{%endif%} </td> However, the current time is more recent, than the ticket expiration date, but the engine says that the ticket is still valid. I'm checking for these times: query_time = 2020-08-15 18:04.15 token_expires = 2020-08-13 22:33.16 -
How to integrate Web MIDI API with React frontend and Django backend
I'm fairly new to Django and React but have a good grasp of Python and JavaScript. What I'm trying to do is use the Web MIDI API to monitor some MIDI data, extrapolate some information from it and store that in a database. It's basically for a DAW, Software synth monitoring system, information can be transmitted as MIDI to the browser (via IAC) and then various pieces of information stored in the database. This needs to be done per user, with user data separation. I'm guessing I would need to implement a CRUD API. I currently have a Python project that does this and holds the data in memory formatted as JSON - the plan is to take this and turn it in to a Web App. I've watched and followed a bunch of tutorials on integrating Django & React and also found this boilerplate for a basic login system. https://github.com/justdjango/django-react-boilerplate If possible I'd like to use this and just add in the functionality I need, can anyone point me in the right direction of where to start and where I would add the additional code for the MIDI stuff to this boilerplate. There is another stage to this project … -
Django validation returns two errors instead of one
as the questions states i receive two errors in my template. Here is the code def create(request): full_content = forms.InputForm() if request.method == "POST": full_content = forms.InputForm(request.POST) if full_content.is_valid(): title = full_content.cleaned_data["title"] content = full_content.cleaned_data["content"] if full_content.clean_title():#Works full_content.create(title, content) context= { 'title' : util.get_page_name(title), 'entry' : util.get_entry(title), } return render(request, "encyclopedia/entry.html",context) #From here on its not valid: context = { 'form':full_content } return render(request, "encyclopedia/create.html", context) return render(request, "encyclopedia/create.html", { 'form':full_content }) And the forms.clean_title(): def clean_title(self): title_name = self.cleaned_data.get("title") filename = f'entries/{title_name}.md' if default_storage.exists(filename): raise ValidationError("This title is already taken") return title_name Ofcourse the create.html aswell: <h3>Create new entry</h3> <form action="{% url 'create'%}" method="POST"> {{ form.title.errors }} {% csrf_token %} <table> {{form.as_p}} </table> <button type="submit" value="save">Save</button> </form> Any ideas why i get two bullets?: This title is already taken This title is already taken -
Field 'id' expected a number but got 'abdullah123'
I hope all are safe and good! I am working on this below code, i am trying to get balance from the UserBalance table filter by username. I have tried using UserBalance.objects.filter(username=username) where i am actually getting error. Please help me out how can i proceed with this #views.py def login_validation(request): if request.method=='POST': username=request.POST.get("username") password=request.POST.get("password") user=auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) user_balance=UserBalance.objects.filter(username=username) #error_i_am_getting_here return render(request, "homepage.html", {'name':username, 'balance':user_balance}) else: return redirect("http://google.com/") else: return redirect("http://yahoo.com/") #models.py from django.db import models from django.contrib.auth.models import User class IncomeExpense(models.Model): entry_type=models.CharField(max_length=100) amount=models.IntegerField() details=models.TextField() capture_date=models.DateField() username=models.ForeignKey(User, on_delete=models.CASCADE) class UserBalance(models.Model): balance=models.IntegerField() username=models.ForeignKey(User, on_delete=models.CASCADE) I have pasted views.py and models.py code, Please help me to solve this problem. I tried using filter with username and its giving that error and i tried using get method also...but again getting same error. Also please explain me how get and filter works -
Redirect user to personal dashboard page after successful login
I am trying to redirect my user to his/her dashboard url after login: urls: (2 seperate apps) name = 'user' urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), ] name = 'register' urlpatterns = [ path('<slug>/dashboard/', DashboardView.as_view(), name='dashboard'), ] I have made a CustomLoginView to handle the custom succes url of the login. views (users app) class CustomLoginView(LoginView): def get_success_url(self, *args, **kwargs): return redirect('register:dashboard', kwargs={"slug": Bedrijf.slug}, Bedrijf=Bedrijf), Now I am getting the following error: Reverse for 'dashboard' with keyword arguments '{'kwargs': {'slug': <django.db.models.query_utils.DeferredAttribute object at 0x040A5970>}}' not found. 1 pattern(s) tried: ['(?P[^/]+)/dashboard/$'] I am guessing this is because the login is not yet successful and the query cannot get the slug for the logged in user to put use it in the url. Is this correct and does anyone have any suggestions to fix this? Or the used query is returning all of the slug fields in the database for every user and is therefore not capable to parse it right. Do I then need to pass a user=request.user or something? P.S. I am using Allauth to handle the authentication -
No module named 'requests' But it is showing in pip3 list
If I try to import requests then it is showing No module named 'requests'. If i try pip3 list then it is showing. pytz (2020.1) requests (2.24.0) rsa (4.6) setuptools (39.2.0) six (1.15.0) sqlparse (0.3.1) uritemplate (3.0.1) urllib3 (1.25.9) virtualenv (15.1.0) -
collectstaic command fails gives me post-processing error
While deploying my django-app to heroku I get this error .I disabled collectstatic and it pushed but when I went to the site it wasn't working.I tried a lot of things but nothing seems to work Post-processing 'vendors/owl-carousel/assets/owl.carousel.css' failed! Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 134, in collect raise processed whitenoise.storage.MissingFileError: The file 'vendors/owl-carousel/assets/owl.video.play.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f580a2b32e8>. The CSS file 'vendors/owl-carousel/assets/owl.carousel.css' references a file which could not be found: vendors/owl-carousel/assets/owl.video.play.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. my settings.py looks like this """ Django settings for personal_portfolio project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import django_heroku import os # Build paths inside … -
django + table2: issue in view to load table
I am trying to redirect a user to table on a click of button. Little background: the user input a value in a search bar, infos show up and there is link to click on that guides the user to another page containing info related to this value. My issue is in the structure of the view of this page containing the additional infos. the code look like this: @method_decorator(login_required, name='dispatch') class Supplier_items(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): query = request.GET.get('search_res', None) if query and request.method == 'GET': queryset = supplier.objects.all(supplier = query) table = supplier_items_table(queryset) RequestConfig(request).configure(table) export_format = request.GET.get("_export", None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table) return exporter.response("report_supplier_items.{}".format(export_format)) return render(request, 'Supplier_items.html', {'table':table}) else: return Response('Supplier.html') and the table look like this: class supplier_items_table(tables.Table): reference = tables.Column(gettext_lazy("item"),localize= True) stock_reel = tables.Column(gettext_lazy("stock on hand"),localize= True) en_cours_de_reception = tables.Column(gettext_lazy("on order"),localize= True) class Meta: model = Item fields = ('reference', 'demand_30_jours', 'stock_reel', 'en_cours_de_reception') template_name = "django_tables2/bootstrap4.html" Everytime, 'supplier.html' is returned meaning that it didnt work. I am confused about what is happening, can anyone see what I cannot? -
Django Forms: How to make form.fields by Model.QuerySet in dynamic?
I need to generate Django forms.Form object with filds not from Model.fields (Database Table Columns names), but by records in Model.Table. I have table Model in models.py: class MntClasses(models.Model): type = models.CharField(max_length=2, blank=True, null=True) class_subtype = models.CharField(max_length=45, blank=True, null=True) text = models.CharField(max_length=45, blank=True, null=True) explanation = models.CharField(max_length=45, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) views.py # Form generate class Form_classes(forms.Form): def __int__(self, *args, **kwargs,): super(Form_classes, self).__init__(*args, **kwargs) print("some") for fld_ in args: self.fields[fld_.name] = forms.BooleanField(label=fld_.text) #Main def page_Category_Main(request, post): db_table = MntClasses form_fld = db_table.objects.all() ''' This QuerySet 20 records returned of <MntClasses: MntClasses object (0-19)> type. QuerySet Filds Names: 'name','type','expalnation', 'text' ''': form_ = Form_classes(*form_fld) exit_ = { 'form': form_, } return render(request, template_name="category.html", context=exit_) It raise TypeError init() takes from 1 to 12 positional arguments but 20 were given So, i have no idea what does it mean this code taken from were: Auto-generate form fields for a Form in django: def __int__(self, *args, **kwargs,): super(Form_classes, self).__init__(*args, **kwargs) What is this "*args", how to use it? How can i generate Form.fields by QureySet form_fld.name in that case? -
Django | Error using class form-control in views field
When wanting to assign class to the fields (code_station and name_station) in the views, it returns an error. Instead if I apply class in forms there is no problem. What's going on? Thank you. Error: 'code_station'.widget.attrs.update({'class': 'form-control'}), AttributeError: 'str' object has no attribute 'widget' File: views.py: class StationUpdateView(LoginRequiredMixin,UpdateView): template_name = "station/update_station.html" model = Station fields = [ 'code_station'.widget.attrs.update({'class': 'form-control'}), 'name_station'.widget.attrs.update({'class': 'form-control'}), ] success_url = '/station/' login_url = reverse_lazy('users_app:user-login')