Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template internal url concatenation
In my django project, I have URL patterns like below. urls.py in project root: urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('summernote/', include('django_summernote.urls')), ] urls.py in app(blog) root: urlpatterns = [ path('', views.index, name='index'), path( 'category/<str:category_id>', views.category_view, name='category_view', ), ] What I want to do is making hyperlink for each category with django template. Something like below. {% for category in categories %} . <a href="{{ {% url 'index' %}|add: {% url 'category_view' category %} }} " class="nav"> {{category}} </a> {% endfor %} However, it doesn't work. There are too many categories that I can't hard code any of them, but have to make url "(domain root)/category/(category name)" with django template. How can I concatinate two url in a template (as django does with path(A, include(B)) ) -
ModuleNotFoundError: No module named 'social.models' when running celery worker
I have the following project structure: SocialRating - accounts -- __init__.py -- models.py -- tasks.py - instagram -- __init__.py -- crawler.py - social -- __init__.py -- models.py # Not Django models - celery_worker.sh accounts/models.py contains class: from instagram.crawler import InstagramCrawler class SocialProfile(models.Model): ... def collect_profile_stats(self): crawler = InstagramCrawler() record_data = crawler.get_profile_stats(self.account_id) InstagramCrawler class is located in instagram/crawler.py: from social.models import SocialUserData, SocialCommentData, SocialProfileStatsRecordData class InstagramCrawler(object): ... And social/models.py contains simple data classes: @dataclass class SocialUserData(object): user_id: str @dataclass class SocialCommentData(object): social_id: str user: SocialUserData text: str @dataclass class SocialPostStatsRecordData(object): post_id: str subscribers_count: int likes_count: int reposts_count: int comments_count: int post_date: str @dataclass class SocialProfileStatsRecordData(object): subscribers_count: int accounts/tasks.py: @app.task(bind=True) def update_profile_stats(self, social_profile_pk: int): social_profile = SocialProfile.objects.get(pk=social_profile_pk) logger.info(f'Updating profile stats for {social_profile}') social_profile.collect_profile_stats() celery_worker.sh: #!/usr/bin/env bash celery -A SocialRating worker -l info So, when I run celery_worker.sh (from project's root directory) it raises: Signal handler <bound method DjangoFixup.on_import_modules of <celery.fixups.django.DjangoFixup object at 0x106819d30>> raised: ModuleNotFoundError("No module named 'social.models'") Traceback (most recent call last): File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send response = receiver(signal=self, sender=sender, **named) File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 82, in on_import_modules self.worker_fixup.validate_models() File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 120, in validate_models self.django_setup() File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/celery/fixups/django.py", line 116, in django_setup django.setup() File "/Users/user/src/python/web/SocialRating/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) … -
Django - Unable to create Profile instance - Error RelatedObjectDoesNotExist
I am currently following this tutorial. I am hoping the author will see this question and answer to this. https://thinkster.io/tutorials/django-json-api/profiles I am posting the below to create user and profile. {"user":{"username":"admin4", "password":"admin333", "email":"admin4@admin.com"}, "profile" : {"bio" : "My Bio"} } But Looks like only user details getting posted, but profile is not getting created. I have followed the tutorial to create signals and other details inside init.py as well. when I type u.profile i get the below error >>> u = User.objects.all()[1] >>> u <User: admin4@admin.com> >>> u.profile Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\XXXXXXXX.........\lib\site-packages\django\db\models\fields\related_descriptors.py", line 414, in __get__ self.related.get_accessor_name() authentication.models.User.profile.RelatedObjectDoesNotExist: User has no profile. >>> I am not posting the entire code as the whole code base is available in the URL which is specified Thank you -
Django prefetch_related children of children
I have a model Node that looks something like that: class Node(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE) A Node can have several children, and each of these children can have its own children. If I do: root_node = Node.objects.prefetch_related('children').filter(pk=my_node_id) print("Now testing queries") root_node.first().children.first() # Database hit once print("Test 2") root_node.first().children.first().children.first() # Database hit 4 times The database is getting hit multiple times. How could I make it so that it gets the node, its children, the children of its children, etc, in a single database query? -
Custom command failing due to field not being defined
I am creating a custom command that checks all the lessons, and deletes ones with a lesson_datetime_end, that the current date has passed. I am currently getting an error that says lesson is not defined, and was wondering how to properly define it as lessson.lesson_datetime_end is not working. from django.core.management.base import BaseCommand from django.utils import timezone from datetime import datetime from teacher.models import Lesson class Command(BaseCommand): help = 'Expires old lesson objects' def handle(self, *args, **options): if datetime.now() > lesson.lesson_datetime_end: now = timezone.now() Lesson.objects.filter(expire_time__lt=now).delete() -
Troubles editing a django login view
I want to add 2FA to my django app. I found this library but there is some thing i am not understanding. On their example django app they are using the module's login view, it means that the example app does not have its own view, so how do i integrate the 2fa module into my own app? There are two possible ways here: 1) Yes, i could just use their view but the problem is that in the future i want to add other features to my login, so the problem will be: how do i edit the view if i'm using their login view? 2) I could integrate the two fa into my already existing login view (see below), but the problem is that i don't know how to do that. Any advice? this is what my login views looks like at the moment: def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("example:home") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") -
SMTPSenderRefused at /password-reset/ error
How can I solve this problem? EMAIL_HOST_USER = os.environ.get('mymail@gmail.com') EMAIL_HOST_PASSWORD = os.environ.get('generatedpassword') I have generated google app password and put both email and pass on the correct field, still I got this error. Is there any steps to follow? -
Django Saving Form Instance to a Different Database
I am trying to save the instance of the form to a different database. Usually when executing a save on an object instance you will use object.save(using='db_alias'), which I assumed would be for the form.save() function. Currently I am using... form.save(using='db_alias') This throws an error claiming save() got an unexpected keyword argument 'using'. Do I need to override the save() function within this particular form to handle a db_alias argument? I wasn't able to find anything regarding this error when searching, so I am asking here as last resort for the best foot forward. Thanks in advance. -
pagination not working during search in Django
views.py def crud(request): user_list = User.objects.all() paginator = Paginator(user_list, 3) page = request.GET.get('page') users = paginator.get_page(page) return render(request, 'crud/crud.html', {'users': users}) def search(request): users = None fname = request.POST.get('search') try: user_list = User.objects.filter(first_name__startswith=fname) | User.objects.filter(last_name__startswith=fname) paginator = Paginator(user_list, 3) page = request.GET.get('page') users = paginator.get_page(page) except: pass return render(request, 'crud/crud.html', {'users': users}, {'fname': fname}) Crud.html {% csrf_token %} -
Request body arrives in different form on Heroku (new line characters)
Weird problem. As an assignment I have to accept only requests with data {'title':'some movie title'}. On local host my code works fine. On Heroku data is always recognized as incorrect. views.py: class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer def create(self, request, *args, **kwargs): print("Data of the post request for debug:") print(request.data) title = request.data.get('title') if not title: return Response({'Error': "Body should be {'title':'The title of the Movie'}"}, status=status.HTTP_400_BAD_REQUEST) So for example request with content {'title':'Lord of the rings'} returns invalid body error. Tried with browser (django api site), curl and some web request generator. Locally is fine, on Heroku - invalid request. So I printed it on Heroku and this is what I got: <QueryDict: {'_content_type': ['application/json'], '_content': ['{\r\n "title": "snatch"\r\n}']}> Apparently Heroku adds some whitespace characters to received requests. Any idea why this is happening? -
Can we change the rest API of a backend algorithm with another rest API of some similar kind of algorithm with some frontend interface?
I want to change Django rest API of an algorithm related to event detection with another Django rest API of another event detection algorithm using front end interface. Is it possible? -
Question on why the suggested Sentry LOGGING setting works
In the Sentry documentation, the following setup for LOGGING is suggested: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry'], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, }, } All three of the loggers choose the console for their handler. Why would Sentry ever handle any logs? Is this because all three loggers inherit from the root logger, so setting console as the handler adds console to the existing sentry logger? Or something else? Then, the comment on the sentry handler states "To capture more than ERROR, change to WARNING, INFO, etc.". Why would changing this to INFO handle INFO level errors? The root logger has set WARNING as its lowest level, and so how would any handler send an INFO level error to the sentry … -
Django CkEditor Load Custom Plugin - Not Working
I'm creating a custom CkEditor for Django. I followed https://ckeditor.com/docs/ckeditor4/latest/guide/plugin_sdk_sample_1.html and tried to load the plugin but it doesn't. When I put other plugins into my static folder (lib/static/ckeditor/ckeditor/plugins/MYPLUGIN) and try to load them, it works. Maybe someone can help me. Console error: ckeditor.js:98 GET http://127.0.0.1:8000/lib/static/ckeditor/ckeditor/plugins/utils/plugin.js?t=I3I8 net::ERR_ABORTED 404 (Not Found) ckeditor.js:255 Uncaught Error: [CKEDITOR.resourceManager.load] Resource name "utils" was not found at "http://127.0.0.1:8000/lib/static/ckeditor/ckeditor/plugins/utils/plugin.js?t=I3I8". at CKEDITOR.resourceManager.<anonymous> (ckeditor.js:255) at e (ckeditor.js:250) at Array.z (ckeditor.js:250) at y (ckeditor.js:250) at ckeditor.js:251 -
How to create few models with a single query depending on the selected items from the multiple select?
There are 2 models - "RelationType" and "RequestRelation". The second model is connected with the first through MTM field. There is a multiple select form based on a list of “relationship types”. Need to create several models when submitting, depending on the selected items of the multi-select? F.e., if "husband / wife / son" is chosen, need to create 3 models accordingly. Distinctive in them are only the types of relationships. The form is valid, the correct values come. But So far, only one model is created, with lists of all selected relationship types. Also in my code there is a bug. The model is created immediately when the page is loaded, not when it is submitted. Thank you in advance. models.py class RelationType(models.Model): title = models.CharField(max_length=40) def __unicode__(self): return self.title class RelationRequest(models.Model): creator = models.ForeignKey(User, related_name='creator') relation = models.ForeignKey(User, related_name='relation') type_of_relation = models.ManyToManyField(RelationType, related_name='type_relation', verbose_name=_('type_relation')) status = models.BooleanField(_('status'), default=False) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) html <form action="" method="POST" multiple="multiple"> {% csrf_token %} {{ relation_form.type_of_relation }} <input type='submit' value='ok'> </form> forms.py class RelationRequestForm(forms.ModelForm): class Meta: model = RelationRequest fields = ('type_of_relation',) widgets = { 'type_of_relation': forms.SelectMultiple( attrs={ 'class': 'select2', 'style': 'width: 235px', } ), } def __init__(self, … -
Django Generic List View Uses Annotations During Paginator Count SQL Query
When using the Django Generic List View, the same query set is used to generate the paginator.count and object_list. This makes perfect sense, because any filtering needs to be reflected in the count and in the list of objects displayed. However, when adding on annotations to the queryset that are not used in the filter, the count query needlessly includes this additional complexity. I have noticed some instances where the PostgreSQL planner is smart enough to not perform these annotations, but I have also seen the queries require the same work when the count query could be greatly simplified. I am wondering if anyone has ran into this and found a workaround. I have had the following ideas: override the generic list view and paginator to use a count_queryset on the CBV override the the generic list view and paginator to remove any annotations from the provided queryset before calculating the count I am using Django 1.11.4 and PostgreSQL 11.2 . -
Invalid block tag on line 8: 'crsf_token', expected 'endblock'. Did you forget to register or load this tag?
I have a problem, can't see the difference between two codes. First isn't working and second works. I'm getting this: "Invalid block tag on line 8: 'crsf_token', expected 'endblock' . Did you forget to register or load this tag?" Thanks for answers. First: {% extends 'basic_app/base.html' %} {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Please Login</h1> <form method="post" action="{% url 'basic_app:user_login' %}"> {% crsf_token %} <label for="username">Username:</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password:</label> <input type="password" name="password"> <input type="submit" name="" value="Login"> </form> </div> </div> {% endblock %} Second: {% extends 'basic_app/base.html' %} {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Please Login</h1> <form method="post" action="{% url 'basic_app:user_login' %}"> {% csrf_token %} {# A more "HTML" way of creating the login form#} <label for="username">Username:</label> <input type="text" name="username" placeholder="Username"> <label for="password"></label> <input type="password" name="password"> <input type="submit" name="" value="Login"> </form> </div> </div> {% endblock %} -
Convert number to specific word in Python
I am looking to a received number from a form converted to a specific name dependent on the number. Apologies in advance if this is straight forward, my brain is not with it. The form is being posted via a js script to this view 'def create account' from here i want to translate the number to a word i.e 1 = Aries, so when it is posted to the database it shows the revised value. Here is the code - the value is being sent in on 'ss' (star_sign) Thank you def create_account(request): if request.method == "POST": if Account.objects.filter(email=request.POST['email']).exists(): return HttpResponse("dupe") else: ip = get_client_ip(request) cid = "" if "cid" in request.GET: cid = request.GET["cid"] account = Account.objects.create(email=request.POST['email'], first_name=request.POST['first_name'], birth_day=request.POST['birth_day'], birth_month=request.POST['birth_month'], birth_year=request.POST['birth_year'], star_sign=request.POST['ss'], ip=ip, cid=cid) return HttpResponse("window.location.href='/lp/?id=check-email-ss&cid=" + cid + "'") -
Django, My Password Reset Done and Password Reset Complete can be accessed
Im always can accessed Password-reset-done and password-reset-completed instanly without input user email can i block it?? So i want user must input email in http://localhost:8000/accounts/password-reset/ before they can access http://localhost:8000/accounts/password-reset-done/ and http://localhost:8000/accounts/password-reset-complete/ and if user not input email in password-reset, redirect to password-reset Sorry for my poor english Thanks -
using vs-code testrunner with django unittests
I am trying to debug django unit tests in vs-code with python extensions and hitting Exception has occurred: SystemExit my breakpoint is also not hitting. Can some one provide some insights? -
django-allauth openid implementation for Okta
So I am following this doc. I added the following into my settings.py SOCIALACCOUNT_PROVIDERS = { 'openid': { 'SERVERS': [ dict(id='okta', name='Okta', openid_url='https://dev-292302.okta.com/oauth2/default'), ] } } and the following in my login.html {% load socialaccount %} <a href="{% provider_login_url "openid" openid="https://dev-292302.okta.com/oauth2/default" next="/success/url/" %}">Okta OpenID</a> I seem to have issues with "openid" key above. If I add that into anchor above it gives me KeyError. If I remove it I get following. VariableDoesNotExist at /login/ Failed lookup for key [openid='https://dev-292302] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, {'site_name': u'example Server', 'site': <Site: example.com>, 'form': <AuthenticationForm bound=False, valid=False, fields=(username;password)>, 'next': u'/'}]" . another thing is that, which I think could be related, doc says to add id in extra_data field of socialaccount. So should I create a social account first? Attributes are in form (id, name, required) where id is key in extra_data field of socialaccount, name is identifier of requested attribute and required specifies whether attribute is required. -
How to define the slug of another model in myListView
I sort of need help understanding my own code specifically the views.py. I'm trying to change url pattern for my TitleUpdateListView from using my Update models title field and instead using the slug field instead. If someone could help explain line by line whats going in in my TitleUpdateListView so I could better understand whats specifically going on that would be great. urls.py urlpatterns = [ # Update view for each game path('<str:title>/updates/', TitleUpdateListView.as_view(), name='title-updates'), # Adds the ability to sort by platform path('<str:title>/updates/<int:platform_id>/', TitleUpdateAjaxListView.as_view(), name='title-updates-ajax'), ] views.py class TitleUpdateListView(ListView): model = Update context_object_name = 'updates' template_name = 'updates/title_updates.html' def get_queryset(self): title = get_object_or_404(Game, title=self.kwargs.get('title')) return Update.objects.filter(game=title).order_by('-date_published') def get_context_data(self, **kwargs): context = super(TitleUpdateListView, self).get_context_data(**kwargs) context['game'] = get_object_or_404(Game, title=self.kwargs.get('title')) return context class TitleUpdateAjaxListView(ListView): model = Update template_name = 'updates/updates_ajax.html' context_object_name = 'updates' paginate_by = 5 def get_queryset(self): title = get_object_or_404(Game, title=self.kwargs.get('title')) return Update.objects.filter(game=title, platform=Platform.objects.filter( id=self.kwargs.get('platform_id')).first()).order_by('-date_published') def get_context_data(self, **kwargs): context = super(TitleUpdateAjaxListView, self).get_context_data(**kwargs) context['game'] = get_object_or_404(Game, title=self.kwargs.get('title')) return context def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() context = self.get_context_data() return render(request, self.template_name, context) -
Django forms with instance of object
How to create on one page multiple form with instance of each model object. I have already created object of salon. And i need to render form with instance of all objects on one page. forms.py class SalonForm(forms.ModelForm): class Meta: model = Salon fields = ('some_fields') views.py def salon_list(request): salons_list = Salon.objects.all() form = SalonForm() ctx = { 'salons': salons, 'form': form, } return render(request, 'template/list.html', ctx) list.html {% for salon in salons %} {{ salon }} {{ form }} {% endfor %} -
Django Restapi - How to test if POST saves data in database?
So I found this question: Django Rest Framework testing save POST request data And I understood that the data created with POST request should be accessible as long as the function is running. So I made the whole test in one function: class PostMovieAPITest(APITestCase): def test_correct_request(self): title = 'Snatch' response = self.client.post('/movies/', data={'title': title}, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) movies = Movie.objects.all() self.assertTrue(Movie.objects.get(title=title)) The problem is, Movie.objects.all() is empty, even though I send a CREATE/POST request in the same function. The API works fine when I do `manage.py runserver' and test it in browser. But how can write a proper test to check if data is actually saved in database? -
how to return mp3 file in django view
I'm creating audio upload/download app with django and I want to return .mp3 file that I saved in templates/ in my view. please help me. thanks. -
MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
I am trying to install mysqlclient in django virtualenv. But I get this error Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error Complete output from command c:\users\adity\desktop\dev\blog\env\scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\adity\\AppData\\Local\\Temp\\pip-install-wxr9hw0f\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\adity\AppData\Local\Temp\pip-wheel-zjrz983m --python-tag cp37: running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" -Ic:\users\adity\appdata\local\programs\python\python37-32\include -Ic:\users\adity\appdata\local\programs\python\python37-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\8.1\include\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\\Program …