Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My domain name keep switching from example.com to mydomainname.com
After struggling to finish the project, I built a sitemap. After pushing it digital ocean, I and signing up to Google search console it gave out an error (from Google console) invalid domain name. When I looked at the generated file from mydomainname.com/sitemap.xml I saw that example.com is appended to sitemap instead of my domain name. I removed example.com from Sites. But it's showing same thing. I found an article on stackoverflow and realised that I should've changed the name from instead of deleting it. I went on my server and turned the id of mydomainname.com to 1 from the database, now mydomainname.com and example.com is swapping ..? How can I fix this? -
I created a user model myself, but I get an error in 'ChoiceField'. | PYTHON - DJANGO
When I try to register a user, I get the error "('favorite_music' is an invalid keyword argument for this function)". Request Method: POST Request URL: http://localhost:8000/user/register/ Exception Type: TypeError Exception Value: 'favorite_music' is an invalid keyword argument for this function Traceback says, C:\Users\adilc\Desktop\DjangoMusic\Music\user\views.py in register registeredUser = User(username = username, email = email,favorite_music = favorite_music) forms.py class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = MyUser fields = ('full_name','username','email') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = MyUser fields = ('full_name','email', 'password', 'active', 'admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather … -
How to redirect a page using Session ID
I am displaying qr code on a page and save the session id regarding qr code to authenticate the user.Once the user scan the qr code, the scanner app send response by using callback URI. I have received the response for specific user now how I can redirect the user using Session ID. Thanks -
How to fix a false permanent redirect [on hold]
I have used the following code in my project/urls.py but I don't want the change after restarting my project or computer. How can I fix it? I learned it would be difficult. Please explain for a beginner. from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='/app1/', permanent=True)), ] -
Cannot return null for non-nullable fiel error with graphene form mutations
I'm trying an example of graphene-django with forms. But I get next error: `graphql.error.base.GraphQLError: Cannot return null for non-nullable field [MyMutationPayload.name]. I'd tried set values in return expression inside perform_mutate function. It does not work if request does not perform all variations. class MyForm(forms.Form): name = forms.CharField(min_length=10) age = forms.IntegerField(min_value=0) birth_date = forms.DateField() class MyMutation(DjangoFormMutation): class Meta: form_class = MyForm @classmethod def perform_mutate(cls, form, info): print('ok') return cls(errors=[], name=form.cleaned_data.get('name'), age=form.cleaned_data.get('age'), birth_date=form.cleaned_data.get('birth_date')) class Mutations(): my_mutation = MyMutation.Field() class Mutation(Mutations, ObjectType): pass ROOT_SCHEMA = Schema(mutation=Mutation) Query mutation customMutation($data: MyMutationInput!){ myMutation(input: $data){ name age birthDate errors{ field messages } clientMutationId } } Variables { "data": { "name": "Cristhiam", "age": "-29", "birthDate": "1990-04-06" } } Response { "errors": [ { "message": "Cannot return null for non-nullable field MyMutationPayload.name.", "locations": [ { "line": 3, "column": 5 } ], "path": [ "myMutation", "name" ] } ], "data": { "myMutation": null } } Mutation result should show all errors or all form values. -
How to save queryset in models from template data by logged in user?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) match_name = models.CharField(max_length=20, help_text='Enter the name of 2 team using vs (eg. ban vs ind)') first_team = models.ForeignKey('FirstTeam', on_delete=models.SET_NULL, null=True) second_team = models.ForeignKey('SecondTeam', on_delete=models.SET_NULL, null=True) tournament_name = models.ForeignKey('TournamentName', on_delete=models.SET_NULL, null=True) match_created = models.DateTimeField(auto_now_add=True) match_stated = models.DateTimeField(default=timezone.now()) In views: def league(request, pk): match = Match.objects.all() context = { 'match': match, } return render(request, 'main/league.html', context=context) In templates: {% for match in match %} <div class="row text-center py-2"> <div class="col-3"> <img src="{{ match.first_team.flag.url }}" alt="image" class="team-image"> <h6>{{ match.first_team.name }}</h6> </div> <div class="col-6" style="font-size: 14px;"> <p>{{ match.tournament_name }}</p> <div>Starts On: <div style="color: red;">{{ match.match_stated|date:"d F, Y. h:i A" }}</div></div> </div> <div class="col-3"> <img src="{{ match.second_team.flag.url }}" alt="image" class="team-image"> <h6>{{ match.second_team.name }}</h6> </div> </div> {% endfor %} In my admin site, I add many data for my models without user fields and i show that queryset in my templates. This is working properly. Now, i need to save queryset for logged-in user from the templates. In template when users select my build in queryset then the queryset will save in the models with the user who select it. Every user can select the different different data from templates and the data will store in a new … -
Django projects directory permission error on Azure
I am trying to host a Django web project on Azure. I am able to publish it and create a resource for it to read from in the deployment center through a git repository, and it syncs successfully. However when I try to access the actual page I get: "You do not have permission to view this directory or page". I checked the detailed diagnostics and it comes up as 403 and 404 errors I tried uploading a default Django web project and that didn't work either. Tried higher pricing tier (non-free) also didn't work, making project on git public also failed. Below is the detailed diagnostics message from Azure. HTTP 4XX requests detected 404 Directory listing denied. The Web server is configured to not list the contents of this directory. This error typically comes if you do not have the default document configured and the request has come to the root of the site. The default document is the web page that is displayed at the root URL for a website. The first matching file in the list is used. Web apps might use modules that route based on URL, rather than serving static content, in which case there … -
Django/Django REST Framework - Internal API displaying results fetched from external API with filtering
So hey guys currently I'm trying to create an API endpoint that calls an external API via url with some filtering by comma separated strings. I'm used to creating internal APIs with models and views that call from it's own local sqlite database. But I'm less familiar with this. For instance I'm trying to have it so when I open my django devserver for this endpoint say called 'api/data/' it gets the JSON response from say 'www.example.com/api/data?tags=beef,chicken' and displays it. I was thinking about something like the code but wasn't sure how to apply filtering to it without accessing the queryset. import requests from rest_framework import status from rest_framework.response import Response def external_api_view(request): if request.method == "GET": r = requests.get("https://example.com/api/data/") -
Django wsgi server bjoern multithreaded
i would like to use bjoern wsgi server, currently this is working fine but i want to get it multithreaded so that i can access my application localy on multiple ports not only on port 8080 but also und 8081, 8082 etc... currently i do the following at my run.py file which starts the django app: import bjoern from app.wsgi import application bjoern.run(application, 'localhost', 8080, reuse_port=True) how can i spawn multiple processes of run.py on diffrent ports? Or in general how can i use multithreading at this point? The documentation seems quite complicated to me or at least i dont know where to start, https://docs.python.org/3/library/threading.html. Thanks in advance -
How I can store hashed access tokens in the database?
I use django-oauth-toolkit in my application. I noticed that the tokens are stored in the database in raw(unhashed) form. I think it is not secure. I was looking in the documentation and did not find a way to store hashes instead of tokens in db. Did I miss something, or does it really work like that? How can I fix this for my application? -
App works with ModelChoiceField but does not work with ModelMultipleChoiceField
I am trying to retrieve user input data in a django page. But I am unable to choose to multichoice field. I have tried multiple alternatives to no relief. self.fields['site'].queryset=forms.ModelMultipleChoiceField(queryset=sites.objects.all()) self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id)) self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)]) forms.py class SearchForm(forms.Form): class Meta: model= images fields=['site'] def __init__(self,*args,**kwargs): project_id = kwargs.pop("project_id") # client is the parameter passed from views.py super(SearchForm, self).__init__(*args,**kwargs) self.fields['site'] = forms.ModelChoiceField(queryset=sites.objects.filter(project_id=project_id)) views.py def site_list(request, project_id): form = SearchForm(project_id=project_id) site_list = sites.objects.filter(project__pk=project_id).annotate(num_images=Count('images')) template = loader.get_template('uvdata/sites.html') if request.method == "POST": image_list=[] form=SearchForm(request.POST,project_id=project_id) #form=SearchForm(request.POST) #site_name=request.POST.get('site') if form.is_valid(): site_name=form.cleaned_data.get('site') print(site_name) I expect to get a multiselect field but I end up getting this error: Exception Value: 'site' Exception Location: /home/clyde/Downloads/new/automatic_annotator_tool/django_app/search/forms.py in init, line 18 (line 18:self.fields['site'].queryset = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=[(p.id, str(p)) for p in sites.objects.filter(project_id=project_id)])) -
Being a superuser of my Django project, How can l see inventory of other user?
In the Django project, users have their inventory and see only their own inventory when logged in, which is displayed on page via views. If I want to create a dashboard where I can choose any users and see their inventory on a page. I should not need to log in with the user's credentials to see their inventory. -
Can't create user with custom user model and hash password DJANGO
I created a custom user model for my users in django and I'm using django rest framework and Jwt along with angular as my frontend. It was working fine while I was using superuser to login, but now that I've created new users I can't login with them, only with superuser. The main problema that I noticed is that the password wasn't being hashed, so the question is, How can I hash the password when I create an user posting the User from Angular?? is it right the way I'm doing it? Cause I see plenty diferente ways to do it, I'm kind of lost to be honest. Thank you models.py class User(AbstractUser): email = models.EmailField(unique=True) username = models.CharField(blank=True,null=True,max_length=30) is_candidate = models.BooleanField(default=False) is_employer = models.BooleanField(default=False) skype_id = models.CharField(max_length=50, blank=True) last_modified = models.DateTimeField(auto_now_add=False, auto_now=True, null=True) created = models.DateTimeField(auto_now_add=True, auto_now=False, null=True) email_confirmed = models.BooleanField(default=False) user_cpf = models.CharField(max_length=14, blank=True,verbose_name='cpf') company_name = models.CharField(max_length=50, blank=True) user_data_waiver = models.BooleanField(default=True) user_receive_emails = models.BooleanField(default=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() core/urls.py router.register('user', UserViewSet, base_name='user') qualify/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('select2/', … -
Download Button Redirecting to Wrong Page
In my Django project, a user submits an Elasticsearch query into a form and it returns a downloadable report generated from that query. We've made some changes, and now I'm trying to get the portion that returns the report working again. However, I'm running into an issue with my url pattern that should call on the view function to download the report. I have a Download Report button that appears once the report is done being generated (checked by an Ajax request). The idea is that a user will click the button, and the report will appear in their downloads folder. But, when I click the button it sends me to /report/return_doc/ instead of /return_doc/. The logic of sending the user to /return_doc/ is that it's associated with the return_doc function in my views, but can I trigger this function and download the report to the user without refreshing the page/sending them to a new url? Or do I need to do something entirely different to make this button functional? error message Page not found (404) Request Method: GET Request URL: http://0.0.0.0:0001/report/return_doc/ Using the URLconf defined in icm_audit_tool_app.urls, Django tried these URL patterns, in this order: admin/ accounts/ form/ report/ … -
Django Media image files not loading on production on apache
After uploading image by user its not showing on listing page, but its saving in media folder in my production, but its working fine for development. I configured MEDIA_URL, MEDIA_ROOT in settings.py and urls.py and also set alias in apache but still its not loading image In settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' In urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) In Apache(/etc/apache2/sites-available/000-default.conf) <VirtualHost *:80> <Directory /var/www/html/ourdemocracy/newproject/newproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess newproject python-path=/var/www/html/ourdemocracy/newproject python-home=/var/www/html/ourdemocracy/venv WSGIProcessGroup newproject WSGIScriptAlias / /var/www/html/ourdemocracy/newproject/newproject/wsgi.py Alias /static /var/www/html/ourdemocracy/newproject/static <Directory /var/www/html/ourdemocracy/newproject/static> Require all granted </Directory> Alias /media /var/www/html/ourdemocracy/newproject/media/> <Directory /var/www/html/ourdemocracy/newproject/media/> Require all granted </Directory> </VirtualHost> On listing page {% if campaign.campaign_image %} <img src="{{ MEDIA_URL }} {{ campaign.campaign_image.url }}" alt="{{ campaign.title }}"> {% else %} <img src="{% static "img/cause-6.jpg" %}" alt=""> {%endif%} when i am locating the media image its showing following error The requested URL /media/campaigns/images/myimage.jpg was not found on this server. -
Roles in django model
I have a model in django, in which there will be several roles - regular user, admin and manager. Each of them will be able to do something else. Is the following model OK to work correctly? class Team(models.Model): name = models.CharField('Name', max_length=128) users = models.ManyToManyField(User) admins = models.ManyToManyField(User) managers = models.ManyToManyField(User) def __str__(self): return self.name -
project does not recognize custom filter templatetags when deploying(Django + uwsgi + nginx )
When a personal project is deployed to a ubuntu server (16.04), the command ( python manage.py runserver 0.0.0.0:8000) can be used to access the project on the web page, but the static file is not loaded. However, when running with the (uwigs) command, the error was reported to be inaccessible. Project Description:(django2.1,python3) filter positionsetting contentUwsgi+nginx configuration When I run the command in Xshell: use runserver use uwsgi I have used some methods, but I still can't.Another error occurred using the uwsgi command: use uwsgi I don't know if I am clear about it, thank you for your help. -
Player-Team model relationship
I am building a database to show the tournaments of online games. I have three questions; first one, Which method should i use class Player(models.Model): team=models.ForeignKey(Team,related_name='player',verbose_name='Team') OR class Team(models.Model): player=models.ManyToManyField(Player) third; my tables between the team and the player does this look correct? Last; After these tables I will make the tables between the match and the tournament. What should be the relationship between the match and the team class OnlineGame(models.Model): game_name=models.CharField(max_length=120) class Team(models.Model): name=models.CharField(max_length=255,verbose_name="Takım ismi") slug=models.SlugField(max_length=120,unique=True) bio=models.TextField() country=models.CharField(max_length=50) logo=models.ImageField(null=True,blank=True,upload_to='team') background=models.ImageField(null=True,blank=True,upload_to='team') extra=models.CharField(null=True,blank=True,max_length=150) website=models.CharField(null=True,blank=True,max_length=120) game=models.ManyToManyField(OnlineGame)#manytomany because team have one or more online game team (for example sk gaming have lol and counter-strike team def get_unique_slug(self): slug=slugify(self.name.replace('ı','i')) unique_slug=slug counter=1 while Team.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def __str__(self): return self.team_name class PlayerGameRole(models.Model): role=models.CharField(max_length=50) class Player(models.Model): slug=models.SlugField(unique=True,max_length=120) nickname=models.CharField(max_length=120) first_name=models.CharField(max_length=120) last_name=models.CharField(max_length=50) birthday=models.DateField(null=True,blank=True) picture=models.ImageField(null=True,blank=True,upload_to='player') country=models.CharField(max_length=50) role=models.ManyToManyField(PlayerGameRole) team=models.ForeignKey(Team,related_name='player',verbose_name='Team') twitch=models.URLField(null=True,blank=True) facebook=models.URLField(null=True,blank=True) twitter=models.URLField(null=True,blank=True) extra=models.CharField(max_length=150) game=models.ManyToManyField(Game) def get_unique_slug(self): slug=slugify(self.nickname.replace('ı','i')) unique_slug=slug counter=1 while Player.objects.filter(slug=unique_slug).exists(): unique_slug='{}-{}'.format(slug,counter) counter+=1 return slug def age(self): import datetime return int((datetime.date.today() - self.birthday).days / 365.25) -
How to run tests in a django view without affecting the database
I am trying to run the functional tests (using Selenium in python/django) directly from the django views by using management.call_command, in order to allow the user to run the test from the web site. The django view is something like: class MyView(): def get(self): output = call_command('test', 'folder.tests.MyTest') # doing ./manage.py test folder.tests.MyTest test_result = 'Test result: ' + output return something_http_with_test_result What is the best way to do this in order to do not affect the current user data? MyTest is going to create a lot of object in the database but the user must not see them. Thank you -
Work of FormView with Ajax request is not clear
I try to send data from the form to the server using post ajax request. But for some reason, neither form_valid nor form_invalid works. But comes in post method. I try to pull out the form from request.POST, but it turns out to be invalid. forms class CreditFilterExtendedForm(forms.Form): sum2 = forms.CharField(widget=forms.NumberInput(attrs={'id': "sum2", 'class':"form-control"})) views class CreditsList(ListView): def get(self, request, *args, **kwargs): big_form = CreditFilterExtendedForm(self.request.GET or None, prefix="big") class BigFormView(FormView, CreditsList): form_class = CreditFilterExtendedForm prefix = 'big' def form_valid(self, form, *args, **kwargs): print(1) def form_invalid(self, form, *args, **kwargs): print(2) def post(self, *args, **kwargs): print(3) template <form action="{% url 'big_form' %}" class="mt-3" id="big_form"> {% csrf_token %} {{ big_form.sum2 }} <button type="submit" name="{{ big_form.prefix }}">Submit</button> </form> $(document).on("submit", "#big_form", function (e) { e.preventDefault(); $form = $(this); var form_data = new FormData($form[0]); $.ajax({ type: 'post', url: '{% url "big_form" %}', data: form_data, processData: false, contentType: false, success: function(data) { } }) }) There are 2 questions: Why first comes into the post method? Although there is a similar form and it comes right into form_valid. How to find out why the form is invalid? All fields are filled. -
django.core.exceptions.ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module
I have an almost fresh install of django and when I try to python manage.py runserver.It is is giving me this error: File "C:\Users\hp\AppData\Local\Programs\Python\Python36\dj\my2\lib\site-packages\django\core\servers\basehttp.py", line 50, in ge t_internal_wsgi_application ) from err django.core.exceptions.ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. settings.py INSTALLED_APPS = [ 'cognitive.apps.CognitiveConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jchart', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' WSGI_APPLICATION = 'myproject.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_wsgi_application() ```**strong text** -
Form Not Submitting after using slug in my model
I am working on a project, where I need to hide the primary key in the url so I implemented slug in all my models. But the model which is using the foreign key to another model does not seem to work properly. The form is taking values but is not getting submitted no matter what I do. I don't know what is wrong in my code. views.py class CabinCreateView(CreateView): fields = '__all__' model = Cabin success_url = reverse_lazy("NewApp:logindex") def form_valid(self, form): self.object = form.save(commit=False) self.object.cabin = Cabin.objects.filter(slug=self.kwargs['slug'])[0] self.object.save() return HttpResponseRedirect(self.get_success_url()) models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) def __str__(self): return self.user.username def get_absolute_url(self): if (self.verified==True): return reverse("NewApp:mail", kwargs={'pk': self.pk}) else: return reverse("NewApp:userlist") class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("index") template <form method="POST"> {% csrf_token %} <div class="form-group col col-md-3"> <label>Centre Name</label> {{form.centre_name}} </div> <label … -
Multiple models inlineformset django
I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store) A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User") The second is "Product" that has as foreignKey the "ProductPlace" model The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model I created formsets associated to these three models in the "forms.py" file. But i don't know how to do for "views.py" #models.py from django.db import models from django.core.validators import FileExtensionValidator from .validators import validate_file_extension from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class ProductPlace(models.Model): name = models.CharField(max_length=50) num_road = models.IntegerField(blank=False, null=False) name_road = models.CharField(max_length=50) postal_code = models.IntegerField(blank=False, null=False) city = models.CharField(max_length=50) country = models.CharField(max_length=50) acquired_by = models.ForeignKey(User, related_name="product_places", null=True, on_delete=models.SET_NULL) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(blank=False, null=False) place = models.ForeignKey(ProductPlace,related_name="products", on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name class Menu(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(blank=False, null=False) place = models.ForeignKey(ProductPlace, related_name="menus", on_delete=models.CASCADE) … -
Stop signal send trigger for specific Sender
I'm using Django 2.2 In my application, there is a shared user feature and every shared user are added to User model with is_shared field set to True. The shared user is linked to a user in SharedUser model like class SharedUser(models.Model) user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='owner_user') shared_user = models.ForeignKey(User, on_delete=models.CASCASE, related_name='shared_user') On delete of a record from SharedUser model, I also have to delete the linked shared_user record from the User model. For that I'm using the post_signal receiver. receivers.py @receiver(post_delete, sender=SharedUser, dispatch_uid='post_delete_shared_user') def post_delete_shared_user(sender, instance, *args, **kwargs): try: if instance and instance.shared_user: owner = instance.user instance.shared_user.delete() except: pass and the receiver is loaded in the app.py config class SharedUsersConfig(AppConfig): name = 'shared_users' def ready(self): from . import receivers Now, whenever a record from the SharedUser model is deleted, it makes a lot of SQL queries. When the import receivers is removed from the apps.py file. There are a lot more SQL queries being made when the receiver is used to delete the associated user. In my use case, there is nowhere the shared_user is associated to any other model other than SharedUser model. How can I reduce the query on deleting a user? Can I disable sending the … -
How can i remove this django server error
I'm getting this error when i am using the command: python manage.py runserver Error:[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions