Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - What are the advantages and disadvantages of using unique_togueter vs. using a queryset in the view?
Suppose we have the next model: class Publications(models.Model): author = .......... post = .......... and we don't want duplicate records to be stored in the database. This could be done with unique togheter on the model: Meta: unique_together = (author, post) or it could be done in the view with something like: register_exist = Publications.objects.filter(...).exists() if register_exist == False: #Code to save the info What are the advantages or disadvantages of using these methods? -
Django 2.2.6 (Python 3.6) + Apache + Ubuntu 18.04.3 error
I made a django project and I tried deploying it with apache and wsgi, however I'm getting the following error in error.log: Current thread (most recent call first): [Wed Dec 04 17:14:02. 2019] [core:notice] [pid :tid ] AH00051: child pid 27347 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' I'm using python 3.6.9, I've installed every necessary library using pip3 and I've installed ibapache2-mod-wsgi-py3 using apt. This is my mysite.conf in /sites-available WSGIPythonHome /var/www/projectenv/lib/python3.6 WSGIPythonPath /var/www/projectenv/bin/python3 WSGIScriptAlias / /var/www/project/project/project/wsgi.py <VirtualHost *:80> # adjust the following line to match your Python path <directory /var/www/project/site> <Files wsgi.py> Require all granted </Files> </directory> </VirtualHost> Django 2.2.6 is only compatible with python 3, so I'm not sure what to do. I'm not married to the idea of using apache, so if you have any recommendations for other webservers, that will serve as well. Thanks! -
Ajax returns 500 Internal server error but there is no error in django rest framework api request
This is my Ajax requesting function: function updateAPI(key, bool) { console.log(key, bool) console.log('updating...') var data = { 'completed': bool } var url = '/api/todo/' + key + '/update' console.log(url) console.log(data) $.ajax({ url: url, method: 'POST', data: JSON.stringify(data), dataType: 'application/json', success: function (data) { console.log('SUCCESS') console.log(data) }, error: function (data) { console.log('ERR') console.log(data) }, }) } But when i send request manually djangorestframework is working fine. What is the wrong did i do? -
What is the correct way to get translations from Django's *.po/mo files?
Currently I activate each language and then use ugettext but it looks ugly. from django.conf import settings from django.utils.translation import activate, ugettext # settings.LANGUAGES looks like: settings.LANGUAGES = [ ('en', 'English'), ('ru', 'Russian') ] class Profile(models.Model): ACTIVE = 1 INACTIVE = 2 CLOSED = 3 PROFILE_STATUS_CHOICES = ( (ACTIVE, _('Active')), (INACTIVE, _('Inactive')), (CLOSED, _('Closed')), ) def choices_serialize(choices): """ Convert choices to format suitable for Front End's tree-select. :param choices: :return: [{'id': 1, 'text': {'en': 'Active', 'ru': 'Действующий'}}, {'id': 2, 'text': {'en': 'Inactive','ru': 'Недействующий'}}, {'id': 3, 'text': {'en': 'Closed', 'ru': 'Закрыт'}}] """ data = {} for lang in [t[0] for t in settings.LANGUAGES]: activate(lang) for choice in choices: data.setdefault(choice[0], {}) data[choice[0]].setdefault(lang, ugettext(choice[1])) return [{'id': k, 'text': v} for k, v in data.items()] choices_serialize(Profile.PROFILE_STATUS_CHOICES) Is there a better approach? -
Parse Data into HTML Bootstrap modal (Django)
I have downloaded a bootstrap theme. In one of the HTML documents there is a modal. Basically a Popup that contains like a detail page. My question is how I can parse data into that detail page from the specific object I tapped. So some kind of id. Before I used to have the detail page on a separate page. Through a URL I did this: {% url 'URL' object.id %}. This is a part of the modal and lets say I want to change the modal-title depending on the object.id: <div class="modal modal-task" id="task-modal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Create Brand Mood Boards</h5> This is the loop of cards, all with different urls: When I tap one the detail pop-up shows. And I want the data of that card inside the pop-up. like a detail view: <div class="modal modal-task" id="task-modal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Create Brand Mood Boards</h5> Here are the cards: This is the pop-up: -
How to require dependent drop down whenever there are options to choose from in Django?
I have a form with a dependent drop-down. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py def enter_exit_area(request): enter_without_exit = … -
How to add images and document as sub menu item of common menu item on admin panel in wagtail
I want to remove images and documents from menu in admin panel of wagtail. Create a new menu element and add bother as submenu item in wagtail. Please have any idea about it so help me. Thanks in advance! -
See all the items created by the logged in user
novice here trying to get an ebay style e-commerce project finished! When a user checks their profile, I want it to list all the items they have for sale. The owner in the Item model stores the username, so, essentially, I want to check the owner field of all items, then pull the ones that are == username. Here's the code I got so far: views.py def user_profile(request): """The users profile page""" user = User.objects.get(email=request.user.email) user_items = Item.objects.filter(owner__icontains=request.GET[user]) return render(request, 'profile.html', {"profile": user, "items": user_items}) I'm then using {% for item in user_items %} in the html. Apologies if this is an easy one, but I'm struggling to get this right. -
How do i set session storage on angular from a django token?
There is an application(app A) currently on ground which i want to make an integration(app B) for. App A is developed with Django. App B is going to be developed using Angular. So when a user is already logged in to app A, then he clicks the link to app B, a token should be generated for that user when redirected to App B. i need to store the token in storage and get data like email, username e.t.c. from it. -
Need to capture user pk who is posting a tweet
The problem I'm having is somewhere between my views.py and serializers.py, To start this is the error I'm getting. It happens when I try and create a new tweet. The parameter it is having an issue with is from the views TweetAPIView: perform_create. The TweetSerializers doesn't have a 'user' field but I've also tried setting author=self.request.user The goal is to have this new tweet being posted attached to the user posting it. FYI building basic Twitter functionality with this project. Tweet() got an unexpected keyword argument 'user' Views.py from django.shortcuts import render from django.contrib.auth.mixins import UserPassesTestMixin from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from rest_framework.response import Response from rest_framework import generics, mixins from .models import Tweet, User from .serializers import TweetSerializer from .permissions import IsOwnerOrReadOnly class TweetAPIView(generics.CreateAPIView, mixins.CreateModelMixin): lookup_field = 'pk' serializer_class = TweetSerializer def get_queryset(self): return Tweet.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Models.py class User(AbstractUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] USERNAME_FIELD = 'email' def get_username(self): return self.email class Tweet(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="tweets") tweet_text = models.CharField(max_length=200) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet_text Serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): … -
Why is my dependent drop down disappearing upon submission?
I have a form with a dependent drop down. Whenever the form is submitted, only the first field is cleared, if the drop downs were filled out, they remain the same. I have the dependent dropdown set to appear only when there are options available, but after the form gets submitted with an option that has a secondary option, only the first dropdown renders, because it does not load the dropdown logic until you select a new option and go back to what you had. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two remain, however, when the page reloads upon submission, it looks like this And when I look at the data that remained in the form, only the work area stayed, because the dependent dropdown does not load until you select another option from the drop down, and if you wanted to be able to see the Box Assembly options again, you'd have to click another option and then go back to Box Assembly (for … -
Mandatory many to many relationship in Django
Suppose I've a model Car (cars are not owned, may be shared by passengers) and a model Passenger (passenger includes the driver of the bus). The models are read/write able via DRF and admin interface. How can I enforce that each car has at least one passenger and potentially several passengers (mandatory many-to-many relationship)? -
Celery beat tasks not executing
I'm learning periodic tasks in Django with celery beat. But my tasks are not executing. my __init__.py file: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) my celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_todo_app.settings') app = Celery('new_todo_app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) my tasks.py file: from celery import Celery from celery import shared_task app = Celery('tasks', broker='pyamqp://guest@localhost//') @shared_task def progress_bar(): print("Executed every minute") and my settings.py file CELERY_BROKER_URL = 'amqp://localhost' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TIMEZONE = 'Asia/Baku' CELERY_ENABLE_UTC = True CELERY_BEAT_SCHEDULE = { 'progress-bar': { 'task': 'app1.tasks.progress_bar', 'schedule': 5.0, }, } I run celery beat worker by writing: #celery -A new_todo_app beat -l info celery beat starts, but tasks don`t execute.I tried DEBUG logging mode and I get: Configuration -> . broker -> amqp://guest:**@localhost:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%DEBUG . maxinterval -> 5.00 minutes (300s) [2019-12-04 19:35:24,937: DEBUG/MainProcess] Setting default socket timeout to 30 [2019-12-04 19:35:24,938: INFO/MainProcess] beat: Starting... [2019-12-04 19:35:24,975: DEBUG/MainProcess] Current schedule: <ScheduleEntry: progress-bar app1.tasks.progress_bar() <freq: 5.00 seconds> <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * … -
Django: Access num_pages in view to generate pagination
I want to generate a range of pages in my template when using a ListView and it's pagination, to generate dynamically the number of pages for the pagination: https://getbootstrap.com/docs/4.0/components/pagination/ My first attempt was to make a for loop for everyelement in page_obj.paginator.num_pages, getting error int is not iterable: {% if is_paginated %} <ul class="pagination"> {% for i in page_obj.paginator.num_pages %} <li class="page-item"> <span class="page-link"> <a href="/catalogo?page={{i}}"> <span class="sr-only">(current)</span> </span> </li> {% endfor %} </ul> {% endif } Then I've discovered that there isn't and wont be a range template filter because this calculation should be done in the view and send the range to the template, not generated in the template. See: https://code.djangoproject.com/ticket/13088 So how can I access the page_obj.paginator.num_pages inside the view??? My LisView: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 10 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') return context def get_context_data(self, **kwargs): context = super(CatalogoListView, self).get_context_data(**kwargs) context['filtro'] = self.request.GET.get('filtro', 'todas') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = Category.objects.get(slug="catalogo") return context -
Docker app server ip address 127.0.0.1 difference of 0.0.0.0 ip
He everyone. I'm working with docker and trying to dockerize a simple django application that does an external http connect to a web page (real website) so when I set in the Docker file the address of my django server that should work in the container - 127.0.0.1:8000. my app wasn't working because of the impossibility to do an external connection to the website. but when I set the port for my server: 0.0.0.0:8000 it started to work. So my question is: Why it behaves like that? What is the difference in this particular case? I just want to understand it. I read some articles about 0.0.0.0 and it's like a 'generic' or 'placeholder' port that allows to use the OC default port. 127.0.0.1 is like a host that redirects the request to the current machine. I knew it. But when I run the app at my localmachine (host: 127.0.0.0:8000) everything was working and the app could do the connection to the real website but in case of docker it stopped to work. Thanks for any help! Here are my sources: Docker file FROM python:3.6 RUN mkdir /code WORKDIR /code COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY … -
How to make a dependent drop-down be required when there are options available using Django?
I'm fairly new to Django/Python, so apologies in advance. I have a form with a dependent drop-down. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif … -
How to make a field read-only inside a CreateView
I am a Django beginner and I am trying to make read-only a 'price' field for an order. I think, based on what I have understood, this cannot be done inside the model itself, but rather inside a form. Since I am using a CreateView generic view, I thought this could have been done by setting the attribute disabled equal to True, as said here. so what I have done is, in views.py from django.shortcuts import render from django.views.generic import CreateView from .models import Order from django import forms # Create your views here. class CreateOrderView(CreateView): model = Order template_name = 'home.html' meal_price = forms.DecimalField(disabled=True) fields = [ 'meal_name', 'meal_price', 'restaurant', 'customer', ] But this doesn't work. Here is my models.py from django.db import models from restaurant.models import Restaurant from account.models import Customer # Create your models here. class Order(models.Model): meal_name = models.CharField(max_length=255) meal_price = models.DecimalField(max_digits=5, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, default=None) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, default=None) Can anybody give me a hint? Please consider that I am still learning so I would prefer coded answers to descriptive ones. Thank you in advance -
Python django 'NoneType' object has no attribute 'indicador_set'
I have the following problem, I implemented an ajax function to be able to have a dependent dropdown, at the time of creating a question all right but the problem arrives when saving it and sending me to the page to add questions, could someone tell me that I am wrong?. error: Traceback (most recent call last): File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Proyectos\proyecto-educa-quiz\classroom\views\teachers.py", line 733, in question_change form = QuestionForm(instance=question, quiz=quiz) File "C:\Proyectos\proyecto-educa-quiz\classroom\forms.py", line 450, in __init__ self.fields['indicador'].queryset = self.instance.objetivo.indicador_set.order_by('id') AttributeError: 'NoneType' object has no attribute 'indicador_set' this is my code: forms.py: class QuestionForm(forms.ModelForm): class Meta: model = Question context_object_name = 'questions' fields = ('number','objetivo','indicador','text','description', 'texto' ,'puntaje' ,'image','document','video') label = 'Pregunta' def __init__(self ,quiz ,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['objetivo'].queryset = Planificacion.objects.filter(asignatura_id = quiz.subject.id, curso_id = quiz.curso.id) self.fields['indicador'].queryset = PlanificacionIndicador.objects.none() self.fields['texto'].queryset = TextoQuestion.objects.filter(owner__id=quiz.owner.id) if 'objetivo' in self.data: try: objetivo_id = int(self.data.get('objetivo')) self.fields['indicador'].queryset = PlanificacionIndicador.objects.filter(objetivo_id=objetivo_id).order_by('indicador_evaluacion') except (ValueError, TypeError): pass elif self.instance.pk: … -
How to clear only a specific field from a form after submission?
I have a form with a few fields. Most of the time, people only need to change one field every time they submit, not all, so I would like to change it in such a way that upon submission, only the employee # field is cleared, but the Work Area choice and station (if there are any available) remain selected. How could I change the way the form is handled so it is not completely cleared upon submission? I know the form = WarehouseForm() is what clears is, but I'm not sure how I could just specify I only want the employee_number field cleared. views.py def enter_exit_area(request): enter_without_exit = None exit_without_enter = None if request.method == 'POST': form = WarehouseForm(request.POST) if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: # Submission logic form = WarehouseForm() elif 'leave_area' in request.POST: # Submission logic .. form = WarehouseForm() else: form = WarehouseForm() return render(request, "operations/enter_exit_area.html", { 'form': form, 'enter_without_exit': enter_without_exit, 'exit_without_enter': exit_without_enter, }) -
DJANGO ORM join on multiple tables
I have the following models: class Timesheet(models.Model): work_packet logged_billable_hours class WorkPacket(models.Model): type name purchase_order description class PurchaseOrder(models.Model): customer class Customer(Programme): verbose_name the following queries: my_timesheet_Q3 = me.timesheets.filter(date__gte=datetime.date(2019, 9, 1), date__lte=datetime.date(2019, 11, 30)).values('work_packet', 'logged_billable_hours') my_timesheet_Q3_by_wp = my_timesheet_Q3.values('work_packet').annotate(wp_hours=Sum('logged_billable_hours')).order_by() produces: [{'work_packet': 1152, 'wp_hours': Decimal('384.00')}] to the result I would like to add: WorkPacket.type, WorkPacket.name, WorkPacket.purchase_order, WorkPacket.description, Customer.verbose_name I know how to achieve it in plain SQL but I don't using DJANGO ORM. Can you help? -
Django Admin Forms validate child form based on parent values
What I'm trying to do is validate a nested_admin.NestedTabularInline form based on some parent data. (If a parent field is one value check if a child field is blank). But I'm having trouble finding a good solution. I've tried using self.data, but it seems incredibly difficult to parse reliably. I've also seen use of FormSet to access other forms, but I'm not sure how to apply it in my case. A simple example looks like: model.py Parent(models.Model): type = models.CharField(max_length=256) Child(models.Model): value = models.IntegerField() items = models.CharField(max_length=256) admin.py @admin.register(models.Parent) class ParentAdmin(nested_admin.NestedModelAdmin): inlines = [ChildInline] class ChildInline(nested_admin.NestedTabularInline): form = forms.ChildInlineAdminForm model = models.Child forms.py class ChildInlineAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChildInlineAdminForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() # How can I access the parent instance type field here??? I really feel like there should be a straightforward solution I'm missing, but I haven't found it yet so help would be greatly appreciated. -
can't catch/get the created instance, during the test for create_view in Django
I can't get the just created instance during the create_view() test(in Django). The View class works properly. It seems that the instance is being deleted before I can make an assertion(if it's possible to happen like that). this is my view: class CreateItemView(CreateView): form_class = ItemForm template_name = 'item/item_create.html' success_url = '/list_item' # <---- redirecting my test: class ItemViewsTest(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() self.category = create_category() self.item = create_item(self.category) def test_item_create(self): data = { 'number': 2, 'name': 'item_2', 'description': 'item 2 description', 'created_by': 'admin', 'quantity': 100, 'category': self.category.pk, } request = self.factory.post('/item_create', data) response = CreateItemView.as_view()(request) """following has the same result(doesn't work): response = self.client.post( '/create_item/', data, )"""" print(Item.objects.all()) # <----- only getting instance created in SetUp function self.assertEqual(Item.objects.last().name, data['name']) getting no errors for request or response, except the following error for the assertion: Creating test database for alias 'default'... System check identified no issues (0 silenced). FAIL: test_item_create (core.tests.test_views.ItemViewsTest) Traceback (most recent call last): File "D:\PYTHON\Projects\My web\warehouse\warehouse\core\tests\test_views.py", line 155, in test_item_create data['name']) AssertionError: 'item_1' != 'item_2' Ran 1 test in 0.497s FAILED (failures=1) Destroying test database for alias 'default'... and I have the same for another model and it works: class CreateCatView(CreateView): form_class = CategoryForm … -
Django view function getting called twice for one GET request
I have a url path defined as follows: re_path(r'installapp/(.+)', views.install_app, name='install-app') This URL path triggers a view function install_app. When a GET request is made to this URL path, the view function is triggered twice instead of once. How to prevent calling of view function twice for one GET request. -
How can I modify custom datetimepicker to display time selection first?
I have a modal that pops up to request an estimated timestamp. Most of the time, people only have to change the time, not the date, I was wondering how I can modify this so the time selection is displayed first when the picker is clicked, not the date? I'm not too familiar with python so I'm not sure if this is possible. update_modal.html {% load core_tags %} <form id="create-update-form" method="post" action="{% url "operations:update_timestamp_modal" main_object.id %}"> {% csrf_token %} <label>Please enter best estimated time for missing entry/exit</label> <div class="row"> <div class="form-group col-xs-6"> {% standard_input form.edited_timestamp datetimepicker=True hide_label=True %} </div> </div> </form> This is where I get the standard_input from core_tags.py def standard_input(context, field, **kwargs): """ Renders a form field with a label and a tooltip containing the help_text :param context: :param field: Form field :param kwargs: Additional keyword arguments (see below) :return: Rendered HTML for form field Additional optional kwargs: pre_addon: Additional group-addon text that appears before the input post_addon: Additional group-addon text that appears after the input datepicker: Whether or not this should use a datepicker widget datepicker_future: Whether or not this should use a datepicker widget that only allows future dates timepicker: Whether or not this should use … -
How to save manytomanyfield in django rest framewor and angular?
I am trying to save a manyToManyField, but I have the following error. TypeError at Direct assignment to the forward side of a many-to-many set is prohibited. Use .set() instead. In the following way I make my object in angular this.event.plan = []; checkPlan(plan) { if (this.event.plan.indexOf(plan) > -1){ this.event.plan.splice(this.event.plan.indexOf(plan),1); }else{ this.event.plan.push(plan); } } I only have this error when adding a record, when editing everything is done well