Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access POST data in get_context_data method in Django?
I want to send back as context data, what i got from request.POST in form_valid method. How Can i access that POSTdata in get_context_data() method? -
new read_only + default behaviour of drf 3.8 gives error
here is an example of the error : model: from django.db import models class Hero(models.Model): alias = models.(max_length=60) character = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name serializer: class HeroSerializer(serializers.ModelSerializer): character = HyperlinkedRelatedField(read_only=True, default=<some user object>) class Meta: model = Hero fields = ('character', 'alias') Viewset: class HeroViewSet(NestedViewSetMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.ReadOnlyModelViewSet): queryset = Hero.objects.all() serializer_class = HeroSerializer Test: def test_created_successfully(self): alias = 'blab blah' response = self.client.post(self.url, {'name': name}) self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) now this test used to pass is drf 3.7.7 as i upgraded to drf 3.8.2 this error started to occur django.db.utils.IntegrityError: null value in column "character_id" violates not-null constraint DETAIL: Failing row contains (blah_blah, null). they said that now default + read_only fields are excluded from writable fields so you have to explicitly save those fields by writing perform_create or overriding create , update and save functions of serializer so i wrote this in the viewset def perform_create(self, serializer): serializer.save(character=<some user object>) for reference this perfrom_create is called inside create method of mixins.CreateModelMixin def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) so it worked here but now if the same serializer is changed to(character field is changed to name and … -
View taking too much time to process images with Heroku and S3
I am running a Django application in Heroku which handles multiple image uploads from the user and storage them to Amazon S3. The problem is that the execution of this proccess requires usually more than 30s (the time execution limit of Heroku). I tested it and the line which takes longer time is the one saving the image file in the ImageField. This is done like that because the image has to be cropped and processed by ProcessImageFile(). However this function is not taking long time, but the save method itself, maybe because it storages the files in S3 one by one while saving them. Here is the view (omitted irrelevant lines): @login_required def image_create(request): if request.method == 'POST': images = request.FILES.getlist("files") crop_points = json.loads( request.POST.get('crop_points')) #Validation of inputs in the form: images and other fields if len(images) < 3 : return JsonResponse({'val_result': 'min_error'}) if len(images) > 12: return JsonResponse({'val_result': 'max_error'}) #We Create the gallery, iterate over the images provided by the form, validate, insert custom fields and save them in bulk associating it to the gallery. with transaction.atomic(): new_items = [] gallery = Gallery.objects.create( user=request.user ) for i, img_file in enumerate(images): new_item = Image() new_item.user = request.user #-----THIS IS … -
django "Models aren't loaded yet" while running migrate or makemigrations
I'm trying to run python manage.py migrate/makemirations on my test server (using sqlite) but I get 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.' I've seen other questions and answers on this but the solutions do not work on my issue. I've tried looking at the traceback but it doesn't have much information pointing to where the error is coming from on my app. Here is the traceback: Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/home/isppme/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/isppme/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/isppme/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/isppme/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 15, in check_all_models models = apps.get_models() File "/home/isppme/lib/python3.6/site-packages/django/apps/registry.py", line 178, in get_models self.check_models_ready() File "/home/isppme/lib/python3.6/site-packages/django/apps/registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Python - DJango -psutil: monitoring remote machines and application status
I have some Python scripts that check memory usage and resources in several remote machines in our network. The script also checks the status of some vital services that serve our web application. At the moment we are using a manual process meaning that you run the script and read the results. I want to build a live monitor that continuously shows the state of the system. I have never done something of this kind. My idea would be to run the script on a timer to be executed at certain intervals and then pass the result to a graphical interface build using Django. My question is if this is the right approach. Is there a better way to use python for this kind of operations. Thank you for your suggestions and help. -
How to complement the block of parent template?
I have first.html: {% block title %} hi there {% endblock %} {% block content %} blah-blah {% endblock %} {% block footer %} bye {% endblock %} and second.html. How can I incude all first.html page to second.html and complement content block like this: hi there blah-blah this text is from second.html bye I've tryed {% extends "first.html" %} this text is from second.html (just nothing added) and {% extends "first.html" %} {% block content %} this text is from second.html {% endblock %} (block content is overrided). -
How to list blog posts of a particular user in Django REST Api
How to list blog posts of a particular user. using ListAPIView, all blog posts are listed. How to list blog posts of a particular user? #views.py class BlogList(generics.ListAPIView): queryset = models.Blog.objects.all() serializer_class = serializers.BlogSerializer #serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'user_id', 'title', 'content', 'created_at',) model = models.Blog #urls.py path('', views.BlogList.as_view()), -
VSCode / Django Unit Tests fail when run together, but succeed when run individually
I have the following two tests within my testcase: from rest_framework.test import APITestCase, APIClient class ProductListTest(APITestCase): def test_one(self): client = APIClient() response = client.get('/api/products/') self.assertEqual(True, True) def test_two(self): # mock exceptions mock_products = MockSet() mock_products.add(MockModel( product={'id':1, 'name':'product1'}, )) # hit the API endpoint client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get('/api/products/') # expected result serialized = ProductSerializer([{'product': {'id': 1, 'name':'product1'}}], many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data) When I run them individually, they both pass. If I run them at the same time using a visual studio code extension and "run all", only the first one passes, and the second test fails, because response.data is empty. The status code is 200 though. The view is as simple as it can get: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer -
How to send password reset email with dynamic email backend
I am not configuring my email setting in my project settings.py file.I have made it dynamic so that i got confused how can i send the password reset email here ? path('password-reset/', auth_views.PasswordResetView.as_view(template_name='password_reset.html', html_email_template_name='password_reset_email.html', success_url=reverse_lazy('password_reset_done', ), #normally i used to do -->from_email=settings.EMAIL_HOST_USER, form_class=EmailValidationOnForgotPassword ),name='password_reset'), In other cases i am sending email like this config = EmailConfig.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[user.email], connection=backend) email.send() How can i use this in my urls.py from_email argument -
Change model object url in django admin list using template overriding
Suppose I have a model of Category, and it has been declared in admin.py. There are two things that I want to do using Django template overriding. Add a button on the right near "Add Category +" which is visible only on the Category List page and takes me to another URL. Overriding URLs of Category object so that clicking on each individual category on the list takes to the respective URLs # models.py class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=False) LANGUAGE_ENGLISH = 'en' LANGUAGE_FRENCH = 'fr' LANGUAGES = ((LANGUAGE_ENGLISH, 'English'),(LANGUAGE_FRENCH, 'French'),) language = models.CharField(max_length=12, default=LANGUAGE_ENGLISH, choices=LANGUAGES, blank=False) created_at = models.DateTimeField(auto_now_add=True) # admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'language', 'created_at') list_filter = ('created_at', 'language') search_fields = ('name',) date_hierarchy = 'created_at' ordering = ['-created_at'] Category in the admin panel -
Django causing noReverseMatch even with correct namespacing
I have the below urlpatterns in the root's url.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('api.urls'), name="api_app"), ] where api app contains: app_name="api_app" urlpatterns = [ url(r'^users/', views.UserList.as_view()), url(r'^users/(?P<user_type>[a-zA-Z_]+)$', views.UserList.as_view(), name="filter_type"), ..., ] the first url displays a list of users and the second url accepts a user type and filters the user list with the user_type These both work fine when I put the urls in a browser's address bar. However when I try to reference the second url from a django template like so: <form action="{% url "api_app:filter_type" user_type %}" method="GET"></form> The below error occurs: NoReverseMatch at /api/users/ Reverse for 'filter_type' with arguments '('',)' not found. 1 pattern(s) tried: ['api/users/(?P<user_type>[a-zA-Z_]+)$'] why is that? aren't the namespaces configured correctly? -
How to add custom on fly ordering for a django TabularInline?
I have a list of TabularInline objects for Model in django admin. I want to make their ordering customizable, e.x. drag & drop to rearrange Inline objects. To achieve it I plan: Use JS for drag & drop On drop event - call api endpoint with the ids of items I want to switch On back-end side execute something like: one = Model.objects.get(id=1) two = Model.objects.get(id=2) one.id, two.id = two.id, one.id one.save() two.save() Which does the trick, but I'm not sure if it's safe to swap DB ids like so and maybe there is a better (easier, safer) way to achieve this -
Filed is required on foreign key error Django rest Framework
I am in a issue in which my api is creating a duplicate data as I am just passing ingredient name and its restaurant not Pk etc. So to prevent this thing I made a class Meta: unique_together = ('restaurant' ,'name') constraint in my model . Before this everything was fine just duplicate entries were creating. Now after adding this constraint its saying 'Restaurant field is required' and my serializer is not valid. My Ingredient model is like this class Ingredient(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE ) name = models.CharField(max_length=255 ,) class Meta: unique_together = ('restaurant' ,'name') def __str__(self): return str(self.name) and my Ingredient Serializer is like class IngredientsSerializer(serializers.ModelSerializer): restaurant = RestaurantSerializer(required=False) class Meta: model = Ingredient fields = '__all__' def create(self, validated_data): restaurant = validated_data.get('restaurant') name = validated_data.get('name', None) ingredient = Ingredient.objects.create(restaurant=restaurant, name=name) return ingredient And my view.py for serialize is like @permission_classes([AllowAny]) class CreateIngredients(APIView): def post(self, request): serializer = IngredientsSerializer(data=request.data) if serializer.is_valid(): restaurant=Restaurant.objects.get(id=request.POST['restaurant']) obj_article = serializer.save(restaurant=restaurant) return Response(success_response(data='none', msg='Ingredient added'), status=status.HTTP_200_OK) -
How to store user details without asking the user?
I am trying to store user details with the PhoneBook and Contacts he creates so that I will be able to show the PhoneBook and Contacts that have been created by them. I don't want the user to explicitly add the details himself. It should be handled by the backend. I am successfully able to store the user details with the PhoneBook he created, but when I try to do the same thing with contacts, I am getting an attribute error. models.py class PhoneBook(models.Model): name = models.CharField(max_length=10, blank=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class Contact(models.Model): first_name = models.CharField(max_length=50, blank=False) last_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=13, blank=False, unique=True) phone_book = models.ManyToManyField(PhoneBook, related_name='phone_book') user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.phone_number views.py @login_required def create_phone_book(request): form = CreatePhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = CreatePhoneBookForm() context = {'form': form} return render(request, 'CallCenter/create_phone_book.html', context) @login_required def add_to_phone_book(request): form = AddToPhoneBookForm(request.POST or None) form.instance.user = request.user if form.is_valid(): form.save() form = AddToPhoneBookForm() context = {'form': form} return render(request, 'CallCenter/add_to_phone_book.html', context) forms.py class AddToPhoneBookForm(forms.Form): class Meta: model = Contact fields = ['first_name', 'last_name', 'phone_number', 'phone_book'] class CreatePhoneBookForm(forms.Form): class Meta: model = PhoneBook fields = ['name'] … -
Need help to build the pattern for print the number serially like given example
I have to print some digits like the given example. Can anyone give a pattern for this? Suppose I have 60 digits. On a page, I can print 21 digits. So the total page will be 3 but when I want to print the digits like the given example but I can set the pattern for this. Example: page 1: page 2: page 3: 1 22 43 2 23 44 3 24 45 4 25 46 5 26 47 6 27 48 7 28 49 8 29 50 9 30 51 -
Show modified foreignkey in django form dropdown
Models.py class Receiver_client(models.Model): name = models.CharField(max_length=255, default=0) city = models.CharField(max_length=255, default=0) address = models.CharField(max_length=255, default=0) partner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='client') def __str__ (self): return self.name class OutwardDocket(models.Model): transaction_date = models.DateField(default=datetime.now) dispatch_date = models.DateField(default=datetime.now) sending_location = models.ForeignKey(Receiver_client, on_delete=models.CASCADE, related_name='receiver_location') Views.py @method_decorator([login_required, employee_required], name='dispatch') class OutwardDocketFormView(CreateView): model = OutwardDocket form_class = OutwardDocketForm template_name = 'packsapp/employee/OutwardDocketForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The OutwardDocket was created with success!') return redirect('employee:outward_table') Forms.py class OutwardDocketForm(forms.ModelForm): class Meta: model = OutwardDocket fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['sending_location'].queryset = Receiver_client.objects.all() I am able to show the list of Reciever_client in my OutwardDocket Form but how can I modify it in a way such that it shows the name as well as the city of reciever client ? I don't want to change the str in the reciever client model as it is used in multiple places -
Set up a local version of Travis CI
I am trying to set up some continuous integration utility for a Django python project. The project will use Travis CI, but I also want to be able to do CI locally, for some reason. My plan is to configure a local Travis. But all resources I can find on the web were written a few years ago, such as this question on StackOverflow. Basically, all posts or discussions tell me I should use a Docker image. However, unfortunately, the official Travis image for python on Docker Hub is 3 years old. I don't think it is still being maintained. Is it because there is a new trend, and I am doing the opposite? I don't know what step to take next. -
Row level permissioning for admin page in DRF
In my project i am having few stores and for each store there is one particular owner as well. I wanted to assign stores to particular store owner that he can update the status of the order placed etc. One owner one store in the sense. Other cannot get into stores which is not assigned to him. -
How to generate current date and time on local server using DJango
I know how to print out current date and time in the console, but I am trying to add the date/time as a feature on my daily task python website. I have tried adding it as a function in my views.py file and then inserting the function in the html file of the page i want it to be on, but everything I have tried has not worked. Here is the function I created at first in views.py: def today(): """Shows todays current time and date.""" today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") return today Then I began playing around and tried this: def today(request): """Shows todays current time and date.""" today = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") context = {'today': today} return render(request, context) And this is what I tried adding to the html file: <h4>{{ today }}</h4> -
Stripe Payment Intents With Django And Stripe.js
Problems: 1) Submitting the Stripe.js form with a card that requires authentication (such as 4000002760003184 or pm_card_authenticationRequired) causes the 3D secure popup to appear but the the customer cannot do anything because the page refreshes automatically after clicking submit meaning the customer cannot properly authenticate in time. Need some way to slow this process down by having the customer finish authenticating first. 2) Not sure how to replace "pm_card_visa" with the card number that the user types into the Stripe.js form. 3) What should the form action be? Is {{checkout}} correct? 4) The except statement error message runs each time I try to submit a successful payment which is not desirable. There is also no code for showing the payment was successful. 5) Submitting the Stripe.js form does not store data in the Django database like the older Stripe tokens code does. Note: Creating a subscription and a payment intent causes a successful charge for the subscription as well as the payment intent resulting in a customer getting double charged. I updated the code so that the subscription will be in trial thus avoiding the double charge. Working Older Token Code: https://github.com/justdjango/video-membership/blob/master/memberships/templates/memberships/membership_payment.html https://github.com/justdjango/video-membership/blob/master/memberships/views.py https://github.com/justdjango/video-membership/blob/master/static/js/checkout.js Older Token Code Explanation: https://www.youtube.com/watch?v=zu2PBUHMEew Payment … -
Is it possible to filter out some database rows in the middleware?
Sorry for the length of this question, I could not make it shorter and still meaningful. We have a very simple application with two simple models Company and Building, with a many-to-many relationship between them. Each has a restricted attribute. User is a regular Django User class, except we add a show attribute. # models.py class User(AbstractUser): show = models.BooleanField(default=True) class Company(models.Model): name = models.CharField(max_length=100) restricted = models.BooleanField(default=False) class Building(models.Model): name = models.CharField(max_length=100) restricted = models.BooleanField(default=False) companies = models.ManyToManyField(Company, related_name='buildings') The views are regular Django REST Framework view sets, and the serializers are as simple as possible: # views.py class CompanyViewSet(ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer class BuildingViewSet(ModelViewSet): queryset = Building.objects.all() serializer_class = BuildingSerializer # serializers.py class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' class BuildingSerializer(serializers.ModelSerializer): class Meta: model = Building fields = '__all__' Now we want to implement this behavior: if user.show is False, the user must not be able to see (in the views) the restricted Company and Building. In other words, if john is an User and john.show is False, john can see (in the views) normal_company and normal_building, but not restricted_company or restricted_building. To achieve this, we don't want to edit the views … -
How to delete model objects using an inline formset in Django
In Django I am trying to use an inline formset factory so a user can edit and delete instances of a model related to a parent model via a foreignkey. For some reason the methods I am trying allow me to edit the objects, but when I click the delete checkbox the object doesn't delete. It is not showing me any error messages either, even when I use formset.errors or formset.non_form_errors. Models: class ExerciseName(models.Model): muscle_group = models.ForeignKey(MuscleGroup, on_delete = models.CASCADE) name_of_exercise = models.CharField(max_length=100, default = 'Exercise name', unique=True) def __str__(self): return self.name_of_exercise class SetLogger(models.Model): weight = models.IntegerField(default=0) reps = models.IntegerField(default=0) date = models.DateField(default=datetime.date.today) exercisegroup = models.ForeignKey(ExerciseName, on_delete = models.CASCADE) Content within the view I am using (not including render): exercisename = ExerciseName.objects.get(pk=exercisegroup_id) SetsFormSet = inlineformset_factory(ExerciseName, SetLogger, fields=('weight','reps',), can_delete=True) formset = SetsFormSet(instance=exercisename) sets = SetLogger.objects.filter(exercisegroup=exercisename) if request.method == 'POST': formset = SetsFormSet(request.POST, instance=exercisename) for form in formset: if form.is_valid(): form = form.save(commit=True) else: formset = SetsFormSet(instance=exercisename) And I am displaying the forms in my formset like this: <form method="post">{% csrf_token %} {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <button type="submit" class="save btn btn-default">Save set</button> </form> This code shows a delete checkbox … -
How Can Static Variables Within a Python Class Be Used in an Instance of the Class
In other languages, static variable are only accessible through the class name, and do not relate at all to an instance of that class. I've been following the Django Polls App Tutorial. It seems that when a model is declared, the fields of that model are static variables: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') However, the tutorial then demonstrates how the Django shell can be used: >>> from polls.models import Question >>> q = Question(question_text="What's new?", pub_date=timezone.now()) This is really confusing to me, as it seems that we are constructing, q, an object that is of type Question, but that somehow is capable of holding information (question_test and pub_date) that I thought was only related to the class, not the instance (static variables). Can someone explain to me what is going on? How is it possible that these bits of data are able to be assigned to an instance of the class? Is this a Python or Django related thing? If so, what does q even represent? Does it represent just a row in the table? This is pretty bizarre come from C++ where a static variable can't ever be related to an object of the class. -
Annotate returning null on non-existent values and I want to convert this to null into empty string
I have two models , Customer and Purchase. I want to return the last store that the customer purchased from and order on this. I can successfully show this list, showing last store the Customer purchased from, and being able to order on store name, using the following models, query/subquery. # models class Customer(models.Model): name = models.CharField(max_length=30) class Purchase(models.Model): store = models.CharField(max_length=30) amount = models.DecimalField(decimal_places=2,max_digits=6) customerID = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='purchases',null=False,blank=True) order_date = models.DateField() #viewset #subquery purchase_qs = Purchase.objects.filter(customerID=OuterRef("pk")).order_by("-order_date") queryset = Customer.objects.all().annotate(last_purchase=Subquery(purchase_qs.values('store')[:1])) ordering_fields = ['last_purchase'] My Current Output for Customers who have zero Purchases is. "last_purchase":null I want to have "last_purchase":"" -
Want to allow user to to pick datetime using the django model and forms
I have a Django model that records the DateTime of reservation. and I'm not able to create a date and time picker! I have created a model and form which allows picking a date but not time. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Reservation(models.Model): LastName = models.CharField(max_length=100) FirstName = models.CharField(max_length=100) ReserveDate = models.DateTimeField() form.py from django import forms from .models import Reservation class DateInput(forms.DateInput): input_type = 'date' class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = ['LastName', 'FirstName', 'ReserveDate'] widgets = { 'ReserveDate':DateInput(), } Reservation.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <style> .asteriskField { display: none; } </style> <div class="row justify-content-center"> <div class="col-6"> <div class="card"> <div class="card-body"> <h2> Contact </h2> <form action="" method="post" novalidate> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-secondary" value="Create" /> </form> </div> </div> </div> </div> {% endblock %} I want to see the date and time on the DateTime picker filed