Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having problems in SQLite using Django
I had created two lists First List and Second List, and I'm trying to access the Items of both lists but somehow when trying to access the items of the second list, it shows exception main.models.Item.DoesNotExist: Item matching query does not exist. https://i.stack.imgur.com/9WTJa.png -
Redirecting user to dynamic url after google login using django allauth
NOTE: I asked this question 5 days ago without response so trying again. Remove if this violates the rules of duplicate questions. I am using google sign in to authenticate users using django allauth. There is no need to log the user in prior to them trying to interact with the website, which happens at https://www.example.com/example/5 where 5 is just an id to a model instance in my database. After user login, I would like to redirect the user to the same page they are on. Would it be possible to do this either through passing the model id (5 in this example) through the google credentials and receive the number back at the /accounts/google/login/callback/ callback, or something similar? Or perhaps there is way using django allauth. This question is close to what I need, but I don't know how to get access to the model ID using this approach. Django-Allauth, Multiple login redirect url # In myapp/adapter.py from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): url = super(AccountAdapter, self).get_login_redirect_url(request) user = request.user ''' # pseudocode, change it to actual logic # check user role and return a different URL role = get_user_role(user) if role == 'student': url = … -
Why is CSS not updating with live reload in django
I just figured out how to use live reload with django - (How to get liveserver to render django templates?). I used the first answer (but instead of ./manage.py livereload, I did python manage.py livereload. My problem is that now the CSS is not uploading. I know it is because of the live reload because when I use the regular python manage.py runserver, the CSS loads. Any help on this will be appreciated. (When in my command prompt (I use Windows 10), and while in the directory which contains the manage.py file, I type ./manage.py livereload.) -
How to solve PytestConfigWarning: Unknown config option: DJANGO_ SETTINGS_MODULE error?
I am using django to build my website and I have used django-pytest to test my apps but I have got this error Note I am usign python 3.9 ================================================================== warnings summary =================================================================== ..\venv\lib\site-packages\_pytest\config\__init__.py:1233 c:\users\eng_diaa_shalaby\desktop\unittest\venv\lib\site-packages\_pytest\config\__init__.py:1233: PytestConfigWarning: Unknown config option: DJANGO_ SETTINGS_MODULE self._warn_or_fail_if_strict(f"Unknown config option: {key}\n") -- Docs: https://docs.pytest.org/en/stable/warnings.html This is my pytest.ini file content # -- FILE: pytest.ini (or tox.ini) [pytest] DJANGO_SETTINGS_MODULE = testing_settings # -- recommended but optional: python_files = tests.py test_*.py *_tests.py and I run this command pytest and this is my venv packages Package Version ------------- ------- asgiref 3.3.4 atomicwrites 1.4.0 attrs 21.2.0 colorama 0.4.4 coverage 5.5 Django 3.2.4 django-pytest 0.2.0 iniconfig 1.1.1 packaging 20.9 pip 21.1.2 pluggy 0.13.1 py 1.10.0 pyparsing 2.4.7 pytest 6.2.4 pytz 2021.1 setuptools 57.0.0 sqlparse 0.4.1 toml 0.10.2 -
TemplateDoesNotExist at / on Heroku while working on local server
New to Django and Heroku; I get "TemplateDoesNotExist at /" when loading the page. Have read somewhere that it might have something to do with Caps. My template is called templates. In settings.py : from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent print(BASE_DIR) print(BASE_DIR / 'templates') And TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] HOWEVER in the error, I get : "django.template.loaders.filesystem.Loader: /app/Templates/homepage.html (Source does not exist)" It seems like Heroku doesn't upload the changes I've made to settings.py even though I get "Everything up-to-date" Everybody seems to be using os.path.join but my Pathlib is working correctly (I assume). Thanks in advance for any help :) -
Map selected radio button to existing post category: Cannot assign "'Artikel'": "Post.category" must be a "Category" instance
I want to map radio buttons to given categories. One way is to do this with the help of a choice field. I don't know if this is a good approach. I have seen many other articles and SO-posts but they did not point me to a direction from where I could see my mistake - so after many hours of research I wanted to ask you here. Thanks! models.py class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Kategorie") ... class Post(models.Model): title = models.CharField(max_length=150) .... category = models.ForeignKey(Category, verbose_name="Kategorie", forms.py CAT_CHOICES= [ ('Artikel', 'Artikel'), ('Videos', 'Videos'), ('Anderes', 'Anderes'), ] class PostForm(forms.ModelForm): category = forms.ChoiceField(widget=forms.RadioSelect, choices=CAT_CHOICES) class Meta: model = Post # is this throwing an error because I only handle the 'Post' model? fields = [ 'title', ... 'category', ] views.py def function_name(request): ... if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # error happens here template.html: <label>Artikel</label> <input id="category0" type="radio" name="category" value="Artikel"> <label>Videos</label> <input id="category1" type="radio" name="category" value="Videos"> <label>Anderes</label> <input id="category2" type="radio" name="category" value="Anderes"> output: ValueError at / Cannot assign "'Artikel'": "Post.category" must be a "Category" instance. What would be a good practice to handle this? I am thankful for any advice. -
Will django notifications be there in React Native?
I am building a simple blogapp in Django AND i made few features like like, dislike, chat, comment on blog and i set up to create notification using models.py class Notification(models.Model): receiver = models.ManyToManyField( User, related_name="notification_receiver", default=None) sender = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notification_sender') content = models.CharField(max_length=100, null=True, blank=True) When someone send a message using chat then i am getting a notification from browser. BUT i am trying to convert my django app into React Native. So, will notifications be sent in React Native with same lines of code in django. I am new in React Native and i have no idea how notifications works in React Native. So, Any help would be Appreciated. Thank you in Advance. -
404 error when access Wagtail cms page after Integrating Wagtail with existing Django project
I am new to Wagtail and intended to learn by practice. Django=3.0.5 | Wagtail=2.13.1 | Python=3.7.10 I have existing Django project with below file structure: |- manage.py |- static/ |- templates/ |- IoTSite/ ___|- urls.py ___|- settings.py ___|- ... I was strictly following Wagtail official guide: Integrating Wagtail into a Django project for this integration. However, after I finish the root urls.py config, // IoTSite/urls.py urlpatterns = [ path('',TemplateView.as_view(template_name='homepage.html'),name='home'), path('admin/', admin.site.urls), path('article/',ArticleListView.as_view(template_name='TL_ArticleList.html'),name='article-list'), path('article/<int:pk>/',ArticleDetailView.as_view(template_name='TL_ArticleDetail.html'),name='article-detail'), path('archive/<int:year>/<int:month>/', ArticleMonthArchieveView.as_view(month_format='%m',template_name='TL_ArticleList.html'),name='archive_mmonth'), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('pages/', include(wagtail_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) when I try to access Wagtail admin site; http://127.0.0.1/cms/ I encountered 404 not found error with below debug details. Using the URLconf defined in IoTSite.urls, Django tried these URL patterns, in this order: 1. [name='home'] 2. admin/ 3. article/ [name='article-list'] 4. article/<int:pk>/ [name='article-detail'] 5. archive/<int:year>/<int:month>/ [name='archive_mmonth'] The current path, cms/, didn't match any of these. Q1: Why 127.0.0.1/cms was not matched when it was clearly configured in urls.py? are there any required configs not mentioned in the official guide ? Q2: Behind the scene, how Django and Wagtail interacts with each other? I did not see a Watgail app folder within the Django project directory, it seems that Django interacts with Wagtail purely via import … -
Restoring Django request object in graphene
I'm using graphene-django to make an API, I don't have access to the request object anymore. I want a global variable to access the logged in user in any file. I want to implement this solution and I want to know if it's unnecessary or the right way. class user: __instance = None def __new__(cls, username, id, **_ignored): if cls.__instance is None: cls.__instance = object.__new__(cls) cls.__instance.username = username cls.__instance.id = id return cls.__instance Also opened to your solutions. Thanks! -
Ckeditor Tool icons are not showing
I installed django-ckeditor using pip install django-ckeditor. while using it in the normal page (I created a html and inserted the form.media and form to get the editor there) everything worked but the icons in the toolbar are not appearing in the page where I wanted to use it. Note: I am able to use it properly in admin page and the icons are also appearing. Icons here are not appearing but the functionality is working i.e, 'Ctrl+B' works for etc.. Image: Files are: In the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'accounts', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_UPLOAD_PATH = '' STATIC_URL = '/static/' STATIC_ROOT = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = 'media/' In the models.py file: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Message(models.Model): msg = RichTextUploadingField(blank=True, null=True) cid = models.ForeignKey(Car, on_delete=models.CASCADE) id = models.AutoField(primary_key=True) def __str__(self): return f"{self.id}:{self.msg[:6]}" In the forms.py file: from django.db.models import fields from django.db.models.base import Model from django.forms import ModelForm from .models import Message class MessageForm(ModelForm): class Meta: model = Message fields = ['msg','cid'] In the html: <form method="POST"> {% csrf_token %} {{ form.media }} {{ form }} <button class="btn btn-secondary">Post</button> </form> -
paypal.HostedFields.isEligible() returns False always : Paypal Debit/Credit Card Payment
I want to include debit/credit card payments powered by papal for my website, I am following the guide as per https://developer.paypal.com/docs/business/checkout/advanced-card-payments/ but for the code paypal.HostedFields.isEligible() I always get the false or undefined as error, may be I skipped something, please help. -
How to correctly get variables from Django to javascript and do a GET ajax call on a Django URL?
I apologize if I butchered the terms there. I'm learning webdev and I still don't understand how these technologies work together, so I'm writing everything that might contribute to the problem. Here's where I'm at right now: The urlpatterns in sites/urls.py: urlpatterns += [ path('api/test/<str:crop>/<str:category>/<str:date_from>/<str:date_to>/', data.get_test_page_data), path('test/<str:item>/<str:category>/<str:date_from>/<str:date_to>/', data.render_initial_test_page) ] The functions in data.py: def get_test_page_data(item, category, date_from, date_to): date_from = datetime.datetime.strptime(date_from, "%Y-%m-%d") date_to = datetime.datetime.strptime(date_to, "%Y-%m-%d") data = Items.objects.all().filter(item=item, category=category, date__range=[date_from, date_to]) context = { "data" : data, } return JsonResponse(context) def render_initial_test_page(response, item, category, date_from, date_to): ... context = { "item" : item, "category" : category, "date_from" : date_from, "date_to" : date_to } return render(response, 'sites/test.html', context) The test.js: var sites, map; var test_data; var item = '{{ item }}'; var category = '{{ category }}'; var date_from = '{{ date_from }}'; var date_to = '{{ date_to }}'; getTestData(); function getTestData() { $.ajax({ method: 'GET', url: '/api/test/' + item + '/' + category + '/' + date_from + '/' + date_to + '/', success: function(data) { test_data = data; renderTestData(); } }); } The problem: It doesn't work. It should render two objects in the test page, one Google Maps with markers on where the item is last seen … -
How to print filtered results from django model
I am trying to print the filtered results from a django model. This is my code record = StudentInfo.objects.filter(Name=name, School=school, City=city, Country=country) I know there are 4 entries that satisfy the filter. I now want to print the records. But when I try print(record) I get the following [<StudentInfo: StudentInfo object (1)>, <StudentInfo: StudentInfo object (4)>, <StudentInfo: StudentInfo object (6)>, <StudentInfo: StudentInfo object (8)>] How do I print the entire record as a list? -
Django Celery background scraper
I need some help, My setup is Django, Postgres, Celery, Redis – all dockerized. Besides regular user-related features, the app should scrape info in the background mode. What I need is to launch the scraping function manually from management command like "python manage.py start_some_scrape --param1 --param2 ..etc", and know that this script works in the background mode informing me only by logs. At this moment script works without Celery and only while the terminal connection is alive what is not useful because the scraper should work a long time – like days. Is Celery the right option for this? How to pass a task from management command to Celery properly? How to prevent Celery to be blocked by the long-time task? Celery also has other tasks – related and not related to the scraping script. Is there are threads or some other way? Thx for help! -
How to pass a javascript constant to django?
Usually, you pass Django vars to HTML templates but today I want to do the opposite. I have a custom tag in javascript and I need to pass it back to handle it inside Django. @register.filter(name='test_alerst') def test_tags(value, arg): return MyFunction(val) goalg pass myConst to the function test_tags % load test_tags %} <!doctype html> <html lang="en"> <body> <button id='botton'>socket.send</button> <script> const myConst = javascriptThings {% with name= myConst %} {{ token|test_alerst:name }} {% endwith %} Error: django.template.exceptions.TemplateSyntaxError: 'with' expected at least one variable assignment -
Prevent Django from Removing Previous Entries in PostgreSQL
I have the following Django code that is being run on PostgreSQL and Huey (an automatic scheduler). The problem is that, whenever the periodic task is run, Django removes the previous rows in a table instead of adding on to existent ones. Scheduled code: @periodic_task(crontab(minute='*/1')) def scheduled(): team = nitrotype.Team('PR2W') team_id = team.data["info"]["teamID"] timestamp = datetime.datetime.now() for members in team.data["members"]: racer_id = members["userID"] races = members["played"] time = members["secs"] typed = members["typed"] errs = members["errs"] rcd = RaceData( racer_id=racer_id, team_id=team_id, timestamp=timestamp, races=races, time=time, typed=typed, errs=errs ) rcd.save() Basically, the above code is going to run every minute. Here's the database (PSQL) data that I started with: nttracker=# TABLE data_racedata; racer_id | team_id | timestamp | races | time | typed | errs ----------+---------+------------+--------+---------+----------+-------- 35051013 | 765879 | 1623410530 | 4823 | 123226 | 793462 | 42975 35272676 | 765879 | 1623410530 | 8354 | 211400 | 1844434 | 38899 36690038 | 765879 | 1623410530 | 113 | 2849 | 16066 | 995 38486084 | 765879 | 1623410530 | 34448 | 903144 | 8043345 | 586297 38625235 | 765879 | 1623410530 | 108 | 2779 | 20919 | 1281 39018052 | 765879 | 1623410530 | 1908 | 48898 | 395187 | … -
django: how to calculate percentile of each value
I have a model class TestResults(models.Model): name = models.CharField(max_length=256) score = models.FloatField() Now how to add percentile column using annotate the procedure for calculating percentile of each value Percentile = (number of values below score) ÷ (total number of scores) x 100 I know we can use annotate from django.db.models import F total = TestResults.objects.all().count() TestResults.objects.annotate(...) <-- here how to get number of values below -
Django models - year and monthly fields
I am developing a system using Django 3.0, I need to change balance values on a monthly basis but still have the previous value for displaying on the statement example bills statements.. how best can write my models -
Which field use in a model if I need store several elements in one field?
I try to create a model cart on my shop site. It model should contain the product names. class Cart(models.Model): products = models.Field() Cart.products = 'ps5', 'tv', 'keyboard' -
Django seems to not escape XSS attacks?
I will appreciate your help in this so much, I am developing a Django application and everything is fine and working. I was reading yesterday about security breaches and how django templates permit to block dangers like csrf, xss...etc. So I wanted to test my app if it does escape an xss attempt before I move on with my app and duplicate my models, forms, and views. What I did was that I have entered as input <script alert("xss"); in one of my forms (POST), pressed the submit button, and checked the entered instance in a list view. My problem is that it was there with the exact same input without any sort of encrypting from Django. Yes, the javascript didn't get executed and no alert message showed, but isn't Django supposed to escape/encript html tags? I have also inspected the code source behind and, similarly, the result is exactly as I have entered it. The same thing in the database. The input is stored as it is without escaping the html tags. Am I missing something or it is how it's supposed to be? My product view in views.py def add_product(request): pharmacy = Pharmacy.objects.get(id=1) form = ProductForm(initial={'pharmacy':pharmacy}) if request.method=='POST': … -
ckeditor django no error but don't show editor
I trial make editor for my blog django when used django_summernote work good but when ckeditor django no error but don't show editor so how fix it forms.py when used SummernoteInplaceWidget show but when used CKEditorWidget don't show and textarea input hiden from django_summernote.widgets import SummernoteWidget, SummernoteInplaceWidget from ckeditor.widgets import CKEditorWidget class NewTopicForm(forms.ModelForm): # content = forms.CharField(widget=SummernoteInplaceWidget()) content = forms.CharField(widget=CKEditorWidget()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['author'].widget.attrs.update( {'class': 'd-none'}) self.fields['author'].label = '' self.fields['author'].required = False self.fields['slug'].required = False class Meta: model = Topic fields = ('title','image', 'author', 'content','NotfFaV','slug') widgets = { 'title': forms.Textarea(attrs={'class': 'ml-3 mb-3 form-control border-0 read-more rounded-0', 'rows': '1', 'placeholder': 'اضف تعلق'}), } urls.py path('ckeditor/', include('ckeditor_uploader.urls')), views.py def home(request): topic_form = NewTopicForm() return render(request, 'forum/home.html', { 'topic_form': topic_form }) home.html {{topic_form.media}} {{topic_form.content}} -
Throttle in Django Rest Framweork if user is None during Oauth2 request with CLient Credentials
I am using Django Rest Framework with Django OAuth Toolkit for allowing external organization to request endpoints. I am using Crendentials Client grant type to ask access token.enter image description here When i try request my endpoint I have this error : 'NoneType' object has no attribute 'is_authenticated'. The exception is raised in the get_cached_key function of the AnonThrottleClass. In fact request.user is None with Client Credentials, so this function can not pass. Here is my viewset : class StudentViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet,): serializer_class = StudentSerializer authentication_classes = (OAuth2Authentication,) permission_classes = (TokenHasScope,) required_scopes = [ oauth2_settings.READ_SCOPE, oauth2_settings.WRITE_SCOPE, ] schema = is_schema_for_open_api_doc(True) queryset = Student.objects.all() Can you help me with this ? Thank you ! -
How do you turn a user into staff?
Using a view i want to turn a user into staff, how do i do it. using is_staff just gives me if the user is staff or not. def createAdmin(request,member_id): admin_group= Group.objects.get(name='admin') member = get_object_or_404(Member,pk=member_id) user = User.objects.get(member = member) admin_group.user_set.add(user) user.staff=True user.save() This is the code i use to make that user a admin but i don't know how i could give him staff status. user.staff doesn't work. -
Social Network Login Failure django allauth with discord
I am trying to integrate discord social account to my django project login.html: {% extends 'base.html' %} {%load crispy_forms_tags %} {% load socialaccount %} {% block content %} <div class='content-section card bg-dark p-4'> <form method='POST' autocomplete="off" > {% csrf_token %} <fieldset class='form-group'> <legend class='border-bottom mb-4'>Sign In</legend> {{ form | crispy }} </fieldset> <div class='form-group'> <button class='btn btn-outline-info' type='submit'>Login</button> </div> </form> <div class="border-top pt-3"> <p>Don't have an account? <a class='ml-2 btn btn-outline-info' href="{% url 'register' %}">Sign up</a></p> <a href={% url 'reset_password' %}>Forgot password?</a> </div> </div> <div class='login-buttons'> <div class='social-login'> <hr class="my-4"> <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><a href="{% provider_login_url "google" %}"><i class="fab fa-google mr-2"></i>Login with Google</a> </div> <div class='social-login'> <hr class="my-4"> <button class="btn btn-lg btn-discord btn-block text-uppercase" type="submit"><a href="{% provider_login_url "discord" %}"><i class="fab fa-discord mr-2"></i>Login with Discord</a> </div> {{ auth_error }} </div> {% endblock content %} I have added api key and secret key via the admin panel.. I already have set up google authentication and it works fine. What is the error and how to solve it? Pls inform if any other info is needed -
How to add a prefix before the domain name in a url in django?
I want to create custom url like this http://admin:testserver.com/login/ I've been trying different ways to to achieve this but all of my efforts were in vain. After reading Django document i'm able to create a custom url where i can add a certain prefix after the domain name which look like this "http://127.0.0.1:8000/mod:add_product/" with this line of code url(r'^mod:', include('moderator.urls')), My friend was suggesting to use django_subdomains to get a somewhat similar url which would look like this "http://admin.xyz.com/loign" i was considering that as an option but django_subdomains has been abandoned since July 2019 is there any other options to create such urls?