Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model field through linked relationship
Is there a way to create a "virtual" field in a model linked to a field in a relationship? e.g. I have: class User(models.Model): organization = models.ForeignKey( "Organization", ... ) Organization model have a field name so I want to add a virtual field in User model (e.g organization_name) to be able to do user.organization_name instead of user.organization.name is it possible? -
Disaply Django Fieldset values according to previously selected option?
I'm using Django's built-in Admin functionality to support a web app's admin users. So far I'm also using mixins and "rest_framework - viewsets" library to have automated a generic CRUD API. In my admin.py files, I've used fieldsets to easily create a nice form to add new records with automatically included dropdowns, checkboxes, dateboxes etc. Great. A recent concern is that some of these some item selections should dictate the available options of other items. For example, if a person selects a state/province, the list of available cities should be restricted to those in just that state/province, instead of all the cities in the database. Is there any way to implement this behavior within the fieldsets syntax / without having to abandon viewsets and revert to manually coding this behaviour? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use variants.set() instead
I am trying to create an api where a user can add a product with many variants. However, when I am sending raw json data from the postman I am getting above error. As you can see, a single variants can have multiple variants so the variants ids are sent at a same time from front end. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Brand(models.Model): brand_category = models.ForeignKey(Category,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Brands" def __str__(self): return self.name class Collection(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Collections" def __str__(self): return self.name class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70,default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" def __str__(self): return self.product_id … -
Django REST Framework token login also works with less fields than I have determined
So I have a Django REST Framework login, and I determindes, that the user need the phone_number, username and password user/serializers.py [...] class Meta: model = Account fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, 'username': {'required': True}, 'phone_number': {'required': True} } [...] But with postman, I can make a post request without the phone_number field and nevertheless I get the token from the Token authentication :/ Postman: -
Django: models.BooleanField(default=False) always save value as 1(True)
I have one Boolean model field payment_received which as default value set to False. From the frontend dropdown it as coming as 0 or 1 form.No matter what value from the dropdown I select it is always saved as 1(True) in the table. I am trying to debug it & I can verify that proper value is coming from the HTML form but after cleaning is done by Django form it is always results in True value. My Model class InvoiceHeader(models.Model): class Meta: db_table = 'invoice_hdr' invoice_no = models.CharField(max_length=50) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) campaign = models.ForeignKey(CampaignHeader, on_delete=models.DO_NOTHING, null=True) invoice_date = models.DateField() invoice_amount = models.DecimalField(max_digits=11, decimal_places=2) cgst = models.DecimalField(max_digits=11, decimal_places=2) sgst = models.DecimalField(max_digits=11, decimal_places=2) igst = models.DecimalField(max_digits=11, decimal_places=2) total_amount = models.DecimalField(max_digits=11, decimal_places=2) payment_received = models.BooleanField(default=False) def __str__(self): return self.invoice_no My Form class InvoiceHeaderForm(forms.ModelForm): class Meta: fields = ('invoice_no','invoice_date','campaign','client', 'invoice_amount','cgst','sgst','igst','total_amount','payment_received') model = InvoiceHeader invoice_no = forms.CharField(max_length=50) invoice_date = forms.DateField() client = forms.ModelChoiceField(queryset=Client.objects.all()) campaign = forms.ModelChoiceField(queryset=CampaignHeader.objects.all()) invoice_amount = forms.DecimalField(max_digits=11, decimal_places=2) cgst = forms.DecimalField(max_digits=11, decimal_places=2) igst = forms.DecimalField(max_digits=11, decimal_places=2) sgst = forms.DecimalField(max_digits=11, decimal_places=2) total_amount = forms.DecimalField(max_digits=11, decimal_places=2) payment_received = forms.BooleanField() def clean_payment_received(self): val = self.cleaned_data['payment_received'] print('TEST1', val) #<---- always True return val def clean_invoice_no(self): invoice_no = self.cleaned_data.get('invoice_no') if InvoiceHeader.objects.filter(invoice_no=invoice_no).exists() and not str(self.instance): raise forms.ValidationError('Invoice … -
This page isn’t working right now If the problem continues, contact the site owner. HTTP ERROR 405. trying to fix this problem? In Django Python
I have two types of users in my AbstractUser model. One gripe is registered as KORISNIK and the second as MAJSTORI. When users under KORISNIK login, they will be available to like profiles from users MAJSTORI. Like button also have to show a number of LIKE from that profile page. But when a user clicks on the like button he is getting an error: This page isn’t working right now If the problem continues, contact the site owner. HTTP ERROR 405 I am trying to find an error but still no progress. Need some suggestions. model.py: class CustomKorisnici(AbstractUser): MAJSTOR = '1' KORISNIK = '2' USER_TYPE_CHOICE = ( (MAJSTOR, 'majstor'), (KORISNIK, 'korisnik') ) user_type = models.CharField(max_length=100,blank=True,choices=USER_TYPE_CHOICE) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) class LikeButton(models.Model): user = models.ForeignKey(CustomKorisnici, on_delete=models.CASCADE) likes = models.ManyToManyField(CustomKorisnici,related_name='profile_like') def total_likes(self): return self.likes.count() view.py def LikeProfile(request,pk): like = get_object_or_404(LikeButton, id=request.POST.get('majstori_id')) like.likes.add(request.user) return HttpResponseRedirect(reverse('majstori_profile', args=[str(pk)])) class LikeMajstoriProfile(DetailView): model = LikeButton context_object_name = 'like_button' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(LikeMajstoriProfile, self).get_context_data(*args, **kwargs) stuff= get_object_or_404(LikeButton, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes'] = total_likes return context class MajstoriProfile(DetailView): model = CustomKorisnici context_object_name = 'majstori' template_name = 'majstori_profile.html' def get_context_data(self, *args, **kwargs): context = super(MajstoriProfile, self).get_context_data(*args, **kwargs) majstori= get_object_or_404(CustomKorisnici, id=self.kwargs['pk']) context['majstori'] … -
Django ValueError: No route found for path 'ws/chat//'
I'm working on making a simple chat app using this tutorial from youtube (github link here: LINK). One potential issue is that the tutorial uses 2.x version of django but i have 3.1.7, but I had it working pretty well and was close, but then started getting this error: ValueError: No route found for path 'ws/chat//' When looking at my terminal, it keeps trying to reconnect over and over, possible becaues I'm using the ReconnectingWebSocket github javascript code. When I run redis-cli and type 'ping', I get 'PONG' in return so I think that is working properly. Below is my code: routing.py (I believe this seems most likely where the issue is) from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), #new django ] wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') application = get_wsgi_application() settings.py: WSGI_APPLICATION = 'django_project.wsgi.application' ASGI_APPLICATION = 'django_project.asgi.application' # older version of django: 'django_project.routing.application' # Channels redis config: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } views.py: chat/views.py from django.shortcuts import render import json from django.contrib.auth.decorators import login_required from django.utils.safestring import mark_safe def index(request): return render(request, 'chat/index.html') @login_required def room(request, room_name): return render(request, 'chat/room.html', … -
Redirect a form in same URL in Django
this is my first question so if i had made any mistakes excuse me. I have a template like below : I have and Object model and for that model i am making queries and returning to template. What i am trying to is when user select one of the objects and submits, I would like to redirect to the same page so based on the object that has been choosen i will have different result for the queries because this Object model related with different models. I am trying to do this in TemplateView. So far I have override the get_context_data() method and return all the Object records for select form and I can return queries results but for just one record which I specify in view. But I couldn't find a way to submit the form and depending on that record return the queries and redirect it to the same url. I am not sure the TemplateView is the best way to do it. Because of the privacy policy of my company i can not share any files for code. I just need a guidance or a clue about my view. Any help will be so appreciated. -
Grouping user in database by category object
I have experienced issues with this code and I truly need assistance. I need to allocate client to another client in a similar category or in the class category like a line or queue. There will be a sending clients and an accepting client the sending client will demand for an installment of the sum in my class or category (for instance $5, $10, $15) at that point the framework will naturally dole out the client to another client mentioning to get an installment in that classification. Lets say it will be a line or queue and it will be the first come and first serve or first assignment. client to client payment and a class or category to classification client matching or allotting to pay every others. kindly investigate my code and tell me what to do. from django.db import models from django.contrib.auth.models import User from collections import deque d = deque('receiving') m = deque('sending') class PaymentCategory(models.Model): price = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, ) class Senders(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Receivers(models.Model): amount = models.ForeignKey(PaymentCategory, on_delete=models.CASCADE) class Payment(models.Model): senders = models.ForeignKey(Senders, on_delete=models.CASCADE) receivers = models.ForeignKey(Receivers, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE) def __init__(self, request, receivers=None, senders=None, *args, **kwargs): super(Payment).__init__(*args, … -
Django class based view, how to return when using django_filter
I am using class based view because I employed django_filter. I also utilize django_tables2. When rendering request after POST I return the context. I figured out how to add table to it, but can't find a way to return pagination or my filter. I can simply redirect to the same page, but it just doesn't feel right. class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 2 filterset_class = ZamowienieFilter def post(self, request, *args, **kwargs): table = self.table_class(Zamowienie.objects.all()) filterset_class = self.filterset_class(ZamowienieFilter) if request.POST.get('zatwierdz_zam'): pk_zn_zamowienie = request.POST["zatwierdz_zam"] Zamowienie.objects.filter(pk=pk_zn_zamowienie).update(zam_status=1) elif request.POST.get('anuluj_zam'): pk_zn_zamowienie = request.POST["anuluj_zam"] Zamowienie.objects.filter(pk=pk_zn_zamowienie).update(zam_status=0) context = {'table': table, 'filterset_class': filterset_class, 'paginate_by': 2} return render(request, self.template_name, context) -
Django Error NoReverseMatch at /invest/(?P1\d+)/
So I am trying to update a value in django. But when clicking on submit it is throwing me a error. NoReverseMatch at /invest/(?P1\d+)/ Reverse for 'invest' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['invest/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/$'] I am calling invest page from brand.html page in this manner <a href="{% url 'invest' pk=marking.id %}";><button type="button" class="btn btn-primary" data-toggle="modal" >Invest</button></a> I am passing the value properly in my html code <script> $(document).on('submit', '#post-form',function(e){ // console.log("Amount="+$('input[name="amount"]').val()); e.preventDefault(); // getting the value entered amount = $('input[name="amount"]').val(); product_title = $('input[name="product_title"]').val(); console.log("Product title="+product_title); console.log("Amount entered by user="+amount); $.ajax({ type:'POST', url:"{% url 'invest' pk=context.id %}", data:{ product_title: product_title, amount: amount, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(xhr, errmsg, err){ window.location = "brand" }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } }); }); </script> urls.py path('invest/(?P<pk>\d+)/', views.invest, name='invest'), views.py def invest(request, pk): # fetching the current event details event_data = MarketingMaestro.objects.get(pk = pk) context = { 'id' : event_data.id, 'product_title' : event_data.product_title, 'total_value' : event_data.total_value, 'total_votes' : event_data.total_votes, } # fetching user details user_data = MarketingInvesment.objects.get(emailID = request.user.email) user_details = { 'name' : user_data.name, 'emailID' … -
Offline django web application with high level of encryption for database
The task: Build an application that manages important documents for internal use only. No internet involves. My solution: Build a django web application that uses sqlite. My question: Is django applicaiton a good choice for this task? How do I encrypt the database, so that hacker cannot use a simple SQLite browser to read the content of the database? Thank you! -
Django crispy forms helper
i installed crispy using pipenv install django-crispy-forms {% load crispy_forms_tags %} works perfectly but when i try to import crispy_forms.helper like below from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit its says Unable to import 'crispy_forms.helper'pylint(import-error) i use Python 3.9.2, and Django 3.1.7 and crispy 1.11.1 i tried install a fresh crispy-forms but still the same problem -
Django Messages not showing in generic view
I am trying to show a flash message in a django app (Django 3.1), but having difficult time figuring out how: My settings are as follows: MIDDLEWARE = [ # other middleware 'django.contrib.messages.middleware.MessageMiddleware', # Even more middleware ] MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', } Then my generic view is as follows: class AppIndex(generic.ListView): model = User, template_name = 'users/index.html' def get(self, request, *args, **kwargs): messages.success(request, "Test users flash message") return super().get(request, *args, **kwargs) My index.html looks like this: {% include 'users/_messages.html' %} <table> {#List of users here...#} </table> The _messages.html partial file looks like this: {% if messages %} {% for message in messages %} <div container-fluid> <div> {{message }} </div> </div> {% endfor %} {% endif %} But this doesnt seem to work in any way. Any help will be greatly appeciated. -
How can I make my twilio code send sms when I sent a product to a customer?
I have a django shop application and I want to send sms using twilio when I sent product to a customer and changed something in the database(for example: changed something to true). So where can I do it to make it work? I am using django + postgresql + gunicorn + nginx + twilio Any suggestions will be appreciated -
Jquery in django : Uncaught TypeError: Cannot read property 'createDocumentFragment' of null
For the life of me I can't figure out what's wrong with this code. It used to work in an earlier version and after I rearranged the javascript at the bottom of the page it just won't work properly. It keeps giving me this error: The row where it throws the error is the following: $('.formset_row').formset({ And this is the jquery plugin that i used. This used to work perfectly until like yesterday when i probably touched something i shouldnt have. <!-- Select2 JS --> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <!-- Semantic UI --> <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script> <script src="/static/bootstrap/js/bootstrap.min.js"></script> <!-- Select2 JS --> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script src="/static/js/script.js"></script> <script> /*$('body').on('focus',".my-date-picker", function(){ $('.my-date-picker').datetimepicker({ format: 'DD/MM/YYYY', ignoreReadonly: true, showTodayButton: true }); });*/ </script> <script src="/static/formset/jquery.formset.js"></script> <script type="text/javascript"> $('.formset_row').formset({ addText: '<div style="color: #34C6AA;" class="my-2 text-center"><span class="oi oi-plus"></span> Add Education</div>', deleteText: '<div style="color: #f4816e; text-decoration: none;" class="my-2 text-center"> <span class="oi oi-x"></span> Remove Education</div> ', prefix: 'educations' }); </script> </body> -
Testing Django views when using django-allauth
I'm using django-allauth for authentication on my site. All my views use LoginRequiredMixin. I'm wanting to simply test that a view loads as expected but I can't seem to correctly login. from django.test import Client password = 'test1234' username = 'test' user = get_user_model().objects.create(username=username, email='test@test.com') user.set_password(password) user.save() client = Client() client.force_login(user) But when I test that I'm able to load the home page, I get redirected back to the login page. Any help would be super appreciated -
Django AppConfig Ready Error: Models aren't loaded yet
I'm trying to run a pubsub function will running in background all the time. In AppConfig i use ready(self) function to start that function and it's running all the time. In that function i call class GetPubSubMessages(Process): and inside of it in def run(self): i run that pubsub listener function. Problem is ,in that listener function i can't use any model or view (error :django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.). I tried to get model in appconfig's ready function but i couldn't pass it as a param to procces class and use it in func. Is there any way that i can include apps then use it in function ? -
Filtering modified at by hour
I was trying to get the number of insurance claims by Day and what time it occurred. For Example, it is March 22 today and there were claims on 8 am another in 12noon. I was trying to get all the claim count this day and what hour did the claims occured. I did try using modified_at__hour but it doesn't show what I needed. Sample code for claims per week and show what day it was claimed class GetClaimsCompare_week(APIView): def get_claim_count(self, claims_data, claim_type): claims_count = claims_data.filter(claim_type = claim_type).count() return claims_count def get_claims_type(self, claims_per_day): return claims_per_day.claim_type #return claims_data.claim_type def get(self, request): today = datetime.now() claims_data = Claims.objects.filter(modified_at__day = today.day) claims_per_day = claims_data.annotate(day = TruncDay('modified_at')).values('day').annotate(claim_type=Count('id')) labels = [] claims_type = list(set(map(self.get_claims_type, claims_data))) final = {} for claims in claims_per_day: labels.append(claims['day']) #data.append(claims['claims']) for claim_type in claims_type: final[claim_type] = self.get_claim_count(claims_data, claim_type) context = { 'Date(s)': labels, 'Claims on this date': final } return Response(context) -
How to optimize access to reverse ForeignKey?
I have models: class ModelA(models.Model): name = models.CharField(max_length=200) class ModelB(models.Model): model_a = models.ForeignKey( ModelA, on_delete=models.CASCADE, related_name="model_bs" ) is_main = models.BooleanField(default=False) I want to make request that returns all ModelA-s, including its main ModelB. Like: [ { "name": "foo", "model_b": { "is_main": true } }, { "name": "bar", "model_b": null } ] I can achieve this with SerializerModelMethod: class ModelASerializer(serializers.ModelSerializer): model_b = serializers.SerializerMethodField() class Meta: model = ModelA def get_model_b(self, obj): model_b = obj.model_bs.filter(is_main=True).first() return ModelBSerializer(model_b).data But it entails an "n+1" problem with DB. It will make additional query on every ModelA. And prefetch_related on model_bs won't help. How to optimize it? -
Django_filters changing label, how to figure out default filter type
I am using django_filter, displaying it in my own way in template. I want to edit label of one of the filters. To do that I need to provide filter type. It works great in default but I can't figure out which filter type is used. This field in my model looks like this: class Zamowienie(models.Model): zam_kontrahent_fk = models.ForeignKey(Kontrahent, on_delete=models.CASCADE) On template it looks like typical select box. I figured out its not django_filters.ChoiceFilter but django_filters.ModelChoiceFilter. I tried using its queryset option but it only displays list of primary_keys (1 instead of 'name' field from the table foreign_key is) class ZamowienieFilter(django_filters.FilterSet): zam_status = django_filters.ModelChoiceFilter(label='Status', queryset=Zamowienie.objects.order_by('zam_kontrahent_fk').values_list('zam_kontrahent_fk', flat=True).distinct()) class Meta: model = Zamowienie fields = [ 'zam_kontrahent_fk', ] Is it correct way to handle that? I didn't find a way to log default filter behaviour, it would help a lot, simply copying this fragment. Any idea how to display values, not list of primary_keys? -
How to prevent upload the file on submit the form
I uploading the file in django with progress bar, and when i choose the file the progress start and when the finish that's mean the file uploaded but when I click in submit form the file upload again and this mean the progress bar is useless, so I want to make something like when I click in submit button the file save with the form but not upload again how I can do this? my form class Video_form(forms.ModelForm,): class Meta: model = Video fields = ('video', 'video_poster', 'title',) the view def VideosUploadView(request, *args, **kwargs): V_form = Video_form() video_added = False if not request.user.is_active: # any error you want return render('account/login.html') try: account = Account.objects.get(username=request.user.username) except: # any error you want return HttpResponse('User does not exits.') if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) video = request.FILES['video'] clip = VideoFileClip(video.temporary_file_path()) instance.video_duration = clip.duration instance.author = account instance.save() V_form.save_m2m() V_form = Video_form() video_added = True if instance.save: return redirect('home') contex = { 'account': account, 'V_form': V_form, 'video_added': video_added, } return render(request, "video/upload_videos.html", contex) the template <form id="upload-form" action="." method="post" enctype="multipart/form-data"> {% csrf_token %} <div id="progress-box" class="d-none">progress</div> <div class="custom-file"> <input type="file" class="custom-file-input" id="formGroupExampleInput2" required value="{{V_form.video}}"> <label class="custom-file-label" … -
Django 500 Internal server error when authenticating against Django’s user database from Apache
I have two web pages on the same server, for each webpage I have created a VirtualHost in Apache. In order to access webpage A (not django) I have to log in previously using the user database from Apache. When I access webpage B (django) I also have to log in, but by default django takes care of it so I don't need to care about it. To achieve that, I have installed mod_wsgi for authentication following Django's documentation My 000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LogLevel info WSGIDaemonProcess wikimedia python-path=/home/ubuntu/django_app python-home=/home/ubuntu/django_app/django_app WSGIProcessGroup wikimedia WSGIScriptAlias / /home/ubuntu/django_app/django_app/wsgi.py <Location "/"> AuthType Basic AuthName "Top Secret" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /home/ubuntu/django_app/django_app/wsgi.py </Location> </VirtualHost> <VirtualHost *:80> ServerAdmin webmaster@example.com ServerName ec2-52-194-22-185.ap-northeast-1.compute.amazonaws.com DocumentRoot /home/ubuntu/django_app ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django_app/static <Directory /home/ubuntu/django_app/static> Require all granted </Directory> <Directory /home/ubuntu/django_app/django_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django_app python-path=/home/ubuntu/django_app python-home=/home/ubuntu/django_app/django_app WSGIProcessGroup django_app WSGIScriptAlias / /home/ubuntu/django_app/django_app/wsgi.py </VirtualHost> wsgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_app.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And this is the apache error.log: Mon Mar 22 07:13:29.386595 2021] [mpm_event:notice] [pid 36906:tid 140284783721536] AH00491: caught SIGTERM, shutting down [Mon Mar 22 07:13:29.480317 2021] [mpm_event:notice] [pid 37031:tid 140582871116864] … -
Django Post save signal gives error save() missing 1 required positional argument: 'self'
I have been working on following model class Member(BaseModel): user = models.OneToOneField(User, on_delete=models.CASCADE) refer_code = models.CharField( max_length=20, unique=True, blank=True, null=True ) and the refer_code was set to be automatically generated when save method is called i.e during creation (not during update) here is my clean method and save method. def clean(self): if not self.user.is_member: raise DjangoValidationError({'user': _('User must member')}) def save(self, *args, **kwargs): if self._state.adding: self.refer_code = self.user.username super(Member, self).save(*args, **kwargs) post_save.connect(save, sender=User) I followed certain tutorials on youtube but got following error save() missing 1 required positional argument: 'self' I want post_save signal to be triggered during creation so I tried created = True but got error. Any help will be useful. -
PUT/PATCH method not updating the response but changes taking place in the database in DRF
I am working on an API using Django REST framework. In my case, I am using nested serializers so I am required to overwrite the .update method. Here's the required desc: Serializers Config Serializer class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField() context = serializers.JSONField() class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] Device Detail Serializer class DeviceDetailSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = [ 'id', 'name', 'organization', 'mac_address', 'key', 'last_ip', 'management_ip', 'model', 'os', 'system', 'notes', 'config', ] def update(self, instance, validated_data): config_data = None if self.data['config'] is None and validated_data.get('config'): config_data_ = dict(validated_data.get('config')) config_templates = config_data_.pop('templates') config = Config.objects.create(device=instance, **config_data_) for template in config_templates: config.templates.add(template.pk) if validated_data.get('config'): config_data = validated_data.pop('config') # When config data is provided with PATCH requests if config_data: instance.config.backend = config_data.get( 'backend', instance.config.backend ) instance.config.status = config_data.get('status', instance.config.status) config_templates = config_data.get('templates') instance.config.templates.clear() for template in config_templates: instance.config.templates.add(template.pk) instance.config.context = json.loads( json.dumps(config_data.get('context')), object_pairs_hook=collections.OrderedDict, ) instance.config.config = json.loads( json.dumps(config_data.get('config')), object_pairs_hook=collections.OrderedDict, ) instance.config.save() return super().update(instance, validated_data) Device Detail Views class DeviceDetailView(RetrieveUpdateDestroyAPIView): serializer_class = DeviceDetailSerializer queryset = Device.objects.all() Now when I Send a PUT/PATCH request to its endpoint, It works fine and the fields in the database get updated, but since after the PUT/PATCH request …