Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Drf token authentication password reset
I'm wondering whether Django rest framework token authentication has password reset property. I have a Django app where I'm using token authentication to register and login users. But I was told that in order for me to implement password reset in the Django app I have to switch to packages like JWT or Knox. But I would like to use drf token authentication without switching to jwt or Similar package. How should I go about this, is it possible? -
This is an online shopping program. I am getting some error while submitting . The serializer is not getting valid
The data is not getting submitted. I tried many trial and error methods. I want to submit some values which are user-defined and some by their calculations. models.py class Cart(models.Model): item_name = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) store_id = models.CharField(max_length=10) order_price = models.IntegerField() user = models.ForeignKey(CustomUser, on_delete= models.CASCADE) serializer.py class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = "__all__" views.py class AddToCartAPI(APIView): def post(self, request, *args, **kwargs): serializer = CartSerializer(data = request.data) email = request.data.get('email') user = CustomUser.objects.get(email=email) if serializer.is_valid(raise_exception=True) : store_id = serializer.data.get('store_id',None) quantity = serializer.data.get('quantity',None) item_name = serializer.data.get('item_name' ) item = Item.objects.get(item_name=item_name) total_price = (item.price) * int(quantity) serializer.save(user=user,order_price = total_price) return Response({"items added to cart"}, status=status.HTTP_200_OK) return Response({"message": "Invalid request?????"}, status=status.HTTP_400_BAD_REQUEST) -
Connecting IoT Device with HTTPS Endpoint (Django Web App) via AWS IoT Core
Web technology and aws are new to me. My goal is to send data from a device to Django web app via AWS IoT Core. In AWS IoT Core, there is an option to added HTTPS endpoint for Routing data directly from IoT Core to web services. I have been able to receive data from device to AWS IoT Core and add HTTPS endpoint (Django web app hosted on Heroku) by adding key received on Heroku log from AWS. In AWS, it shows endpoint enabled after adding the key. Now, whenever device sends payload, I am expecting the payload to be routed to web app. I am watching log to verify this, but I cannot see data. I am expecting that once payload appears in log, I should be able to read data using HTTP GET and display on html frontend. Is my expectation correct or am I missing something? -
Inconsistency Errors in kombu using celery and redis with the key '_kombu.binding.reply.celery.pidbox'
I have two Django sites (archive and test-archive) on one machine. Each has its own virtual environment and different celery queues and daemons, using Python 3.6.9 on Ubuntu 18.04, Django 3.0.2, Redis v 4.0.9, celery v 4.3, and Kombu v4.6.3. This server has 16 GB of RAM, and under load there is at least 10GB free and swap is minimal. I keep getting this error in my logs: kombu.exceptions.InconsistencyError: Cannot route message for exchange 'reply.celery.pidbox': Table empty or key no longer exists. Probably the key ('_kombu.binding.reply.celery.pidbox') has been removed from the Redis database. I tried downgrading Kombu to 4.5 for both sites per some stackoverflow posts and setting maxmemory=2GB and maxmemory-policy=allkeys-lru in redis.conf per celery docs (https://docs.celeryproject.org/en/stable/getting-started/backends-and-brokers/redis.html#broker-redis); originally the settings were the defaults of unlimited memory and noeviction and these errors were present for both versions of kombu I still get those errors when one site is under load (i.e. doing something like uploading a set of images and processing them) and the other site is idle. What is a little strange is that on some test runs using test-archive, test-archive will not have any errors, while archive will show those errors, even though the archive site is not doing … -
How would I automatically make models just by the information from uploading a CSV file in django? As opposed to manually making models in models.py?
Hello I would like to make an automatic model maker where it would parse through the csv file that is uploaded via form. It then would make a new model every time with their respective fields. Does anyone know how to do this? -
How to disable inline labels in django inline admin?
In my Django admin, I want to disable the below-shown paragraph. Please help me out. I am new to changing djano admin. Image Here Here is my current admin.py class ImageInlineAdmin(admin.StackedInline): model = Image max_num = 1 class BlogAdmin(admin.ModelAdmin): inlines = [ParagraphInlineAdmin, ImageInlineAdmin] list_display = ['heading','id'] Here are my models class Container(models.Model): heading = models.CharField(max_length=100, blank=True, default="") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.heading class Paragraph(models.Model): content = RichTextUploadingField() container = models.ForeignKey( Container, on_delete=models.CASCADE, blank=True) def __str__(self) -> str: return self.content P.S I am using Django CKeditor -
Dajngo admin ModelForm: how to get request and/or user loggin in my form to filter queryset?
I have a custom User class with a property that return a queryset And I have an Admin class that use a custom ModelForm with 2 ModelChoiceField and fone BooleanFields. I want to filter queryset of one ModelChoiceField using user property but my problem is that I do not have access to request or user in my ModelForm. I try to use method get_form_kwargs I use for 'normal CBV' but it doen't work as this method do not exist in ModelAdmin admin.py class User_TableAdmin(SimpleHistoryAdmin): def __init__(self, model, admin_site): super(User_TableAdmin,self).__init__(model,admin_site) self.form.admin_site = admin_site # capture the admin_site form = User_TableAdminForm **# How to request object to my form?** list_display = ('id','user','table','can_download') search_fields = ('user','table','can_download') forms.py class User_TableAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(User_TableAdminForm, self).__init__(*args, **kwargs) # add the 'green +' button to create a new user (green + button suppress when overidding field with ModelChoiceField) self.fields['user'].widget = RelatedFieldWidgetWrapper( self.fields['user'].widget, self.instance._meta.get_field('user').remote_field, admin_site) class Meta: model = User_Table fields = '__all__' # display only tables of study database that user workin: User property # tables = self.user.can_download tables = Table.objects.all() **#<- I would like to use something like request.user.can_download** user = forms.ModelChoiceField(queryset = User.objects.all(), label = "User", widget = forms.Select()) table = forms.ModelChoiceField(queryset = … -
What is the best technique for real time server-client communication?
I need to create a web site with Flask or Django where I can plot real time sensor (IOT) reading without loosing any information. is sockets the best solution ? or there exists another solution which serve better for this task ? -
Django Rest Framework pass value in dynamic url into queryset
I have have a dynamic url that will display the same page to the user but with specific data depending on the value that is in the url. I am trying to set up a REST serializer that will return the filtered data based on the value that is in the url. I am not sure how to pass this value in the url into the queryset class I have. urls.py urlpatterns = [ path('sets/<str:setCode>/sets-individual-data', SetsIndividualData.as_view(), name='sets-individual-data'), } view.py class SetsIndividualData(ListAPIView): serializer_class = SetDetailsSerializers def get_queryset(self): queryList = Card.objects.filter(code=setCode) return queryList -
Why I cannot see a error message from ValidationError Django?
I have done what is written on Django Documentation and I have tried several Youtube tutorials, including Stackoverflow's advice. However, I could not make the message "Validation Error" appear on the template. When I click the button to create a post whit bad_word, I redirect to the same page, the post isn't saved but the form doesn't show me the message. I tried to save in a print({{ form.errors }}) in the view and the terminal showed the message that I want to see in the template: contentError So I don't know what I'm doing wrong... #view.py if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] username = User.objects.get(username=f"{request.user}") new_post = Post(user=username, title=title, content=content, datetime=timezone.now()) new_post.writeOnChain() cache.expire("cache", timeout=0) return HttpResponseRedirect("/") else: form = PostForm() return render(request, "api/homepage.html", {'form': form, 'postList': postList}) > #forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'content',) def clean_title(self): title = self.cleaned_data['title'] if "bad_word" in title: raise forms.ValidationError("Error") return title def clean_content(self): content = self.cleaned_data['content'] if "bad_word" in content: raise forms.ValidationError("Error") return content #template <div class="p-3 forms m-3"> <form class="crispy" action="{% url 'homepage' %}" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn buttons" value="Create Post"> … -
Cannot import name 'Context" from 'django.template.base' when using django-social-widgets
When trying to include django-social-widget on Django 3.2.4, I encountered an error: File "C:\Python39\lib\site-packages\django\template\backends\django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'social_widgets.templatetags.social_widget s': cannot import name 'Context' from 'django.template.base' (C:\Python39\lib\site-packages\django\template\base.py) How can I solve this problem? -
'ListBlogPost' object has no attribute 'get_object' django
I am using forms in my list view for review post before it publish. If I select publish then it will be show in my template otherwise not. It's seems to me everything okay. But why I am getting this error 'ListBlogPost' object has no attribute 'get_object'. Here is my code: views.py class ListBlogPost(ListView,FormView): model = Blog template_name = 'approval-blog-post.html' form_class = AdminBlogFrom def get_success_url(self): return reverse('approval-blog') def get_context_data(self, **kwargs): data = super(ListBlogPost, self).get_context_data(**kwargs) data['blog_admin_form'] = AdminBlogFrom() return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return self.form_valid(form) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') return self.form_invalid(form) def form_valid(self, form): form.save() return super(ListBlogPost, self).form_valid(form) froms.py class AdminBlogFrom(ModelForm): class Meta: model = Blog fields = ['is_published','author','slug'] models.py author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) title = models.CharField(max_length=300,unique=True) body = RichTextUploadingField() slug = models.SlugField(max_length=255,unique=True) created_at = models.DateTimeField(auto_now_add= True,blank=True,null=True) updated_at = models.DateTimeField(auto_now= True,blank=True,null=True) CHOICES = ( ('published', 'published',), ('pending', 'pending',), ('rejected', 'rejected',), ) is_published = models.CharField( max_length=10, choices=CHOICES,default='pending' ) #approve-post.html <form method="POST"> {% csrf_token %} {{form}} <button class="btn btn-info">Publish</button> </form> When I am clicking on publish button I am getting this errror ListBlogPost' object has no attribute 'object_list' -
On running django app gives error django.template.library.InvalidTemplateLibrary: Invalid template library specified
I am getting this error across all my django projects. Some settings have been changed. Whats the problem? I get the following error on python manage.py runserver django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'pinax.templatetags.templatetags.shorttimesince_tag': No module named 'django.utils.tzinfo' -
Creating a dropdown menu in python django and adjust website values according to the selection
I have a django framework with a template that has different versions in terms of content. As a User I would like to be able to select the version I want in a dropdown menu and adjust the contents of the website accordingly. Is there a way to create a dropdown menu like that if the content only changes in terms of certain values displayed on the website (e.g. if "3" is selected in the menu, change all the according placeholders to "3") without requiring the use of backend logic or some reactive frontend framework? -
Django: 'str' object has no attribute 'get'
I am trying to effectively make a Reddit clone just for practice with Django and I am trying to set up my upvote/downvote system with just a simple integer(upvote adds one, downvotes subtract one) however when I hit my "upvote" or "downvote" buttons it gives me the error 'str' object has no attribute 'get'. I have no idea what is causing this and all of the other answers with this error were not at all related, any help would be awesome. My Model: class post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) ranking = models.IntegerField(default=0) My Views: class Feed(ListView): model = post template_name = 'thefeed/feed.html' def UpvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking+=1 selected_post.save() return reverse('feed-home') def DownvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking-=1 selected_post.save() return reverse('feed-home') My Urls: urlpatterns = [ path('', views.Feed.as_view(), name="feed-home"), path('post/<int:pk>/downvote', views.DownvoteView, name='downvote-post'), path('post/<int:pk>/upvote', views.DownvoteView, name='upvote-post'), ] My Feed.html(homepage): {% block content %} <div class="announcement"> <h5 style="background: yellow;">Forum.Chat is the Internet's home for debate on any topic, keep it civil!</h5> </div> <br> {% for post in object_list %} <div style="margin-bottom: 2%;"> <h3><a href="{% url 'feed-post' post.pk %}">{{post.title}}</a><a href="#"></h3> <p><a href="#">By: {{post.author}}</a><a href="{% url 'edit-post' post.pk %}"> Edit Post</a></p> <p><a href="{% url 'upvote-post' pk=post.pk %}">Upvote</a><a … -
Django Views and Model: Create ManyToMany User relationship with all other relationships - triangular number series problem
I have 4 models: class User(models.Model): ... class Invite(models.Model): ... user = models.ForeignKey( User, related_name="invites", on_delete=CASCADE) class House(models.Model): ... members = models.ManyToManyField(User, related_name="houses") class Balance(models.Model): balance_owed = models.DecimalField( max_digits=10, decimal_places=2, default=0) two_users = models.ManyToManyField(User, related_name="between_balance") As a User joins a house, I want that user to create a balance with ALL other users in the house. Number of Balance instances per User will start to form a triangular number sequence (for ref see https://www.101computing.net/triangular-numbers/ ); The pattern for number of Balance instances per User would look like: 1, 3, 6, 10, 15 etc. And on a grid, the relationships would look like: User1 User2 User3 User4 User1: x bal bal bal User2: bal x bal bal User3: bal bal x bal User4: bal bal bal x This is where I'm lost! In my views.py I tried: my_invite.house.members.add(this_user) # this_user is the one joining the house all_users = this_house.members.all() # store all members of house, including new user for user in all_users: balance_obj = Balance.objects.create() balance_obj.two_users.add(user) balance_obj.two_users.add(this_user) Unfortunately this does not satisfy a forming of relationships between every single user. I'm guessing this requires some kind of algorithm perhaps? Thank you in advance for your input -
Jsonresponse not returning add data in quaryset
I am using Ajax quary to get filtered data to template. I am appending new data value in quaryset. But json response not included newly append values. Please guide to get append values to template by json. my ajax is: $.ajax( { type: "GET", url: "/waccounts/listaccttrans_date", dataType: "json", data: { {#'id': 1235,#} 'csrfmiddlewaretoken': '{{csrf_token}}' }, success: function (accts) { console.log(accts); ....... my view is: def listaccttrans_date(request): if request.method == "GET": alltrans = FinTransDetail.objects.filter(fd_acct=1601) openbal = 0 # to add new items# for item in alltrans: acctname = item.fd_acct.AcctName transdate = item.fd_no.fh_dt openbal = openbal + (item.fd_debit - item.fd_credit) item.balance = openbal item.acctname = acctname item.transdate = transdate accts=list(alltrans.values()) return JsonResponse({'accts':accts}) my console output not included added values: 0: fd_acct_id: "1601" fd_credit: "1250.00" fd_debit: "0.00" fd_detail: "office files purchased" fd_no_id: 119 fd_posting: false fd_tax: "0.00" id: 45 please note in other view (not for ajax) they are included while rendering: context = {'alltrans': alltrans,} return render(request, 'waccounts/detail_account_trans.html', context) -
how to insert values into mysql database through django restapi
I am going through some trouble lately, I have created 2 tables which are User and Phones models.py from django.db import models class User(models.Model): userid = models.AutoField(primary_key=True,default=None) name = models.CharField(max_length= 100) age = models.IntegerField() class Meta: db_table = 'user' class Phones(models.Model): phoneId = models.AutoField(primary_key=True,default=None) userid = models.IntegerField(null=False) numbers = models.CharField(max_length = 15, null=True) phonesCountryCode = models.CharField(max_length=5,null=True) class Meta: db_table = 'phones' I want to send a post request like this : "User": [ { "name": "abc", "age": 100" }, { "name": "pqr", "age": 50 }, { "name": "xyz", "age": 80 } ], "Phones": [ { "numbers": "65452124", "phonesCountryCode": "+93" }, { "numbers": "45215124", "phonesCountryCode": "+93" } ] multiple data can be added into both databases. I have created a view and tried to add data like that but failed views.py : lass UpdateAll(APIView): def post(self, request ): userid = User.objects.latest('userid').userid name = request.data.get('name') age = request.data.get('age') numbers = request.data.get('numbers') phonesCountryCode = request.data.get('phonesCountryCode') User_Serializer = UserSerializer(data={"name":name,"age":age}) if User_Serializer.is_valid(raise_exception=True): User_Serializer.save() Phone_Serializer = PhoneSerializer(data={"userid":userid,"numbers":numbers,"phonesCountryCode":phonesCountryCode}) if Phone_Serializer.is_valid(raise_exception=True): Phone_Serializer.save() return Response({'status': 'Success'}) finaly serializer.py class UserSerializer(serializers.ModelSerializer): name=serializers.CharField(required=True) age = serializers.IntegerField(required=True) class Meta: model = User fields= '__all__' class PhoneSerializer(serializers.ModelSerializer): userid = serializers.IntegerField(required=True) numbers = serializers.CharField(max_length = 15) phonesCountryCode = serializers.CharField(max_length=5) class Meta: model = Phones … -
Django executes almost all .py files at request
I have Django project with 6 apps. I added logging to every app's init.py, models.py and views.py files (inside any classes/functions) and I've seen that on every GET/POST request almost every of this files are executed. Why is this happening and is there any way to change this behavior? -
How to copy executables in dockerfile multi-stage
I have an django image with multi-stage build. I install dependencies required by the the app, e.g heroku, psql, etc in the first stage. But when when I copy the bin path to the 2nd stage, they don't work in the app. dockerfile FROM python:3.8-slim as base WORKDIR /test # libpq-dev and gcc help with psycopg2 RUN apt-get update \ && apt-get install -y curl unzip git libgtk-3-0 locales postgresql-client libpq-dev gcc gnupg \ && apt-get clean all \ && rm -rf /var/lib/apt/lists/* RUN curl -sL https://deb.nodesource.com/setup_10.x | bash \ && apt-get install nodejs -yq \ && apt-get clean all # Install yarn RUN npm install -g yarn RUN curl https://releases.hashicorp.com/terraform/0.13.6/terraform_0.13.6_linux_amd64.zip -o /tmp/terraform.zip && cd /tmp && unzip /tmp/terraform.zip -d /usr/local/bin RUN curl https://cli-assets.heroku.com/install.sh | sh COPY . . RUN pip3 install --no-cache-dir pipenv \ && pipenv install --deploy --system \ && mv src/* /usr/local/lib/python3.8/site-packages/ RUN python manage.py collectstatic --no-input FROM python:3.8-slim RUN apt-get update WORKDIR /test COPY post-install.sh /test COPY media.tar.gz /test COPY --from=base /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=base /usr/local/bin/ /usr/local/bin/ COPY --from=base /test/static/ /test/static/ ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV LANG C.UTF-8 # Run the image as a non-root user RUN adduser --disabled-password --gecos "" django USER django … -
I can't display my var in template even if var is in my context
My variable created in my view, so i can find it in my contexte of my view but when i want to display it in template base.html that doesn't work my view def accueil(request): if request.method == 'POST': form_plot_one_way = plot_onewayForm(request.POST) if request.POST.get('Plot'): if form_plot_one_way.is_valid(): listbox_values = [key for key in fig_dict.keys()] print(listbox_values) else: form_plot_one_way = plot_onewayForm() context = locals() print(context) return render(request, 'base.html', locals()) my html <select name="Key_" id="Key_" size="5"> {{ listbox_values }} {% for list in listbox_values %} <option> {{ list }} </option> {% endfor %} </select> in my context : {'listbox_values': ['Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare']} terminal : ['Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare'] -
Problems with different types of test databases
I am working on a large Django project with lots of tests. To improve the performance I want to make the test database persistent - by default, it's in memory. One exemplar test class runs perfectly fine in in-memory Sqlite3. When I switch to MariaDB, I get stacked exception for all but the first test case: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. and MySQLdb._exceptions.OperationalError: (2006, '') So I thought it may be a problem with MariaDB, I switch to file-based SQLite3. But there, again - on the same tests! - a stacked exception: sqlite3.ProgrammingError: Cannot operate on a closed database. and django.db.utils.ProgrammingError: Cannot operate on a closed database. The interesting thing is that lots of tests work and the code looks good. I tried to get the broken query which causes the transaction in MariaDB to fail but after searching around for an hour, I ended up with zero results. Looking for closed database connections to SQLite always points to some custom shenanigans what I am not doing. I am running Django (v2.2.23) on Windows 10 Pro with PyCharm (latest). -
Payment Integration using Just Card Number Visa/MasterCard etc | No Stripe, No Paypal, No PayTm, No RazorPay etc
I am developing a web app that supports Online payment in Django. Stripe, Paypal, RazorPay, etc does not support my country. I would like to have those type of payment integration which Google and some other companies uses. Like: Payment through just Card Number + Expiry date and 3-digit pin(from the back of card) Is there any library or method available to do this task using Django Thanks in advance -
Sorting queryset by repeating values in django
There is a school with a total of 12 classes. 9-A, 9-B, 9-C 10-A, 10-B,10-C 11-A,11-B,11-C We have students in each class and I want to order a queryset that contains these students. We can access the degree and letter of the class separately. I want to order them like that : 9-A 10-A 11-A 9-B 10-B 11-B 9-C 10-C 11-C (A B C is not sorted, it should be random. I want to sort 9 10 11.) It will repeat itself every three times like 9,10,11,9,10,11. I couldn't figure how to write a query to sort them with this algorithm. students= Student.objects.distinct().filter(exams__schedule_id=1).order_by('') Here is the student queryset. How should I fill order_by part ? -
Render django-recaptcha's script tag inside head tag
I'm facing issue while rendering django recaptcha inside form because it is adding script tag along with captcha input. <div class="g-recaptcha" data-sitekey="KEY-HERE" data-callback="correctCaptcha"></div> <script type="text/javascript" src="https://www.google.com/recaptcha/api.js?hl=en"></script> How to avoid rendering along div tag and move this script to head tag?