Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework Field name `ia_superuser` is not valid for model `CustomUser`
I got stock with writing custom user in Django an rest framework.I've written custom user and custom serializer, I've added every necessaries in settings.py. When I try to go to user app I get this error: ImproperlyConfigured at /api/user/ Field name ia_superuser is not valid for model CustomUser. Request Method: GET Request URL: http://127.0.0.1:8000/api/user/ Django Version: 3.0.8 Exception Type: ImproperlyConfigured Exception Value: Field name ia_superuser is not valid for model CustomUser. Exception Location: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\lib\site-packages\rest_framework\serializers.py in build_unknown_field, line 1340 Python Executable: C:\Users\Aireza.virtualenvs\lcodev-lF6rFvWb\Scripts\python.exe Python Version: 3.10.2 Python Path: ['F:\Python\lcodev\ecom', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\Aireza\AppData\Local\Programs\Python\Python310', 'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb', 'C:\Users\Aireza\.virtualenvs\lcodev-lF6rFvWb\lib\site-packages'] Server time: Tue, 22 Mar 2022 11:34:45 +0000 I have an api app in the project and the user app is in the api app. anyone can help? thanks here's everything: user serializer.py: from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password from rest_framework.decorators import authentication_classes,permission_classes class UserSerializer(serializers.HyperlinkedModelSerializer): def create(self,validated_data): password = validated_data.pop('password',None) # pop method removes the given index from the list and returns it instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def update(self,instance , validated_data): for attr,value in validated_data.item(): if attr == 'password': instance.set_password(value) else: setattr(instance,attr,value) instance.save() return instance class Meta: model = CustomUser extra_kwargs = {'password':{'write_only':True}} … -
How to fix this django+bootstrap carousel bug
After first scroll carousel stops working and return error, but i don't understand it my html: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <div class="carousel-indicators"> {% for photo in product.photo_set.all %} {% with forloop.counter0 as i %} <button type="button" data-target="#carouselExampleIndicators" data-slide-to="{{i}}"{% if i is 0 %}class="active" aria-current="true"{% endif %}></button> {% endwith %} {% endfor %} </div> <div class="carousel-inner"> {% for photo in product.photo_set.all %} {% with forloop.counter0 as i %} <div class="carousel-item {% if i is 0 %}active{% endif %}"> <img class="d-block w-100 image-source rounded" src={{photo.image.url}} style='height: 30rem;'> </div> {% endwith %} {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> and error in chrome: Uncaught TypeError: Cannot read properties of null (reading 'classList') at at._setActiveIndicatorElement (carousel.js:364:23) at at._slide (carousel.js:435:10) at at.prev (carousel.js:154:10) at Function.carouselInterface (carousel.js:526:12) at HTMLButtonElement.dataApiClickHandler (carousel.js:556:14) at HTMLDocument.s (event-handler.js:119:21) yeah (sorry), at the computer I'm a monkey with a grenade -
Django Kubernetes yaml error mapping values are not allowed in this context
Im currently trying to run helm upgrade --install --dry-run --debug django-test ./helm/django-website but when i do im met with this error line and i cant seem to fix the issue with anything i try Error: UPGRADE FAILED: YAML parse error on django-website/templates/deployment.yaml: error converting YAML to JSON: yaml: line 38: mapping values are not allowed in this context helm.go:84: [debug] error converting YAML to JSON: yaml: line 38: mapping values are not allowed in this context YAML parse error on django-website/templates/deployment.yaml helm.sh/helm/v3/pkg/releaseutil.(*manifestFile).sort helm.sh/helm/v3/pkg/releaseutil/manifest_sorter.go:146 helm.sh/helm/v3/pkg/releaseutil.SortManifests helm.sh/helm/v3/pkg/releaseutil/manifest_sorter.go:106 helm.sh/helm/v3/pkg/action.(*Configuration).renderResources helm.sh/helm/v3/pkg/action/action.go:165 helm.sh/helm/v3/pkg/action.(*Upgrade).prepareUpgrade helm.sh/helm/v3/pkg/action/upgrade.go:234 helm.sh/helm/v3/pkg/action.(*Upgrade).RunWithContext helm.sh/helm/v3/pkg/action/upgrade.go:143 main.newUpgradeCmd.func2 helm.sh/helm/v3/cmd/helm/upgrade.go:197 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.3.0/command.go:856 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.3.0/command.go:974 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.3.0/command.go:902 main.main helm.sh/helm/v3/cmd/helm/helm.go:83 runtime.main runtime/proc.go:255 runtime.goexit runtime/asm_arm64.s:1133 UPGRADE FAILED main.newUpgradeCmd.func2 helm.sh/helm/v3/cmd/helm/upgrade.go:199 github.com/spf13/cobra.(*Command).execute github.com/spf13/cobra@v1.3.0/command.go:856 github.com/spf13/cobra.(*Command).ExecuteC github.com/spf13/cobra@v1.3.0/command.go:974 github.com/spf13/cobra.(*Command).Execute github.com/spf13/cobra@v1.3.0/command.go:902 main.main helm.sh/helm/v3/cmd/helm/helm.go:83 runtime.main runtime/proc.go:255 runtime.goexit runtime/asm_arm64.s:1133 line 38 is the include line under env:, ive read up on yaml indentations, tried yaml scanners, i cant seem to fix it and when i do it causes something else to break but the code im using is generated from kubernetes so i dont understand why it wont work does anyone know how to fix it -
Python equivalent of `binding.pry`
What is the Python and Django equivalent of the Pry Gem, binding.pry. What library can I use to easily debug? In ROR I can put binding.pry in any code and it will stop the execution on that line and give me a chance to debug. -
Include Django variable into a JQuery Code
I have a JQuery code using a pagination plugin, Here is the code : $('#demo').pagination({ dataSource: [1, 2, 3, 4, 5, 6, 7, ... , 195], callback: function(data, pagination) { // template method of yourself var html = template(data); dataContainer.html(html); } }) But here I want to make the dataSource of a list of customers that is stocked in my database -
Django : Structure of the API withe redirect functions or decorators
I am a Newbee on Django and I am not sure of the structure of my API. There is a sidebar with a list of apps. I have one that is to upload files. I want that when the user click on the upload files app it appears a page with a dropdown list to choose a client. Then when it selects a client, it redirects to the upload page with the value of the client selected because this value has to be stored in the database when a file is upload and show in the templates too. When the user wants to change of client, he has to return to the previous page and change the selected client How should I do that ? What is the most efficient and logic in terms of views and decorators ? Here is what I did. I think that it is not efficient.The user clicks on the upload url, it brings to the upload view where the id_client selected is initialize to None. So it redirects to the selectclient view where the user selects the client and brings back to the upload view def upload(request, idclient = None): if idclient == None … -
Filling a complex object from database in Django
I am trying to figure out how I can create a complex object in Django, using data retrieved from different, joined tables in a database, without having to do a series of explicit queries and then manually putting it all together. Lets say I have three tables that look like this **parent** - id - name **attribute** - id - parent_id *(ForeignKey)* - name - value **modifier** - attribute_id *(ForeignKey)* - value - duration So, every parent has an arbitrary number of attributes, and each attribute can have an arbitrary number of modifiers, each identified with ForeignKeys in their respective models. From entries in these tables, I would like to build a Python object that has the following structure **object** - id - name - attributes {} - name : (value, modifiers[(value, duration), (value, duration), …]) - name : (value, modifiers[(value, duration), (value, duration), …]) - … What is the best and most efficient approach to achieving something like this in Django? Is there even a way or will I have to run multiple queries and fill the object in discrete steps? -
Django Autocomplet Light select2 widget not working on ios
I have a project that uses DAL and I thought was all well and good till a friend told me the Select2 widget was broken. Turns out it does not work on any iOS(iphone, ipad) device in safari or chrome. It works on my Google pixel and macOS. Below is a picture of what it looks like on iOS. But basically eh problem is you cannot type into it. It just shows a blank list. Has anyone else run into this. Any idea of where to start would be great. I looked at the css for the select2 in DAL but could not see anything that would be device specific. I am using bootstrap as well and in my search ran into something where select2 did not play well with bootstrap and will try and do some testing of that tonight. Any direction would be appreciated. -
How to make existing columns empty in Django
I want to make existing columns empty and in the future the coulumn can not be filled. application = models.CharField(default="noname", max_length=100, null=False) Make existing columns empty and in the future the coulumn can not be filled with any values. -
How to filter QuerySet depending on fields of a reverse foreign key related model?
I have two following models: class Tour(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=3000, blank=True # some other fields here and class TourDatesInfo(models.Model): departure_date = models.DateTimeField() return_date = models.DateTimeField() tour = models.ForeignKey(Tour, on_delete=models.CASCADE, related_name='dates') Tour model has a one-to-many relationship with a TourDatesInfo, so that one tour may have multiple different sets of departure/return dates. What I try to achieve is to be able to filter the tours QuerySet depending on their set of TourDatesInfo, preciesely on whether each tour contains departure/return pair that satisfies specific conditions, e.g., get all tours that have at least one TourDatesInfo with departure_date > 2022-04-12 and return_date < 2022-05-01. I can write an SQL query to perform this, something like SELECT * FROM tours_tour tours WHERE tours.id IN (SELECT DISTINCT tour_id FROM tours_tourdatesinfo WHERE departure_date > '2022-04-12' AND return_date < '2022-05-01');, but how it can be done using django ORM without raw queries? -
Django with Javascript form not returning to View
I am trying to learn Javascript by developing an interactive form in Django. The form presents a Select list that allows multiple selections. As one or more tests in the list are selected the Javascript updates a list on the page with the current selections. When I press Submit, I expect to return to the View but instead I get a 405 Error and am not directed to the success URL. I added a Print statement to the form_valid method in the View and it never executes. Not sure how to get where I want to go. views.py class OrderTestsViewForJS(ListView): model = Universal_Test_File context_object_name = "testlist" success_url = '/list-patient/' template_name = "lab/order_tests_js.html" def get_context_data(self, *args, **kwargs): patient = get_object_or_404(Patient, pk=self.kwargs['pk']) context = super(OrderTestsViewForJS, self).get_context_data(**kwargs) context['patient'] = patient return context def form_valid(self, form): print("in form valid") return super().form_valid(form) stripped down template.html {% extends 'base.html' %} {% block title %}Order Tests{% endblock title %} {%load static%} {% block content %} <div class="card mt-5 "> <div class="card-header text-center"> NovaDev Order Tests Module </div> <div class="card-body"> <div class="row"> <div class="col-3 m-5"> <form action="" method="post"> {% csrf_token %} <select id="select_tests" name="select_tests" multiple > {% for test in testlist %} <option value = "{{test.service_id}}" > {{test.test_name}}</option> … -
Updating code on via GitHub Digital Ocean
New to Django, Python, and working with digital ocean. I have a Django app on digital ocean https://chicagocreativesnetwork.com/ which was uploaded via GitHub (with the help of a friend) I need to make some changes to the CSS and HTML for this app, which I am doing locally and pushing to my gitHub repository https://github.com/ktduffyincorperated/chicagocreativesnetwork. How do I get the pushed gitHub updates into my Digital Ocean app? thank you! -
How to show the flags in the options for internationalization?
I'm using the i18n to translate, only when I want to put the flags, it doesn't show them. Does anyone have an idea how to show the flags that I have in my images folder? By the way, I'm using spanish and english to translate. {% get_current_language as LANGUAGE_CODE %} <h1>{{LANGUAGE_CODE}}</h1> <h1>{{title}}</h1> <div class="d-flex flex-row"> <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to }}"> <div class="input-field p-2"> <select name="language" id="" class="form-control"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} {{language.code}} <img class="rounded-circle header-profile-user" src="{%static 'assets/images/flags/us.jpg' %}"> </option> {% endfor %} </select> </div> <input type="submit" value="Go" class="p-2"> </form> </div> -
how to delete int object in django
After filtering and updating I have to delete the objscts, How to solve the isuue, AttributeError: 'int' object has no attribute 'delete' def handle(self, *args, **options): trees.objects.filter(old=True).update(new=False).delete() My objective is to first filte all the old trees as True and new as False then updating I have to delete all the object list. -
Django initialize table with post_migrate not working
I want to initialize the database table with some predefined instances. # apps.py from django.apps import AppConfig from django.db.models.signals import post_migrate def initialize(sender, **kwargs): from .models import Address Address.objects.create( # address fields ) print('Created') class BackendConfig(AppConfig): name = 'backend' def ready(self): print('Ready') post_migrate.connect(initialize, sender=self) However nothing was created and nothing was printed after migration like the signal not triggered at all. -
Start scrapy by click button
I started project in django & scrapy. On the homepage I want to user can input model of car (I add car details to link to select right listing for scraping) and click button and the extraction process start and load data to django db. Can you help me how can I do it, is it possible? How make this button? Thanks -
Page 404 not found, current path did not match any of these
PAGE not found (404) Request method: GET Request URL: http://127.0.0.1:8000/action_page.php?steam_uid=12345678912345678&email=example%40gmail.com&username=johndoe&password1=123456&password2=123456 Using the URLconf defined in ReadyUp.urls, Django tried these URL patterns, in this order: [name='home'] account/ game/ group/ login [name = 'login'] logout [name = 'logout'] register/ [name ='register'] admin/ The current path, action_page.php, didn’t match any of these. I'm not exactly sure which url is creating the problem and would like some help. Here's a look at the url: from django.contrib import admin from django.urls import include, path from account.views import( register_view, login_view, logout_view, ) from group.views import ( home_screen_view ) urlpatterns = [ # Te4m Paths path('', home_screen_view, name='home'), path('account/', include('account.urls')), path('game/', include('games.urls')), path('group/', include('group.urls')), path('login/', login_view, name="login"), path('logout/', logout_view, name="logout"), path('register/', register_view, name="register"), # Default paths path('admin/', admin.site.urls), ] -
Django application doesn't seem to recognize related name?
I have a django app with a User's model that contains a followers field that serves the purpose of containing who follows the user and by using related_name we can get who the User follows. Vice versa type of thing. Printing the User's followers works, but I can't seem to get the followees to work. views.py followers = User.objects.get(username='bellfrank2').followers.all() following = User.objects.get(username='bellfrank2').followees.all() print(followers) print(following) models.py class User(AbstractUser): followers = models.ManyToManyField('self', blank=True, related_name="followees") Error: AttributeError: 'User' object has no attribute 'followees' -
Import statement openpyxy is not working on pycharm
i am very new to this language. trying to import openpyxl into pycharm, but it displays error messages that says "No module named 'openpyxl', when i checked through command prompt it says the file is installed, but i can't find it in the libraries -
term 'celery' is not recognized as an external function or cmdlet
I'm using Celery in my django application and when i'm trying to start celery worker with command: 'celery -A <project_name> worker -l info --pool=solo' it shows me an error that module 'celery' is not recognized, despite i've installed all necessary packages... >: celery worker --app=demo_app.core --pool=solo --loglevel=INFO : The term 'celery' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 celery worker --app=demo_app.core --pool=solo --loglevel=INFO ~ CategoryInfo : ObjectNotFound: (celery:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException I've also tried to add celery's path to PATH variable, but it throws this error anyway. -
I have installed django-user-accounts but the templates dont seem to exist
from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) urlpatterns = [ path('admin/', admin.site.urls), path("signup/", SignupView.as_view(), name="account_signup"), path("login/", LoginView.as_view(), name="account_login"), path("logout/", LogoutView.as_view(), name="account_logout"), path("confirm_email/<str:key>/", ConfirmEmailView.as_view(), name="account_confirm_email"), path("password/", ChangePasswordView.as_view(), name="account_password"), path("password/reset/", PasswordResetView.as_view(), name="account_password_reset"), path("password/reset/<str:uidb36>/<str:token>/", PasswordResetTokenView.as_view(), name="account_password_reset_token"), path("settings/", SettingsView.as_view(), name="account_settings"), path("delete/", DeleteView.as_view(), name="account_delete"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ -
How i can use "database_sync_to_async" function for fetching multiple object
I am implementing a consumer, and y want get all productos for example: class TeamConsumer(AsyncConsumer): async def get_all_producs(): products = await database_sync_to_async(Products.objects.all)() When i try fetch all products from the above code causes the error "You cannot call this from an async context - use a thread or sync_to_async." I know that query ar lazy, but, how i can get all products? -
How does discord manages roles and permissions in database?
Users can have multiple roles, roles have multiple permissions, and roles are protected by servers. I was wondering do they use relational db for that? Is django capable of doing such thing? Because to fetch each user for server with role will be very expensive. Does discord uses django for this or any other framework? Any thoughts please? I am trying to build a similar schema but I think it will be very expensive for the db transactions and queries. I have workspace, workspace have users, users have multiple roles, roles have multiple permissions(groups in djangos). And I think this will be very expensive to call a single user to check whether he belongs to this group or not. -
How do I translate the radio selection buttons?
I can change the language of all the other forms, the problem is that I don't know how to change the language through forms.py, because it wouldn't be the same as in the template, right? html <div class="mb-3"> <label class="form-label d-block mb-3">{% trans "Country" %}:</label> <div class="custom-radio form-check form-check-inline"> {{ form.pais }} </div> </div> forms.py PAIS = ( ('United States', 'United States'), ('Canada', 'Canada'), ('Other', 'Other'), ) class ClientesForm(forms.ModelForm): pais = forms.ChoiceField( choices=PAIS, widget=forms.RadioSelect(attrs={'class':'custom-radio-list'}), ) -
What is equivalent to TestCase.client in normal script
For example with TestCase I can check login post and so on with self.client class TestMyProj(TestCase): response = self.client.login(username="user@example.com", password="qwpo1209") response = self.client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) However now I want to use this in script not in test case. because this is very useful to make initial database. I want to do like this. def run(): response = client.login(username="user@example.com", password="qwpo1209") response = client.post('/cms/content/up', {'name': 'test', '_content_file': fp}, follow=True) What is equivalent to TestCase.client in normal script??