Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
In my Django portal after login to the portal my request.user is always giving the value AnonymousUser
def __call__(self, request): print(request.user) if not request.user.is_authenticated: ----------logic------- Above is a small code snipet. As request.user is giving Anonymoususer I'm not able to write my logic accordingly. Can somebody suggest? - 
        
__init__() takes 1 positional argument but 2 were given login page
So I am new to python and I have been trying to make a very basic login page and whenever I look up this error all the solutions are very specific to the persons code. I am learning python for my comsci 3 independent study class and I have been making a very simple website so I don't really know how to fix this. I have been running into a lot of different errors making the front end and back end of a login/logout page. So here is my code thanks for the help:) urls.py from django.contrib import admin from django.urls import path from hello.views import myView from hello.views import myHome from hello.views import home from hello.views import index from hello.views import game from django.contrib.auth import views as auth_views from django.views.generic.base import TemplateView #from hello.views import index from django.conf.urls import url, include urlpatterns = [ #path('admin/', admin.site.urls), url(r'^admin/',admin.site.urls), url(r'^hello/',include('hello.urls')), path('sayHello/', myView), path('home/',home,name='Home'), path('game/',game), path('home/game.html',game), path('home/home.html',home), path('game/game.html',game), path('game/home.html',home), url(r'^login/$', auth_views.LoginView, {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.LogoutView, {'template_name': 'logged_out.html'}, name='logout'), ] login.html {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} logged_out.html {% … - 
        
Why must context be retrieved via the get_context_data method of the generic class DetailView?
I have a simple question which i will explain. I am reading about generic views using the docs on djangoproject.com, On this page they show the following example: from django.utils import timezone from django.views.generic.detail import DetailView from articles.models import Article class ArticleDetailView(DetailView): model = Article def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context My question is: Why would context need to be initialized by calling the get_context_data method from super() when ArticleDetailView is already inheriting from DetailView ? Can't you already access the context through the get_context_data of the subclass? Like this.get_context_data(**kwargs)? I'm confused! - 
        
How to set `lookup_field` correctly for `HyperlinkedModelSerializer` in Django Rest Framework?
I need to change default HyperlinkedModelSerializer urls. According to documentation, I have to either define url field manually like this: serializers.py class StockSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='stock-detail', lookup_field='unique_id') class Meta: model = Stock fields = ['id', 'url', 'symbol', 'unique_id', 'other_details'] Or use extra_kwargs like this: serializers.py class StockSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Stock fields = ['id', 'url', 'symbol', 'unique_id', 'other_details'] extra_kwargs = { 'url': {'view_name': 'stock-detail', 'lookup_field': 'unique_id'} } But non of them work for me. The error is: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "stock-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This is my views.py: class StockViewSet(ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer And if I change lookup_field to pk (in serializers.py), it work without any errors but urls are not what I want. So how can I set lookup_field correctly? - 
        
TypeError: zincrby() got multiple values for argument 'amount'
I wrote this function for recommendation some items and I use the redis database: def products_bought(self,products): product_ids=[p.id for p in products] for product_id in product_ids: for with_id in product_ids: if product_id!=with_id: r.zincrby(self.get_product_key(product_id), with_id, amount=1) but when I run this codes for use this function: from video.models import Product java1 = Product.objects.get(name='java1') java2 = Product.objects.get(name='java2') java3 = Product.objects.get(name='java3') net1 = Product.objects.get(name='net1') net2 = Product.objects.get(name='net2') net3 = Product.objects.get(name='net3') db1 = Product.objects.get(name='db1') db2 = Product.objects.get(name='db2') db3 = Product.objects.get(name='db3') from video.recommender import Recommender r = Recommender() r.products_bought([java1,java2]) r.products_bought([java1,java3]) r.products_bought([java2,java1,]) r.products_bought([net1,net2]) r.products_bought([net1,net2]) r.products_bought([net2,net3]) r.products_bought([db1,db2]) r.products_bought([db1,db3]) r.products_bought([db2,db1]) I got this error - 
        
Django Rest - Use @action with custom decorator
I have a Rest API in Django and I have the following method in a class that extends ModelViewSet: @custom_decorator @action(methods=['get'], detail=False, url_name="byname", url_path="byname") def get_by_name(self, request): # get query params from get request username = request.query_params["username"] experiment = request.query_params["experiment"] If I remove the first annotator everything works fine. But when I am trying to call this function with both decorators, it does not even find the specific url path. Is it possible to use multiple decorators along with the @action decorator? - 
        
Django unit test client login doesn't work. Why?
I've built an API using Django and Django Rest Framework. In my serializer I defined an organisation which can be posted, but needs to be stored to a different model. I defined my serializer as follows: class DeviceSerializer(serializers.HyperlinkedModelSerializer): geometrie = PointField(required=False) organisation = serializers.CharField(source='owner.organisation') owner = PersonSerializer(required=False) class Meta: model = Device fields = ( 'id', 'geometrie', 'longitude', 'latitude', 'organisation', 'owner', ) def get_longitude(self, obj): if obj.geometrie: return obj.geometrie.x def get_latitude(self, obj): if obj.geometrie: return obj.geometrie.y def create(self, validated_data): print("ORG:", validated_data.get('organisation'], "NO ORG FOUND")) # # Do some custom logic with the organisation here But when I post some json to it, which includes an organisation (I triple checked the input), it prints the line ORG: NO ORG FOUND. Why on earth doesn't it forward the organisation? - 
        
pytest, how to keep database change between test
I'm using the following inside conftest.py @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'HOST': 'localhost', } it reads data from existing DB fine. Now I want to run two tests and want the change I made in preceding tests to persist until test2 (until the whole tests in the file is finished) def test_1(): user = User.objects.get(email='a@example.com') user.username = 'hello' user.save() def test_2(): user = User.objects.get(email='a@example.com') print(user.username) # expect 'hello' but it's not there's scope `session/module' and wonder what it means, session means the whole test run? - 
        
How to ensure uniqueness in create_or_update without db level unique constraint in Django
I am using django 1.10 with MySQL 5.7. I have a table that has a unique_together constraint on multiple columns. But few of these columns are nullable. So the DB level uniqueness is not ensured for null entries in any of these fields. I am using create_or_update method to ensure the uniqueness of rows at the application level. But in race conditions, even this does not ensure uniqueness as the system is horizontally scaled and multiple processes are concurrently trying to call the create_or_update function. I think that this should be very a normal use-case for most of the high-scale services. How do we take care of this problem? From what I think, My options can be: save a string instead of keeping the entries nullable. (but it is a foreign-key field). save a formatted string based on fields of unique together column and check uniqueness on that. I feel that both these options would be unintuitive. What's be the commonly followed best practice here? - 
        
Is there a way I can track only the first change to a field in django models?
I have a django model Posts class Post(models.Model, ModelMeta): ... publish = models.BooleanField(default=False) date_published = models.DateTimeField(default=timezone.now) ... I want to update the date_published field only once, for the first time when publish is set to True. I have gone through Field Tracker and pre_save but both of them update on every change. I probably need to use some sort of flag that is set when publish is set to True(for the first time). Since objects can be updated and queued again, publish is again set to False before approved by an admin. I may probably add flag to the model but I think there probably should be a better way to do this? - 
        
Set the user's profile on creation
I have a user profile model (one to one with User) that looks like this: class Profile(models.Model): user = OneToOneField(User, on_delete=models.CASCADE) facebook_id = CharField(max_length=20, blank=True) google_id = CharField(max_length=20, blank=True) def __str__(self): return self.user.email # creates a corresponding profile for the newly created user @receiver(post_save, sender=User) def user_save(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) and I would like to set the user's profile when I create a new user, so something like this: user = User( first_name=validated_data['first_name'], last_name=validated_data['last_name'], username=validated_data['username']) user.profile['facebook_id'] = social_id But this doesn't seem to work. What is the right way to do this? - 
        
on making asynchronous django chat server i got error on running server
Unhandled exception in thread started by .wrapper at 0x000001B5D1AF5A60> Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\apps.py", line 20, in ready monkeypatch_django() File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\hacks.py", line 10, in monkeypatch_django from .management.commands.runserver import Command as RunserverCommand File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\management\commands\runserver.py", line 11, in from channels.routing import get_default_application File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\routing.py", line 9, in from channels.http import AsgiHandler File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\http.py", line 152, in class AsgiHandler(base.BaseHandler): File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\channels\http.py", line 214, in AsgiHandler @sync_to_async File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\asgiref\sync.py", line 202, in init self._is_coroutine = asyncio.coroutines._is_coroutine AttributeError: module 'asyncio.coroutines' has no attribute '_is_coroutine' - 
        
Text choices attribute not recognised
I'm trying to create a model with django-multiselectfield, but when I run python manage.py runserver I get an error saying : AttributeError: module 'django.db.models' has no attribute 'TextChoices'. I successfully installed django-multiselectfield-0.1.10 and I can't figure out why I get this error. Thanks for any help! from django.db import models from multiselectfield import MultiSelectField class MovieGenre(models.TextChoices): Action = 'Action' Horror = 'Horror' Comedy = 'Comedy' genre = MultiSelectField( choices=MovieGenre.choices, max_choices=3, min_choices=1 ) def __str__(self): return self.question_text - 
        
Running 2 service on 2 terminal using docker-compose
I am using window 10 with docker for desktop linux container. docker-compose.yml version: '2.1' networks: my: {} services: web: build: context: . container_name: myweb command: run python manage.py runserver_plus 0.0.0.0:8000 hostname: myweb depends_on: - service networks: my: aliases: - myweb service: build: context: . container_name: myservices command: run python manage.py runserver_plus 0.0.0.0:6001 hostname: myservice networks: my: aliases: - myservice Terminal 1 docker-compose run --service-ports web Terminal 2 docker-compose run --service-ports service Service getting timeout from web. but when I run just below common docker-compose run --service-port web Then working fine. But I need to put debugger(ipdb) in both services(web/service). Can Someone please hlep me out. - 
        
Django pass extra data to ModelSerializer create from a ModelViewSet serializer.save()
I have this ModelViewSet def create(self, request, *args, **kwargs): data_to_save = request.data pharmacy = Pharmacy.objects.get(pk=request.data['pharmacy']) serializer = self.get_serializer(data=data_to_save) serializer.is_valid(raise_exception=True) serializer.save(myArg=pharmacy) headers = self.get_success_headers(serializer.data) return Response({'results': serializer.data}, status=status.HTTP_201_CREATED, headers=headers) The self.get_serializer(...) points to a class PharmacyUserSerializer(serializers.ModelSerializer): ... The PharmacyUserSerializer(...), I'm overriding the create(...) function like so def create(self, validated_data): request = self.context['request'] myArg = self.context['myArg'] pharmacy = request.user.pharmacy user = User.objects.create_user( **validated_data, user_type=c.PHARMACY, pharmacy=pharmacy ) return user ACcording to the DRF docs, this line looks right (passing arguments to the save method) serializer.save(myArg=pharmacy) Doing the above gives the error, TypeError: 'myArg' is an invalid keyword argument for this function So what's going on? What's the right way to pass data (i guess I'm missing something in the docs). And how do I intercept this extra data in the PharmacyUserSerializer - 
        
AttributeError: 'XXXXX' object has no attribute 'request'
I have modified_by in my model. I want someone update that it takes his user instance .I have written in model def save(self,*args,*kwargs): self.modified_by=self.request.user it gives me error above but i have written same in delete method it works.Any suggestion? - 
        
Different language settings for website and API
I have an application with two languages, Farsi and English. This application provides a website which uses Django templates and a simple API with two endpoints using pure Django. Now I'm facing an issue I can't solve: I want the website to load in Farsi by default and the API to load in English. I have set the LANGUAGE_CODE to 'en' so everything loads in English by default. I'm not using session or cookies. Is there anyway I can tell the website to change the language to Farsi while keeping the API in English? Will I have to use cookies for this (I can't go about implementing sessions)? If so will it also affect the API? I have read the Django docs multiple times and still can't figure out the right way to go about this. Any help would be much appreciated. - 
        
DATA_UPLOAD_MAX_MEMORY_SIZE is overriden with django 2.2.6
I was using django 1.11.23 until last month and there was no DATA_UPLOAD_MAX_MEMORY_SIZE mentioned in my settings.py. It used to allow payloads of sizes far greater than the default value of 2.5MB. However, on switching to Django 2.2.6 and (djangorestframework upgraded from 3.9.1 to 3.10.3) it has suddenly started raising the "RequestDataTooBig" Exception. Now to run the same payloads, I am forced to add DATA_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024 *100 (after seeing multiple answers here). I also switched from python 2.7 to python 3.6.8 but that ideally should not be causing any issue. - 
        
Id field set to auth value in Django
I have a custom id field in my model that looks like this: id = models.CharField(primary_key=True, max_length=400) In my view, I render the form with the auth_id that the user signs in with in the context and then set the value of the id field in the html. See below. in my view: if request.method == 'POST': form = PersonalDetailsModelForm(request.POST) if form.is_valid(): form.save() inject(form, userdata, Section.personalDetails) return HttpResponseRedirect('/IntakeForm/2' + '?instance=' + str(form.instance.id)) else: return HttpResponse(form.errors) # else: # return render(request, 'LSPIntake/personal_details_section.html', {'soldier': form, 'auth_id':userdata['user_id']}, # {'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) else: form = PersonalDetailsModelForm(label_suffix="") # get rid of default colon after labels context = {'soldier': form, 'auth_id':userdata['user_id']} # try: return render(request, 'LSPIntake/personal_details_section.html', context, { 'auth0User': auth0user, 'userdata': json.dumps(userdata, indent=4)}) in the html file: <input type="hidden" name="id" id="id_id" value={{auth_id}}> Now, whenever I sign in again to the same user, django says that the form is not valid. I think it's because it won't allow the same value to be entered into "id" twice since it is a primary_key. I want that to happen, however because if the same user signs in to their account, I don't want there to be multiple records - I want it to update an existing record. … - 
        
BeautifulSoup won't replace string
Function doesn't throw any error but strings stay the same after execute. It look like replace_with is doing nothing. So I checked types of var's and I thing this is the problem: <class 'str'> <class 'bs4.element.Tag'> fixed_text is str and blog_text is tag type. I don't know how to resolve this problem. def replace_urls(self): find_string_1 = '/blog/' find_string_2 = '/contakt/' replace_string_1 = 'blog.html' replace_string_2 = 'contact.html' exclude_dirs = ['media', 'static'] for (root_path, dirs, files) in os.walk(f'{settings.BASE_DIR}/static/'): dirs[:] = [d for d in dirs if d not in exclude_dirs] for file in files: get_file = os.path.join(root_path, file) f = open(get_file, mode='r', encoding='utf-8') soup = BeautifulSoup(f, "lxml", from_encoding="utf-8") blog_text = soup.find('a', attrs={'href':find_string_1}) contact_text = soup.find('a', attrs={'href':find_string_2}) fixed_text = str(blog_text).replace(find_string_1, replace_string_1) fixed_text_2 = str(contact_text).replace(find_string_2, replace_string_2) blog_text.replace_with(fixed_text) contact_text.replace_with(fixed_text_2) - 
        
Django and AJAX: Is it possible, or good practice, to submit a single form from a formset using AJAX?
My django application displays forms in formsets which are filled in by the user. These can be up to 10 forms. I have tried to work out a way to 'save' the data from a single form in this formset as this can take a long time, and users may be interrupted and not submit the entire formset, losing their work. Is this possible (or is it very bad practice?) I am thinking something along the lines of: forms.py: class ResultsForm(forms.ModelForm): result = forms.CharField( widget=forms.Textarea(attrs={'rows': 4}), required=False, label='Result') class Meta: model = Result fields = ( 'id', 'result', ) views: def save_result(request): if request.method == 'POST' and request.is_ajax(): form = ResultsForm(request.POST) if form.is_valid(): form.save() templates: {% for form in formset %} <tr> {{form.id}} <td>{{form.evidence}}</td> <td> <button id='{{ form.prefix }}-save-button' action="{% url 'results:save_result' %}" type='button' class="btn btn-info btn-sm save-result">Save</button> </td> </tr> {% endfor %} Will this work without the correct formset management? Can i isolate a form and validate it/save it using the proper django validation method? - 
        
Heruko Time OUT
I created a django app which works perfectly fine in localhost. The SQL server is in GoogleCloud SQL. There is a simple student form registration, for which I create a form using forms.ModelForm. I use logger to find if it passed/failed the is_valid() constraint. Something like, if form.is_valid(): logging.info("passed") student = form.save() logging.info("Saved) else: logging.error("Failed") When I try with local host, it works fine in getting the POST data and creating objects in the Cloud server, but using heruko, it gets timed out. It does retrieve the POST data but times out even during checking the form, and not even print the log line of passed, giving out a timeout, but it shouldn't be a trouble regarding the SQL server because it didn't log the line in the first place to move to next step, and SQL connectivity works fine in localhost too in creating objects and posting. It throws 503 in at=error code=H12 desc="Request timeout" method=POST path="/student/register/" host=x-y.herokuapp.com request_id=----f43d65a33f03 fwd="98.210.122.173" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https - 
        
How to create a unique id for an entire django formset?
I have created a formset to submit project costs and i want each submission to have a unique id. I want to use the submission id in a url later on(ie "projects/1/cost-submission-edit/3"). 1 is the project's id and 3 should be the cost submission id. The formset is defined as: models.py class ProjectData(models.Model): project_name = models.CharField(max_digits = 20) client = models.CharField(max_digits= 15) class ProjectCostSubmission(models.Model): project_name = models.ForeignKey(ProjectData, max_digits = 20) cost_name = models.CharField(max_digits= 15) amount = models.DecimalField(max_digits=9) submission_date = models.DateField(auto_now_add=True) payment_approval_date = models.DateField(auto_add_now=True) forms.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.label_suffix = "" class Meta: model = ProjectData fields = "__all__" MyFormSet = inlineformset_factory(ProjectData,ProjectCostSubmission, form=MyForm,extra=2) views.py class ProjectCostView(CreateView): template_name = "/project_cost.html" model = ProjectCostSubmission fields = '__all__' form_class = MyForm urls.py path("/projects/<int:project_id>/cost-submission-edit/",ProjectCostView.as_view(),name="costView") After 3 submissions,the edit page renders the formset like this: Project Name Client Cost Name Amount Submission Date Approval Date ------------ ------ -------- ------ --------------- ------------- Project1 Client1 Cost A 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost B 1000.00 12/02/2019 12/03/2019 Project1 Client1 Cost C 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost A 1000.00 12/03/2019 12/03/2019 Project1 Client1 Cost F 1000.00 12/04/2019 12/04/2019 Project1 Client1 Cost G 1000.00 12/04/2019 12/04/2019 ------------------------------------------------------------------------- Total: $6000.00 ------------------------------------------------------------------------- with the url "/projects/1/cost-submission-edit/".'/1/' … - 
        
Redis php session handling and fetching saved session on Django
I have saved php session in redis using php session handler and i want to read that session value in Django. The issue is I am getting a byte sting on Django side which seems to be incorrect format for me as I want the value direct by just passing the key to redis server. I want "This is shahiq" only as a result ? - 
        
Is there a way to avoid Gatsby from breaking when a GraphQL node is empty from a Django Rest Framework source?
I am trying to make a simple blog using Gatsby and Django REST Framework for my endpoints. Along with returning the title and content, I am also returning a tags field which could be an array of object and an empty array when the post contains no tags. The error comes up when I try querying a post with no tags (i.e having an empty array). Gatsby breaks since GraphQL cant go forward into querying the children nodes. This is my GraphQL query from my Gatsby page: query MyQuery { allRestApiPosts { edges { node { tags { id tag { color name } } id content title author { profile { first_name last_name profile_photo } } } } } } And the page breaks with this error: There was an error in your GraphQL query: - Unknown field 'tags' on type 'RestApiPosts!'. How can I avoid this error when there are no tags attached to a post?