Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. How to realize the validation for Question object?
How to realize the validation to exist at least 1 right answer and 1 wrong answer for each Question object? from django.db import models class Test(models.Model): test_name = models.CharField(max_length=255) def __str__(self): return self.test_name class Question(models.Model): test = models.ForeignKey(Test,on_delete=models.CASCADE) question_text = models.TextField() def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_text = models.CharField(max_length=255) is_right = models.BooleanField(null=False,blank=False) def __str__(self): return self.choice_text -
How to solve the djongo.exceptions.SQLDecodeError: while trying to run the migrate command
I am creating a DjangoRestful app that uses SimpleJWT for authentication. When I try to add the Blacklist app and make migrations. i.e: py manage.py migrate as suggested in the documentation, I get the error below: raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',) Params: ([],) Version: 1.3.6 I should also mention I am using MongoDB as my database. Here is my installed apps list: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt.token_blacklist', 'drf_yasg', 'main', 'accounts', ] When I remove the app from the installed apps and run the command, there is no error. Anyone knows how to fix this? -
DJANGO: How to write and run the unit tests?
Whenever I run my unit tests, I use this command python manage.py test, but my tests are not running, I get the following message: System check identified 1 issue (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK NOTE: I am using MySQL Database instead of the default SQLite. Does this have to do anything with the unit tests anyway? I have following hierarchy of my project files and folders: --[PROJECT-NAME] ------apps ----------[APP-NAME] --------------migrations --------------templates --------------models.py --------------test.py --------------urls.py --------------views.py ------[PROJECT-NAME] ----------settings.py ----------urls.py ------manage.py And this is my tests.py file from django.test import TestCase from apps.accounts.models import User, Invitation class TestModels(TestCase): def test_sending_password_reset_email(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) email_sent = user.send_password_reset_email() self.assertTrue(email_sent) def test_accepting_invitation(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) accepted = invitation.accept(user, "testinguser@test.com", "TestingPassword1!") self.assertTrue(accepted) def test_cancelling_invitation(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) invitation.cancel() self.assertTrue(invitation.is_canceled) def test_sending_invite_user_email(self): user = User.objects.create( login = "testuser@test.com", email = "testuser@test.com", password = "TestPassword1!" ) invitation = Invitation.objects.create(created_by = user) message = invitation.send_invite_user_email() self.assertEqual(message, "Success") and these are the function signatures in my … -
Django dynamic url arguements missing
Can someone spot the mistake? What i'm expecting to happen is to dynamically pass in the ids of the classes I have created, so that I can update an entry I created in a previous form. Here is my HTML: <td><a class="btn btn-sm btn-info" href="{% url 'update_type_4_service' type_4_service.order_reference.id type_4_service.id %}>Update</a></td> Here is my urls: path('order/<str:pk_test>/update_type_4_service/<str:pk>', views.updateType_4_Service, name="update_type_4_service"), Here is my views: def addType_4_Service(request, pk_test): order = Order.objects.get(id=pk_test) type_4_service_form = Type_4_ServiceForm(order_reference=order) if request.method == 'POST': type_4_service_form = Type_4_ServiceForm(request.POST, order_reference=order) type_4_service_form.instance.order_reference = order if type_4_service_form.is_valid(): type_4_service_form.save() return redirect('/') context = {'type_4_service_form':type_4_service_form} return render(request, 'orchestration/type_4_service_form.html', context) This is the error: Reverse for 'update_type_4_service' with arguments '('', '')' not found. 1 pattern(s) tried: ['order/(?P<pk_test>[^/]+)/update_type_4_service/(?P<pk>[^/]+)\\Z'] -
Filter Django Admin by custom function return value
Given the following models: Profile Book Campaign The following relationships: A Profile has many Books A Book can be in many Campaigns The following Django Admin model has a custom function which fetches all the Campaigns a Book is in: @admin.register(Book) class BookAdmin(admin.ModelAdmin): @admin.display(description="Running Campaigns") def get_campaign_count(self, obj): book_campaigns_db_count = Campaign.objects.filter(asins__contains=[obj.asin]).count() return book_campaigns_db_count list_display = ["title","format","asin","get_campaign_count"] list_filter = ["profile__nickname", "format"] This is a simplified version of the model but has all the necessary parts for this question. Note: the database is PostgreSQL and the asins field is an ArrayField. Question: I would like to filter and show only Books which have >0 running campaigns. Please advise on how to achieve this. -
Django Infrastructure
I am wondering on the best way to achieve this. Basically, I have built and inventory management system for small business owners (this is more a side project). My question is, is if I were to have multiple users sign up so that they can create their own inventory management portal, how would I achieve this? Right now, I sign up and database info is visible to all auth users. But how can I make it to where users can sign up and they will get their own portal? So if multiple users sign up, they will each have their own for their business. Thanks! -
How to import Wagtail ModelAdmin index page into a template
I created a new AdminModel as follows: class OneModelAdmin(MyModelAdmin): model = SomeModel menu_label = 'One' edit_view_class = OneEditView edit_template_name = '.../one-edit.html' index_view_class = OneIndexView index_template_name = '...' class TwoModelAdmin(MyModelAdmin): model = SomeOtherModel menu_label = 'Two' edit_view_class = TwoEditView edit_template_name = '.../two-edit.html' index_view_class = TwoIndexView index_template_name = '...' How can I import the TwoModelAdmin index view inside the OneModelAdmin edit template? -
How to structure the templates folder in django and to use the extends
I have a folder, templates, structured like below /Users/AndyKw/Documents/Python/Else/Yes/templates Within templates, I have two folders, admin and registration (see below for the tree) templates (need.html) | |-- admin | |-- registration (base.html) The file I use base.htmlis in the folder registration. It needs to use a file , need.html in the folder templates with the extends command. Question is the following: How do I configure in the settings.py the templates parameter to use registration as the main folder and through base.html to reach by using extends the file need.html in the templates folder? One possible solution would be to invert the path, put need.html in the registration folder and put the base.html in the templates folder but the dev team seems to be quite unbending on this solution, this would be the less favourable way. Any ideas/tips are welcomed. -
How to order queryset while keeping objects grouped by other field?
I have a model with two fields date and type class Obj(Model): date = DateTimeField type = ChoiceField I want to order them by their creation date but I want the same type objects to stick together OBJECT: 01.01.2022 BLUE 02.01.2022 BLACK 03.01.2022 BLUE 04.01.2022 GREEN 05.01.2022 BLUE 06.01.2022 BLACK 07.01.2022 GREEN When I order I want it to look at the date first, get the latest date, then take all the objects with that object's type and put them into order keeping the date order amongst them, and then it will take the second type's next date and put them into the order after the previous one: ORDERED: 07.01.2022 GREEN 04.01.2022 GREEN 06.01.2022 BLACK 02.01.2022 BLACK 05.01.2022 BLUE 03.01.2022 BLUE 01.01.2022 BLUE So what I want is basically order_by title first, and then order the groups by date Can I do this trivially or do I have to go Case When or maybe even raw SQL It would be best if I can avoid raw SQL because this is paginated -
Is there a way to refresh the active django webpage without using return redirect(...)?
I'm trying to have the current webpage refresh itself after the function is completed, and I'm aware that the best way to accomplish this is through redirect(...), however in order for the code to do what it's supposed to it is already returning a value, and I don't think it's possible to return both at the same time (every time I've tried I got an error). So that leaves me wondering if there is another way to refresh the window. I'm fine with either doing it within the views.py file or as a javascript function, I just don't know how to have the two communicate if using javascript. Here is my HTML Code: {% load static %} <html> <head> <link rel="stylesheet" href="{% static '/styleSheet.css' %}"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edstore"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--BOOTSTRAP ASSETS--> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;700&family=Roboto:wght@100;300;400;500;700&display=swap" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <div class="main_Body"> <div class="section"> <h1>Fileconverter</h1> <br> <label for="file_field" class="custom-file-upload"> <i class="fa fa-cloud-upload"></i>Updload File(s)</label> <input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple> <label id="file_name"></label> <br> <br><br><br> <br> <button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"--> </div> </form> </body> <footer> <p>Click "Choose File(s)" and select the files you want to convert.</p> <p>Once you click "Submit" the … -
Django with Huey - delay a task
For a scenario with sales orders, I'm needing to execute a task with a given delay. To accomplish this, I added a task in my tasks.py file like so: from huey import crontab from huey.contrib.djhuey import db_task @db_task(delay=3600) def do_something_delayed(instance): print("Do something delayed...by 3600 seconds") However, this delay setting doesnt seem to delay anything. The task is just scheduled and executed immediately. What am I doing wrong? -
Passing form data between 2 seperate views without carrying it via URL arguements
basically i have two separate views, but i need form data from the first view to pass to the second view without having to pass it via URL parameters. is this possible? NOJS -
How to mention id from html in django
I'm working on a single page website where the pages are made with id in the main html page. Now the problem is I want to connect the "contact" id's form with database. but I don't know how to mention the id in code. I mean i know what to do if the pages are separated htmls but don't know how to use id from one html site. There's another html page for blogs only. I'm mainly confused on how to use post method in this case. views.py from django.shortcuts import render, HttpResponse from django.http import HttpResponse # Create your views here. def home(request): if request.method=="POST": print("This is post") return render(request, 'index.html') def blog(request,id ='contact'): if request.method=="POST": print("This is post") return render(request, 'blog-single.html') urls.py of main project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('portfolio.urls')) ] urls.py from app: from django.contrib import admin from django.urls import path, include from portfolio import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] template file: <form action="#contact" method="post" role="form" class="contactForm"> {% csrf_token %} <div id="sendmessage">Your message has been sent. Thank you!</div> <div id="errormessage"></div> <div class="row"> <div class="col-md-12 mb-3"> <div class="form-group"> <input type="text" name="name" class="form-control" … -
Azure Linux based web app Restart automatically
I am Running Django Application on an Azure Linux Web App, I have noticed that after a certain point the application restarts. when drilling down the issue, I found that the Container disk or memory is not sufficient. My Image size is around 5-6 gb which is under 15 gb limit. Is there any better way of Deploying Django application ? -
Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running?
I want to push my Django project to GitLab and build a build with the pipeline. But I get this error message every time: Cannot connect to the Docker daemon at tcp://docker:2375. Is the docker daemon running? gitlab-ci.yml -
Rebuilding the database when 'Reverse for 'wagtailadmin_explore' with arguments '('',)' not found error' occurs
I flushed the wagtail database using python manage.py flush and now have this error. I found that in this question somebody else had the same issue and managed to solve it by using docker. Reverse for 'wagtailadmin_explore' with arguments '('',)' not found However, I just want to restore the wagtail site I was working on to a working state in the development server. I already tried flushing again and rebuilding the db but I can't seem to figure it out. Is there a way to fix this error by not using docker? -
How can I create a movie rating site in Django using the TMDB API?
I would like to create a movie review site using TMDB's API and have a question. 1.I am getting an error saying "Movie matching query does not exist. I am thinking that I have defined a Movie model and movie = Movie.objects.get(id=movie_id) is wrong. 2. I would like to list the comments and movies commented by the User in views.py. How do I add this? 3.User can only comment on one movie, but I want to add edit and delete, how can I do that? def view_tv_detail(request, tv_id): if request.method == "POST": user = request.user comment = request.POST.get("comment") stars = request.POST.get("stars") if not request.user.is_authenticated: user = User.objects.get(id=1) Comment(comment=comment, star = stars, user=user,movie_id = tv_id).save() return redirect(f"/tv/{tv_id}/") else: data = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get(f"https://api.themoviedb.org/3/tv/{tv_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comment_list = Comment.objects.filter(movie_id=tv_id) comments = reversed(Comment.objects.filter(movie_id=tv_id)) n_comments = comments.count() if n_comments == 0: average = 0 else: average = sum([comment.stars for comment in comments]) / n_comments return render(request, "Movie/tv_detail.html", { "data": data.json(), "recommendations": recommendations.json(), "type": "tv", "comments": comments, "average" : average, }) class Movie(models.Model): def get_comments(self): return Comment.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: return sum([comment.stars for comment in comments]) / n_comments else: return 'No comments posted yet' class Comment(models.Model): class Meta: unique_together … -
sync labels for multiple data-sets in chart.js
I am making a website that keeps track of your expenditure, so I want to display a graph showing the expense made by each subfield, be it weekly, monthly, yearly, or even daily. Question how do I sync the labels with multiple databases, so what's happening is when I go to show my data weekly. the sports field's data is not getting in sync with the labels. in the first column (labeled week 23) the data which is being shown with week 23 of body is actually the data of week 27 of sports so what I want to do is, sync the labels and make sure that the data of week 27 is being shown in week 27 only, no matter where the data-set starts. code views.py @login_required def maingraph(request, pk): lb_wa = Body.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").order_by( "week").distinct() wa = Body.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").annotate( total=Sum(F('price') * F('quantity'), output_field=FloatField())).order_by("week") s_lb_wa = Sport.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").order_by( "week").distinct() s_wa = Sport.objects.filter(user=request.user).annotate(week=ExtractWeek("pub_date")).values("week").annotate( total=Sum(F('price') * F('quantity'), output_field=FloatField())).order_by("week") return render(request, 'main_app/m_graph.html', {"wa": wa, "lb_wa": lb_wa , "s_wa": s_wa, "s_lb_wa": s_lb_wa}, ) HTML {% extends "main_app/main_base.html" %} {% block scripts%} <script> $(document).ready(function(){ const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for item in lb_wa %}'{{item.week }}',{% endfor … -
Is there a tutorial or easy method to view django database db.sqlite3? [duplicate]
Essentially, I would like to see the tables and their contents of the database for my Django project so that I can keep track of my data and seeing if everything is working correctly? Do I need to use a third party software such as MySQL, MariaDB, etc.? -
Django Many-To-Many through form with specific queryset
I have the following models Program and Exam with foregin keys to University. class Program(models.Model): university = models.ForeignKey(University, on_delete=models.CASCADE) ... exams = models.ManyToManyField(Exam, through='ProgramExam') class Exam(models.Model): university = models.ForeignKey(University, on_delete=models.CASCADE) ... And they have a many-to-many relation through the model ProgramExam which adds extra fields. class ProgramExam(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE) exam = models.ForeignKey(Exam, on_delete=models.DO_NOTHING) coef = models.FloatField( validators=[MinValueValidator(0.0), MaxValueValidator(3.0)] ) class Meta: unique_together = [['program', 'exam']] How do I set the queryset in forms.ModelChoiceField so to only display instances of Exam that have the same fk as the instance of Program class ProgramExamForm(forms.ModelForm): exam = forms.ModelChoiceField(queryset=Exam.objects.none()) I tried passing a queryset in my view but it interferes with request.POST def create_program(request): user = request.user exams = user.university.exam_set.all() program_exam_form = ProgramExamForm() program_form.fields['exam'].queryset = exams if user: if hasattr(user, 'university'): if request.method == 'POST': program_exam_form = ProgramExamForm(request.POST) if program_exam_form.is_valid(): program_exam = program_exam_form.save() ... context = {'program_exam_form': program_exam_form} return render(request, 'create_program.html', context) -
Remove Server Header from TemplateResponse Django 3.1?? (header not showing)
So I have to remove or hide the server header from a django app I am working on for security (I was asked to remove it). I tried removing it from a middleware but the header is not showing! Nonetheless it is shown when the page loads. I tried this, but it raises a ValueError "too many values to unpack" class NoServerHeaderMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response._headers['Server'] = "Empty" return response When I explore the response this is all there is: {'content-type': ('Content-Type', 'text/html; charset=utf-8'), 'content-length': ('Content-Length', '26292'), 'x-frame-options': ('X-Frame-Options', 'SAMEORIGIN'), 'vary': ('Vary', 'Cookie'), 'x-content-type-options': ('X-Content-Type-Options', 'nosniff'), 'referrer-policy': ('Referrer-Policy', 'same-origin')} So, not being Server header in there I can not really modify it can I? What am I missing? Where could the header be being added? -
JWT auth using python-social-auth and django-rest-framework
I'm trying to convert a snippet of code that I found (using python-social-auth) to make it handle JWT authentication instead of simple token authentification. Here is the code: @api_view(http_method_names=['POST']) @permission_classes([AllowAny]) @psa() def oauth_exchange_token_view(request, backend): serializer = SocialAccessTokenSerializer(data=request.data) if serializer.is_valid(raise_exception=True): # set up non-field errors key try: nfe = "non_field_errors" except AttributeError: nfe = 'non_field_errors' try: # this line, plus the psa decorator above, are all that's necessary to # get and populate a user object for any properly enabled/configured backend # which python-social-auth can handle. user = request.backend.do_auth(serializer.validated_data['access_token']) except HTTPError as e: # An HTTPError bubbled up from the request to the social auth provider. # This happens, at least in Google's case, every time you send a malformed # or incorrect access key. return Response( {'errors': { 'token': 'Invalid token', 'detail': str(e), }}, status=status.HTTP_400_BAD_REQUEST, ) if user: if user.is_active: token, _ = Token.objects.get_or_create(user=user) return Response({'access': token.key}) else: return Response( {'errors': {nfe: 'This user account is inactive'}}, status=status.HTTP_400_BAD_REQUEST, ) else: return Response( {'errors': {nfe: "Authentication Failed"}}, status=status.HTTP_400_BAD_REQUEST, As you can see in the code above, the token is returned like this: token, _ = Token.objects.get_or_create(user=user) return Response({'access': token.key}) But I would like it to return a JWT using djangorestframework-simplejwt instead. -
Django Filter with custom field_name and Custom value as an argument in queryset
I am using the filter in Django queryset, as it requires an argument and a value assigned to it. eg. ModelName.objects.filter(name="Amit").values() in such a case I am sending both the values from the API request so that both can be custom as per the need [like in the custom field we can search any custom value], but unable to use in this Filter function. Please let me know where I am doing wrong, can it be possible like this too. Thanks -
I can't create in related tables in django using serializers
Please, help! I need create a stock database postgresQL. I use the command in Visual Studio Code. But I have error on string "StockProduct.objects.create" in serializers.py. The stock is created in base, but without products in this stock. command in Visual Studio Code: ### # create a stock POST {{baseUrl}}/stocks/ Content-Type: application/json { "address": " stock_ address ru3", "positions": [{"product": 2, "quantity": 250, "price": 120.50}, {"product": 3, "quantity": 100, "price": 180}] } serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('title', 'description') class ProductPositionSerializer(serializers.ModelSerializer): class Meta: model = StockProduct fields = ('quantity', 'price') class StockSerializer(serializers.ModelSerializer): positions = ProductPositionSerializer(many=True) #id = serializers.IntegerField() # configure the serializer for the warehouse class Meta: model = Stock fields = ('address', 'positions') def create(self, validated_data): positions = validated_data.pop('positions') # create stock stock = super().create(validated_data) for position in positions: StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity'])# 1.Variant #StockProduct.objects.create(stock=stock, **position) # 2. variant "logistic_stockproduct" relation violates NOT NULL restriction # defaults = {'price'=position['price'], 'quantity'=position['quantity']}) #product=position['product'], price=position['price'], quantity=position['quantity']) # StockProduct.objects.create(position) #position=position # StockProduct.objects.create(stock('id'), position) #StockProduct.objects.create(positions) # quantity = position.pop('quantity') # price= position.pop('price') # StockProduct.objects.create(quantity=quantity, price=price) return stock variant Error # 1 variant Error . line 36, in create StockProduct.objects.create(stock=stock, product_id=position['product'], price=position['price'], quantity=position['quantity']) KeyError: 'product' # 2. variant: DETAIL: The … -
Using JavaScript onclick function to change innerHTML to form field
I am trying to use the JavaScript onclick() function to change a piece of HTML to a Django Model Form field when clicked? Using the code below, I would expect that when the {{ tasks.owner }} is clicked, the html with id "task_owner" would change to {{ task_update_form.owner }}. My Django template is below: <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "{{ task_update_form.owner }}"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> If I use the below code - substituting {{ task_update_form.owner }} with "Test" it works perfectly. <script> function OwnerUpdate() { document.getElementById("task_owner").innerHTML = "Test"; } </script> <p id = "task_owner", onclick = "OwnerUpdate()"> {{ tasks.owner }} </p> I have also tested it using non-form context from my views.py and it works. {{ task_update_form.owner }} works fine when inserted into the Django template normally. My experience with JavaScript is limited and I would be grateful for any help.