Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django factory boy mock model method in factory
My model's save method is calling an api after saving. To test my application I am using DjangoModelFactory to generate objects for testing. However, the api still being called. class MyClass(models.Model): def save(self, *args, **kwargs): super().save(*args, **kwargs) self.call_api() I have tried mocking the method but it is not working #... from .models import MyModel @pytest.mark.django_db @patch("MyModel.call_api") class MyModelFactory(factory.django.DjangoModelFactory, factory.base.BaseFactory): class Meta: model = MyModelFactory My Question is, how can I use mock methods when I use it with factories? -
How do I add context/an additional dictionary to Django DayArchiveView
I have a DayArchiveView where I pass in a queryset of booking slots. I would like to be able to pass in some context too, like more data. Specifically, I would like to pass the earliest time, latest time and a few other small calculations. My view is currently this. class BookingArchiveView(DayArchiveView): queryset = BookingSlot.objects.filter(location__club__id=1) date_field = "start_time" ordering = ['location'] #I would like to pass in another object like so context["earliest_time"]=BookingSlot.objects.filter(location__club__id=1).annotate(Min('start_time')) So I would like to be able to pass in some aggregate functions and calculations that I could render in html. Right now, the HTML only has access to my queryset. -
How to create this type of relationship using Django Models
After seeing a model that I should implement in Django, I was a little confused and I will explain what I tried to do and what was sent to me. The following image is the relationship I must implement in Django https://i.stack.imgur.com/FOYNq.png What I tried to do was: class Contact(models.Model): person = models.OneToOneField(Person) class Person(models.Model): contact = models.ForeignKey(Contact) However this does not work, both classes are in the same file. I read the documentation for ManyToManyField, OneToOneField and ForeignKey, but what makes me confused is the model wanting the variable in both classes, in previous models that I saw there was this same relationship, but the variable only existed in one of the classes. What is the correct way to implement this? -
Python - Generate N colors names
I want to generate N colors (from the darkest to the brightest). The colors should NOT BE RGB, But they should be represent as names ("black","navy","lightgreen") e.g - colors that can be drawn at HTML pages. I try to find a solution but I find only RGB generators. Thank you very much, Amit. -
How to get History (Product List) from orders that user has purchased in django
I have a model Order which has a ManyToManyField order_entries class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_entries = models.ManyToManyField(OrderEntries, blank=True) ... I have another model OrderEntries class OrderEntries(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() Now, I have to get history of purchased products. What is the efficient way to get all those products? Any help will be highly appreciated -
type object 'ViewSet' has no attribute 'action'
I generate this little question in case some developer finds this problem in the current versions of djangorestframework that generates a conflict with the 'action' attribute in my case when overriding the 'get_authenticators' method after doing an analysis I found that it can be solve this way before def get_authenticators(self): print(self.action) Show error "has no attribute" replace self.action with self.action_map['get'] my current version is djangorestframework==3.12.0 -
django model class returns different values on different queries
i have a model called profile with a field for balance which is an integer field, and another model class called task with a foreign key to profile, when I run profile.balance (with the correct pk) it returns a value of 0, but when i run task.profile.balance i get 400, but when i run profile == task.profile it returns True, the foreign key is definitely the right model instance but the field values don't add up any help would be greatly appreciated -
How to have a child key form view in foreign key detail view
I am having a lot of trouble finding this answer as I don't know how to ask it properly. I have found a solution to do something similar to what I want. https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/#an-alternative-better-solution But it seams to fail to work. It loads page correctly, and redirects correctly. But it does not populate the database with child entry for the main foreign key. Any help would be appreciated. class QuizDisplayView(DetailView): model = Quiz context_object_name = 'quiz' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = Q_And_A_Form() return context class QuizQuestionView(SingleObjectMixin, FormView): template_name = 'Quizer/quiz_detail.html' form_class = Q_And_A_Form model = Quiz def post(self, request, *args, **kwargs): #if not request.user.is_authenticated: #return HttpResponseForbidden() self.object = self.get_object() return super(QuizQuestionView, self).post(request, *args, **kwargs) def get_success_url(self): return reverse('quizer:quizDetail', kwargs={'pk': self.object.pk}) class QuizDetailView(View): def get(self, request, *args, **kwargs): view = QuizDisplayView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = QuizQuestionView.as_view() return view(request, *args, **kwargs) -
How to server favicon.ico with Django and Whitenoise
I use whitenoise for static files and it works fine. But how can I serve the /favicon.ico file? There is a setting called WHITENOISE_ROOT, but I don't understand how to use it. I would like to keep my nginx config simple and serve all files via gunicorn -
The view polls.views.vote didn't return an HttpResponse object. It returned None instead
Studied the tutorial up to the seventh part. Everything was fine until I decided to launch my application. After launch, I added a multiple choice question. The error occurs after I select one of the answers to the question. A long search for an answer led nowhere. Please help. I get this error: ValueError at /polls/1/vote/ The view polls.views.vote didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/polls/1/vote/ Django Version: 4.0.dev20210118085850 Exception Type: ValueError Exception Value: The view polls.views.vote didn't return an HttpResponse object. It returned None instead. Exception Location: c:\users\mrand\django\django\core\handlers\base.py, line 309, in check_response Python Executable: C:\Users\mrand\Anaconda3\envs\mysite\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\mrand\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\python38.zip', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\DLLs', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages', 'c:\\users\\mrand\\django', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\win32\\lib', 'C:\\Users\\mrand\\Anaconda3\\envs\\mysite\\lib\\site-packages\\Pythonwin'] Server time: Wed, 27 Jan 2021 22:41:24 +0300 Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/1/vote/ Django Version: 4.0.dev20210118085850 Python Version: 3.8.6 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "c:\users\mrand\django\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "c:\users\mrand\django\django\core\handlers\base.py", line 188, in _get_response self.check_response(response, callback) File "c:\users\mrand\django\django\core\handlers\base.py", line 309, in check_response raise ValueError( Exception Type: ValueError at /polls/1/vote/ Exception Value: The view polls.views.vote didn't … -
how to call property method from model class to html in django
Im making a django app, and its basically an admin site, i have an app called calculator, inisde it i have 3 models Transaction, FamilyGroup and FamilyMember, each model has some property methods for calculation purposes. here are the models for more clearness : class Transaction(models.Model): chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11) property_market_rent = models.DecimalField(max_digits=7) @property def ftb_combined(self): ftb_combined = 0 for family_group in self.familygroup_set.all(): ftb_combined += family_group.ftb_combined return ftb_combined class FamilyGroup(models.Model): name = models.CharField(max_length=10) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) last_rent = models.DecimalField(max_digits=7) @property def additional_child_combined(self): return (self.number_of_additional_children or 0) * self.maintenance_rate_additional_child class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) income = models.DecimalField(max_digits=6) @property def weekly_income(self): if self.transaction.income_period == 'Weekly': return self.income return (self.income or 0) / 2 this is how my models are connected, now i made a method in views.py as below: def transaction_print(request, transaction_id): transaction = Transaction.objects.get(id=transaction_id) return render(request, 'report.html', {'transaction':transaction}) I want to make a report in report.html, 1 report for each transaction, and the transaction can have many FamilyGroups and FamilyMember, and will include almost all the data from the models and the property methods inside it. here … -
How to override row size RichField Django CKEditor
I am trying to override the default RichField row size from 10 to 5 but it's not working. Here is my implementation # models.py class Comment(models.Model): """Model definition for Comment.""" content = RichTextField(_('Content'), blank=True, null=True) # forms.py class CommentForm(forms.ModelForm): """Form definition for Comment.""" class Meta: """Meta definition for Commentform.""" model = Comment fields = ('content',) widgets = { 'content': forms.Textarea(attrs={'rows': 5}) } Default Richfield row size is still being used. Any help to solve this is highly appreciated. Thanks in advance. -
How do I call a custom manage.py command from code
I am trying to simulate the progression of match , whose data I receive as an XML file, in order to progress the match I call a manage.py command python3 manage.py db_schedule --filename=./test_data/replay.xml I would like to automate this call from a python code. I tried using call_command(), but get the error "no such command as db_schedule" -
How to store and serve static images using Django, Pythonanywhere, CDN and cloud storage
I'm quite new to web development, just a self-taught enthusiast, so be kind :) Right now I'm trying to deploy my website (built with Django) on Pythonanywhere. Following all advice on static files and it actually works. So basics are done. But images load painfully slow. I know there is some size and weight optimisation to do, but I also heard that the best way to serve large amount of images is to store them separately from the code (in Amazon S3, Google Cloud Storage) and serve through CDN. I have also found a nice service called IMGIX to always serve the most appropriate version of an image. Now the hard question: how does it work together? OK, I can upload all images to the bucket, point CDN to it too. But then how do I go about 'collectstatic' in Django? How do I keep those images linked to the models? Do I resolve it by pointing STATIC_DIR and STATIC_ROOT to that bucket? My mind is failing me here and googling did not help either. Any help would be highly appreciated. -
AWS beanstalk + Django: 502 Bad Gateway - ModuleNotFoundError: No module named 'application'
I'm trying to deploy Django project to Elastic Beanstalk. I'm following their guide: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But after eb open all pages return "502 Bad Gateway". My AWS admin shows django environment as "Degraded". Please see the screenshot: My logs, seems like something with "ModuleNotFoundError: No module named 'application'": ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 983, in _find_and_load Jan 27 19:30:21 ip-172-31-32-137 web: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked Jan 27 19:30:21 ip-172-31-32-137 web: ModuleNotFoundError: No module named 'application' Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3483] [INFO] Worker exiting (pid: 3483) Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3476] [INFO] Shutting down: Master Jan 27 19:30:21 ip-172-31-32-137 web: [2021-01-27 19:30:21 +0000] [3476] [INFO] Reason: Worker failed to boot. Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Starting gunicorn 20.0.4 Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Listening at: http://127.0.0.1:8000 (3488) Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3488] [INFO] Using worker: threads Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 +0000] [3495] [INFO] Booting worker with pid: 3495 Jan 27 19:30:22 ip-172-31-32-137 web: [2021-01-27 19:30:22 … -
Cannot override templates found in admin/auth and admin/widgets in Django
Context I want to override the following django templates: django/contrib/admin/templates/admin/widgets/clearable_file_input.html django/contrib/admin/templates/admin/auth/user/change_password.html With these custom templates: <project_root>/templates/admin/widgets/clearable_file_input.html <project_root>/templates/admin/auth/user/change_password.html My TEMPLATES settings are configured as followed: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] Problem While I have managed to successfully override a lot of other templates that exist in the django/contrib/admin/templates/admin/ path, I cannot seem to be able to override templates that exist in the paths mentioned above. Regarding the widgets, I also tried the instructions found in the docs here to no avail. -
How to convert ReturnList to simple array with objects or modify this list?
I am using serializers.ModelSerializer in Django to get my objects from database. participants = ParticipantSerializer(Participant.objects.all(), many=True) Now I have a contidtion that if elements in returned list is not equals to some constant then I should fill this list with null values. participants = ParticipantSerializer(Participant.objects.all(), many=True) placeLeft = tournament.max_participants - len(participants.data) if(placeLeft > 0): for _ in range(0, placeLeft): participants.append(None) But I've got AttributeError: 'ListSerializer' object has no attribute 'append'. I could not find any source which would help me. Could I ask you for help? How could -
How to deploy a django project to google cloud with celery workers?
So i have a django project which I installed celery and heroku redis for it and I use google cloud for deployment. Everything works fine at local but i need to run my celery workers on website 24/7. I searched for supervisor and installed it too. I start supervisor from my command line. Celery workers runs since I ran supervisor. But there is a problem. I can not hold my pc open all the time. When I close, supervisor stops too. I did not figured out cloud tasks as well. Lastly, I read some infos about kubernetes and celery. Is it possible to use celery with kubernetes and how can i install kubernetes-celery django setup? -
Django Generate Random String Internally and Validate in Form POST Request
Let's say I have a form and want to add some extra security to it. <form method="POST" enctype="multipart/form-data"> ... <button name="delete" role="button">Delete</button> <button name="save" role="button" type="submit">Save</button> </form> I use class-based views. I add a random string to the context within get_context_data(): import random, string def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['random_string'] = ''.join(random.choices(string.ascii_letters + string.digits, k=20)) return context My form then is: <form method="POST" enctype="multipart/form-data"> ... <button name="delete" value="{{ random_string }}" role="button">Delete</button> <button name="save" role="button" type="submit">Save</button> </form> So what I want to do is: Generate a unique string internally and pass to template using context variable named random_string. When form is submitted, if request.POST has a 'delete' key, I want to validate that the value was generated internally from my system. request.POST would look something like this: <QueryDict: { 'csrfmiddlewaretoken': ['gqYBmmeba8Y...EQFVbzpXyPU0TXF'], 'user': ['19'], ... 'delete': ['h3teSs4bLizQF69EvtAU'] }> I'm hoping someone experienced can tell me either: I'm going about this all wrong, here's how to do it, or here's what I should do instead, or there's no need because xyz. My overall goal is just a sanity check to know that the generated random string was actually generated from my system and the user isn't trying to delete something in some … -
What's the problem with sharing job stores in APScheduler?
I did quite get the problem that arises by sharing a job store across multiple schedulers in APScheduler. The official documentation mentions Job stores must never be shared between schedulers but doesn't discuss the problems related to that, Can someone please explain it? and also if I deploy a Django application containing APScheduler in production, will multiple job stores be created for each worker process? -
Django: How to display a pdf file in a new tab?
Most of the posts showing how to open a pdf file in a new tab are 3 years old. What is the best way in Django to open a pdf file uploaded to a model? invoice.py class Invoice(models.Model): file = models.FileField(upload_to='estimates/', blank =True) name = models.CharField(max_length=250, blank =True) def __str__(self): return self.name views.py def view_invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) return render(request, 'index_invoice.html', {'invoice': invoice}) index_invoice.html <a href=""><i class="fas fa-eye"></i>&nbsp;</a> Many Thanks -
How to get exception in custom handler500?
I'm developing my own template for errors pages, but the handler500 don't get the exception parameter, and I can't know what is the cause of error. How can I do this? My custom template already is working, but I need the information about the exception cause. My handler500: def error_500(request): template_name = "error_500.html" error_code = "500" url = request.build_absolute_uri() username = request.user.username useruuid = request.user.uuid date = datetime.datetime.now() errorObject = Errors(error_code=error_code, url=url, username=username, useruuid=useruuid, date=date) errorObject.save() errorUUID = errorObject.uuid context = { "errorUUID": errorUUID } return render(request, template_name, context) -
AWS EB Django ModuleNotFoundError: No module named 'my_project'
I am trying to deploy a django webapp into AWS EB. The app works fine in the localhost but when I try to deploy it, I keep getting ModuleNotFoundError: No module named 'my_project'. File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'my_project' django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application packages: yum: mod_ssl: [] wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() My local directory looks like this: my_project ├── .ebextensions ├── myapp │ ├── settings.py │ └── wsgi.py ├── manage.py ├── requirement.txt . . . I am using Amazon Linux 2 with the Python environment. How can I make it work? -
send django ModelForm through JsonResponse
I'm wondring how to send a django ModelForm through JsonResponse(if i'ts possible). I have a form as class RecordForm(forms.ModelForm): class Meta: model = Records fields = ("title", "file", "doctor") ... in views.py ... return JsonResponse({"form": RecordForm(instace=x)}) ... I want to user form.as_p based on return data after the response returned the form with instance of the object. Thanks in advance gyus! -
How to programmatically set the model when using Django CreateView?
I am trying to programmatically set the model for a Django class-based view that inherits from CreateView and displays a form for creating a 'member' object. My problem is that my template is not displaying the form itself. Note that I override the 'get' method to determine what model the view should use. The template page renders and I see the submit button but when I view the page's source code, the form is missing. Here's my code: # urls.py path('profile/create/', views.ProfileCreate.as_view(), name='profile-create'), # views.py class ProfileCreate(CreateView): model = None template_name = None def get(self, request, *args, **kwargs): member = Member.objects.get(user=request.user) if member.is_couple: self.model = ProfileCouple self.template_name = 'account/profile_couple_create.html' self.fields = ['person1_name', 'person2_name', 'person1_dob', 'person2_dob'] else: self.model = ProfileSingle self.template_name = 'account/profile_single_create.html' self.fields = ['person1_name', 'person1_dob'] context = {} return render(request, self.template_name, context) # models.py class ProfileSingle(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) person1_name = models.CharField(_("Name"), max_length=50) person1_dob = models.DateField() def __str__(self): return self.user.username class ProfileCouple(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) person1_name = models.CharField(_("Name 1"), max_length=50) person1_dob = models.DateField() person2_name = models.CharField(_("Name 2"), max_length=50) person2_dob = models.DateField() def __str__(self): return self.user.username # forms.py class CreateSingleProfileForm(forms.ModelForm): class Meta: model = ProfileSingle fields = ('user', 'person1_name', 'person1_dob') labels = {'user': _('Username'), 'person1_name': _( …