Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
where to patch a django model method in a view when the method module isn't explicitly imported
I have a test that needs to patch a method's return value on my Profile model: some_app.tests.py with patch('cant.figure.this.part.out.get_current_teacher_list', return_value=[some_user]): response = self.client.get('some/view/that/uses/get_current_teacher_list') The view that uses the method, however, uses it in a convoluted way that I can't figure out how to patch: some_app.views.py teachers_list = submission.user.profile.current_teachers() Where submission is an instance of a model with a User foreign key (and the Profile model has a one to one with User) And here's where the method is defined: profiles.models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # ... def current_teachers(self): # stuff How do I patch the return value of this method? -
Django don't recognize JWT after performing system check
I am using Django with JWT. Sometime when the Django backend performs a system check it doesn't recognize the token of a user that logged in before the system check. Does anyone had this problem and know how to fix it? (I didn't put any code here because the problem is in every view that requires auth) -
pipenv: Pipfile.lock file shows different version than whats installed
I have django installed using pipenv install django I check the version of Django installed using python -m django --version 3.0.3 So its 3.0.3 I have done pipenv lock later sometime after installing few more packages I check the Pipfile.lock to see what django version it locks to 3.0.6 { "_meta": { "hash": { "sha256": "1c89f4b79e61ac01a5f1b50db6b6b0b4ba34199a99f96caf61885884b43a8b3a" }, "pipfile-spec": 6, "requires": { "python_version": "3.7" }, "sources": [ { "name": "pypi", "url": "https://pypi.org/simple", "verify_ssl": true } ] }, "default": { .... "django": { "hashes": [ "sha256:051ba55d42daa3eeda3944a8e4df2bc96d4c62f94316dea217248a22563c3621", "sha256:9aaa6a09678e1b8f0d98a948c56482eac3e3dd2ddbfb8de70a868135ef3b5e01" ], "index": "pypi", "version": "==3.0.6" }, .... } "develop": { .... "django": { "hashes": [ "sha256:051ba55d42daa3eeda3944a8e4df2bc96d4c62f94316dea217248a22563c3621", "sha256:9aaa6a09678e1b8f0d98a948c56482eac3e3dd2ddbfb8de70a868135ef3b5e01" ], "index": "pypi", "version": "==3.0.6" }, .... } And this is my Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] django-extensions = "*" ipython = "*" werkzeug = "*" pydotplus = "*" django-querycount = "*" jupyter = "*" flower = "*" django-request-logging = "*" [packages] django = "*" psycopg2 = "*" django-environ = "*" celery = "*" redis = "==3.3.11" pyjwt = "*" django-webpack-loader = "*" django-rest-framework = "*" kombu = "*" django-otp = "*" pyotp = "*" gunicorn = "*" [requires] python_version = "3.7" Also i checked the version from pipenv graph it … -
How do I render Django queryset to javascript in template?
So I'm working on a scheduler-like app with Django. I have fullcalendar-django library in my template, and making some changes with JavaScript. But then I ran into an issue. Here's my views.py from .models import NewEvent def ScheduleMain(request): allDays = NewEvent.objects.all() return render(request, 'main.html', {'allDays':allDays} Let's say there are two fields in my model NewEvent - date(DateField) and event(CharField). Here's the tag in my template. {% block extrahead %} <script> $(document).ready(function() { for (each in allDays) { $(function() { if ($('.fc-day').attr('data-date') == "{{each.date}}") { $('.fc-day .fc-day-content').html("{{each.event}}") } }); } }); </script> {% endblock %} {% block content %} ... {% calendar %} ... {% endblock %} So in the {% calendar %}, each date is written in this way : ... <td class="fc-day" data-date="2020-05-17"> <div class="fc-day-content">today schedule comes here</div> </td> <td class="fc-day" data-date="2020-05-18"> <div class="fc-day-content">today schedule comes here</div> </td> ... As you can see, I'm trying to fill in the "today schedule comes here" with whatever the event the user inputs. And of course, since the template is pre-designed, I cannot directly make changes to it. So I'm trying to work on it with JavaScript. And let's for now say there can only be one event per day. What have … -
How can I get the count of nested model relationship?
Here are my model relationships: |---Retailer |---Product |---Coupon Now I have a view that returns me each retailer with its products: class ProductList(APIView): def get(self, request): retailer = Retailer.objects.all() serializer = RetailerSerializer(retailer, many=True) data = serializer.data return JsonResponse({'data': data}, safe=False) And here's RetailerSerializer: class RetailerSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True, read_only=True) class Meta: model = Retailer fields = ['name', 'website','description', 'products'] depth = 1 Now I want to get count coupons in each product. What should i do? -
How to create a field in django model but not create its column in database?
I am trying to make a temporary field for a model in django that has nothing to do in database. How can I make it. -
Django REST; JSON parse error - Expecting property name enclosed in double quotes
Upon trying to test a CreateAPIView, I'm getting the following error for which I'm not sure how to resolve. I have explicitly defined my parsers and renderers as well in my settings. {'detail': 'JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)'} tests.py class TestAPIRegisterView(TestCase): @classmethod def setUpTestData(cls): cls.register_form_data_2 = { "username": "User1", "password": "password", "verify_password": "passcode" } def test_register_user_password_match_fail(self): '''Verify that a 400 HTTP response is returned to the client informing it that the passwords entered in the register form don\'t match.''' http_response = self.client.post( reverse("register-user"), data=self.register_form_data_2, content_type="application/json" ) print(http_response.json()) self.assertEqual(http_response.status_code, 400) views.py class UserRegisterView(CreateAPIView): permission_classes = (permissions.AllowAny,) model = get_user_model() serializer_class = serializers.UserSerializer serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) verify_password = serializers.CharField(write_only=True) def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user def validate(self, data): password = data["password"] verify_password = data["verify_password"] if password != verify_password: raise serializers.ValidationError( "Cannot verify your password. Try again." ) return data class Meta: model = get_user_model() fields = ["username", "password", "verify_password"] settings.py REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } -
Update parent model after Inline is saved
I have the following code: class Invoice(models.Model): total = DoubleField() status = CharField() # It's actually an Enum but using Char for simplicity @property def received_amount(self): payments_paid = ... # Sum of payments paid against this invoice return payments_paid.amount class Payment(models.Model): invoice = ForeignKey(Invoice) amount = DoubleField() # # Admin # class PaymentInline(admin.TabularInline): pass class InvoiceAdmin(admin.ModelAdmin): def save_model(...): if obj.received_amount >= obj.total: # Invoice has all its amount paid obj.status = 'PAID' else: obj.status = 'PENDING' obj.save() What I am doing here is that when payments are made against the invoice (using the inline) and the changeform is saved, I check if the full amount is received (inside save_model()) and I update the Invoice's status accordingly. But the problem is save_model() is called before the inline is saved, and the status doesn't update correctly. In other words, the payment information inside save_model is always stale. How do I fix this? -
No Post matches the given query. Redierecting to wrong page
this is my views.py file class PostDetailView(DetailView): model = Post form_class = CommentForm def post(self, request, *args, **kwargs): self.object = self.object() comment_form = self.form_class(request.POST or None) if comment_form.is_valid(): cont = request.POST.get('cont') comment = Comment.objects.create(post=post,user=request.user,cont=cont) comment.save() return HttpResponseRedirect(post.get_absolute_url()) def get_context_data(self,**kwargs): post = self.get_object() request = self.request comments = Comment.objects.filter(post=post) self.comment_form = self.form_class(request.POST or None) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context = super().get_context_data(**kwargs) context.update({'total_likes': post.total_likes(), 'is_liked': is_liked,'comments':comments,'comment_form':self.comment_form}) return context this is post_detail.html ` ` ` <form method="post"> {%csrf_token%} {{comment_form|crispy}} <input type="submit" class="btn btn-outline-success" value="submit"> </form> <div class="main-comment-section"> {{comments.count}} Comment {{comments|pluralize}} {%for comment in comments%} <blockquote class="blockquote"> <p class="mb-0">{{comment.cont}}</p> <footer class="blockquote-footer">by- <cite title="Source Title">{{comment.user | capfirst}}</cite></footer> </blockquote> {%endfor%} </div> ` this is my url.py urlpatterns = [ ---- path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('like/',views.like_post,name="like_post"), --- ] this is my models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) cont = models.TextField() time = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title,str(self.user.username)) ..... when i click on dubmit button for posting comment i get redierected to http://localhost/like page instead of post-detail page. … -
Django extend admin home page - Add elements to the content area
I'm trying to add a link inside the content area of the admin home page. I'm using this template: {% extends 'admin/base.html' %} {% block title %} Custom title {% endblock %} {% block content %} <a href="some/url">LINK</a> {% endblock %} The title is working so I know the extended template is working but the block content is not working, I can't see the link in my admin home page. Acoording to django's github repository (https://github.com/django/django/blob/master/django/contrib/admin/templates/admin/base.html) the block name is correct so I don't know where my error is. How can I add elements to the content area of my admin home page? -
MultiValueDict Error in django get request
Hello guys i am trying to make self generate data in my log div class without refreshing the page, i read online you can do this by using ajax so i tried it but i got this multivaluedic error when i try to get request the ajax variable. Can anyone please explain what did i do wrong? thanks here's my code. View.py def dashboard(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() increment = int(request.GET.get['append_increment']) increment_to = increment + 10 resource_log = api.get_resource("log") content_log = resource_log.get()[increment:increment_to] return render(request,"dashboard.html",{"content_log":content_log}) Dashboard.html (this is the log div class with id="log_file" i want to self generate without refreshing the page <div class="panel-heading"> Log <span class="pull-right clickable panel-toggle panel-button-tab-left"><em class="fa fa-toggle-up"></em></span></div> <div class="panel-body"> <ul> {% for contents_log in content_log %} <li id="log_file"class="left clearfix"><span class="chat-img pull-left"> </span> <div class="chat-body clearfix"> <div class="header"><strong class="primary-font">{{contents_log.topics}}</strong> <small class="text-muted">{{contents_log.time}}</small></div> <p>{{contents_log.message}}</p> </div> </li> {% endfor %} </ul> </div> Ajax Script <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'dashboard' %}, data: {'append_increment': append_increment} }) .done(function(response) { $('#log_file').append(response); append_increment += 10; }); }, 10000) </script> -
TypeError: handle() takes 1 positional argument but 2 were given
update_index.Command().handle( app_label, using=None, remove=indexJob.remove ) import threading try : import queue except ImportError: import Queue as queue from haystack.management.commands import update_index from django.conf import settings import time from django.db import connection from django.core import management TypeError: handle() takes 1 positional argument but 2 were given. I am getting that error, the function used to work in django 1.8 and python 2, but now that i moved to python 3.6.9 and django 2.2..and updated the haystack library to 2.8.1 i am getting that error, i saw same error reported on stackoverflow other places ..but did not help me for this specific function. -
Modifications PythonAnywhere -> GitHub
I've made some changes directly on the code located in the PythonAnywhere files. In this way, some of them are a little bit different from the reppository GitHub files. Assuming the PyhonAnywhere files are correct, what is the best way to 'copy' them and move to the GitHub? Thank you! -
DataTables: Store table data in browser
I am adding data to table using row.add API, which is working fine, but the data disappears when page is refreshed. Is there a way to store this data in cache or something until a POST method is called ? Thanks -
Django get an instance of a object and pass it through to a form
I am new to Django and programming in general. I am trying to generate a list of records from a database but with two fields that can be edited. In the browser it should show a line with the fields: Name, description, Reason, comment Name and description come from the model and are a reference. The user should only be able to capture reason and comments I have created a forms.py file and a ModelForm. My issue is how do I pass through an individual object. For this example I've limited my dataset to 10 records In my view file def home(request): if request.method == 'GET': nca = NcaRe.objects.all()[:10] form = NcaReForm(instance= <what should go in here> ) return render(request, 'NCAComments/home.html', {'form': form, 'nca': nca}) else: pass In my model I have a field called primarykey. I'm not sure how to pass this to the form so that I only bring in that record. I have tried looking at the documentation but have not been able to follow it. -
set dynamically Attributes(model) at Class Based View Django
i have a problem in creating class based views thanks in advance is my first project I need to imitate what I have been doing for function based views.Which is using the "request.POST.get" method to pass values from one view to another,which has saved me a lot of code. For example: registros.html <form action="{% url 'blog-tabla' %}" method="post" class="collapse-item"> {% csrf_token %} <input type="hidden" name="modelo" value="{{row}}"> <input type="submit" value="Tabla {{row}}" class="btn"> </form> i pass the value in the tag {{row}} the name 'modelo' and the link for the next url {% url 'blog-tabla' %} so in the next view i use modelo=request.POST.get("modelo", "") and recover all the values that i need views.py from django.shortcuts import render , get_object_or_404 from tablib import Dataset from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin from django.views.generic import ListView, DetailView,CreateView,UpdateView,DeleteView # la vista de lista from masters.resources import * from masters.models import * from django.core import serializers from masters.auto import * def tabla (request): modelo=request.POST.get("modelo", "") modelo_upper=modelo.upper() modelo_cls=globals()[modelo_upper] field_names = [f.name for f in modelo_cls._meta.get_fields()] data = [[getattr(ins, name) for name in field_names] for ins in modelo_cls.objects.prefetch_related().all()] context={ 'content':modelo_cls.objects.all(), 'data': data, 'field_names': field_names, 'modelo_upper':modelo_upper } return render(request,'masters/tabla.html',context) the problem is when … -
Django available object count after checking the previous booking
Im making a renting app for bikes. when a user selects a DateRange (not DateTime), I should be able to check the range against the previous booking and show the available bikes with the stock count. For Example: bike_category1 = 30 stock bike_category2 = 20 stock. if there is a booking1 for 5 + 5 bikes from 1 to 15, and the next booking if the start or end or the whole date range falls in the booking1, then the user should have 25 + 15 bikes available. Basically if the stock for the chosen dates are = 0 then he shouldn't be able to book it. I have a booking model and a vehicle category model FK to Vehicle model. I have a method in category which gets the count of bikes per category. THIS IS WHAT I THINK I SHOULD DO : I don't know how to get started. start_date = 1 end_date =15 I query the booking model to see if the dates exists in any booking, if it does then get the list of booking and use annotate to get the quantity of bikes each category and then minus that quantity from the category model count … -
Django get_object_or_404 in details view not returning all the fields from the Page model
I want all the fields in my view.py details' function. The details function looks like **Page views.py** def page_detail(request, slug): details = get_object_or_404(Page, slug=slug) return render(request,'page/details.html', {'details': details}) **Page models.py** class Page(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200,blank=True) dscription = models.TextField(blank=True) image = models.ImageField(upload_to='images/%Y/%m/') ... ... def __str__(self): return self.title def get_absolute_url(self): return reverse("page:page_detail", kwargs= {"slug": self.slug }) Want to get all the field details in the views.py details function, but it depends on the models str function. If I increase the number of the field in this str function I can get the value of all those fields, else not. How to display all the fields. why get_object_or_404 depends on str Please describe, thanks in advance. -
I need a field's default create value to to be the current logged in user
I'm pretty new to Django. I'm working on a ticket system so I'd like users to be able to track the tickets they create. I tried to add CurrentUserDefault to the serializer but I got a very unhelpful 400 error. Model: class RepairTicket(models.Model): desc = models.TextField() createdBy = models.ForeignKey(User, related_name='repair_user', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) resolved = models.BooleanField(default=False) equipment = models.ForeignKey(Equipment, related_name='equipment', on_delete=models.CASCADE) operable = models.BooleanField(default=False) affectsProduction = models.BooleanField(default=False) def __str__(self): return "{} - {}".format(self.desc, self.equipment) class Meta: ordering = ["-created"] Serializer: class RepairTicketSerializer(serializers.ModelSerializer): def to_representation(self, instance): representation = super(RepairTicketSerializer, self).to_representation(instance) representation['created'] = instance.created.strftime("%m-%d-%Y") return representation class Meta: model = RepairTicket #fields = () fields = '__all__' depth = 1 -
One to Many to One Model logic
I need help with my model logic. I am trying to recreate an application tracking app that takes in a Candidate instance. Here's my basic model structure: from django.db import models class Candidate(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Job(models.Model): job_title = models.CharField(max_length=128) candidates = models.ManyToManyField(Candidate, through='Application') def __str__(self): return self.job_title class Application(models.Model): candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) application_date = models.DateField() def__str__(self): return str(self.job) + ' ' + str(self.candidate) Here are the logic parameters: A Candidate can only have one instance, but can have multiple Applications An Application for each Candidate can only exist in one Job Something that would probably result to this API view: # candidate detail "candidate": { # candidate info from model "id": 1, ... "applications": { # application 1 # application 2 } } # application detail "application": { # application info from model "id": 1, ... "candidate_id": 1 "job_id": 1 } # job detail "job": { # job info from model "id": 1, ... } One thing that was throwing me off was how I would be able to show the list of Applications in each Candidate instance and how it relates to the Application model. I don't know … -
ImportError: cannot import name model
Hello everyone. This is the first time I ask for help on StackOverflow, so please forgive me if my question here is clear enough... I will gladly provide anything you ask me for in order to have a better understanding of this issue I have Django project that is not importing a model from an app that is registered on my settings. This app has been working good until 2 day ago, but I haven't made any changes related to models. I have tried many things to fix this issue but still giving me the same error... I can't import anything coming from the models on any of my apps... This is very frustrating. Please some advise -
DRF- Django Rest Framework correct re_path query params - "Method \"GET\" not allowed."
I've been trying to GET on generics RetrieveAPIView class using the re_path method in urls.py file. After trying several combinations, I can only get the path method to work. I would like to get an endpoint something similar to /file?id={some_uid}. So far I have the following: django: 3.0.6 djangorestframework=3.11.0 views.py file: class UploadFileInfoView(generics.RetrieveAPIView): lookup_field = "id" queryset = Upload.objects.all() serializer_class = UploadModelSerializer urls.py file: from django.urls import path, re_path from . import views urlpatterns = [ path("file/", views.UploadFileView.as_view(), name="UploadFile"), # this works # path("file/<uuid:id>", views.UploadFileInfoView.as_view(), name="UploadFileInfo"), # this does not re_path(r"^file/(?P<id>[0-9A-Fa-f-]+)", views.UploadFileInfoView.as_view(), name="UploadFileInfo"), ] Have not used url method as the documentation says This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release. -
Problems when obtaining an id, sent by a form
Good evening, I am trying to get the id of my model Note that is sent by means of a form, but when I put form.id it tells me that id is not defined, try to get it through the user session but it says that it was not found. def add_book(request): template_name = 'books/create_note.html' book = get_or_create_book(request) form = NoteForm(request.POST) if request.method == 'POST' and form.is_valid(): note = Note.objects.get(pk=form.pk) book.notes.add(note) form.save() return redirect('books:book') return render(request, template_name, { 'form': form, }) and this is the form class NoteForm(ModelForm): class Meta: model = Note fields = ( 'title', 'nota' ) labels = { 'title': 'Titulo', 'nota': 'Nota', } try creating an instance of my Note model but when it comes time to create it tells me it is empty. -
Testing Image Upload Not Uploading Image
Im trying to unit test that my function which allows users to upload a new profile image. This works on my site but I cant get it to work in my test. tests.py def test_upload_image_works(self): user = User.objects.create(username='testuser', email='user@example.com') self.client.force_login(user) with open(settings.MEDIA_ROOT+'\profile_pics\\testImg.jpg', 'rb') as infile: request = self.client.post( '/profile/update_profile/', {'image': infile} ) user.refresh_from_db() self.assertEqual(user.profile.image, 'testImg.jpg') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username}' # scale down profile pics when theyre saved def save(self, *args, **kawrgs): super().save(*args, **kawrgs) [..cont..] forms.py class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] error msg (user profile img isnt updated) AssertionError: <ImageFieldFile: profile_pics/default.jpg> != 'testImg.jpg' Thank you. -
I set the email requirement to true and unique to true but still one can make account with duplicate email in my django website
Suppose I create an account with username="Ali" and with email="ali5242@gmail.com" and then I create account with different username but with the same email then upon sending post request to sign up the user, django with through error of: Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_profile.email error image:https://imgur.com/1CQeXSV but even then it saves that user in the database with all the info that is provided What should I do? I am new to django. I would love to get the solution and your advice on which topics should i research more. I extended User model and now my models.py files look like this, from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) address = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) email = models.EmailField(unique=True, null=True) email_confirmed = models.BooleanField(default=False) def __str__(self): return str(self.user) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() My forms.py file look like this, from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): email = forms.EmailField(widget= forms.EmailInput(attrs={'placeholder':'Email', 'required':'True', 'class': 'form-control'})) username = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Username', 'class': 'form-control'})) password1 = …