Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unexpected FieldError, "Cannot resolve keyword 'conducted_by' into field. Choices are:..." while getting a queryset in Django
I have this model: class CTScan(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) amount=models.DecimalField(max_digits=10, decimal_places=2, default=0) date=models.DateField(default=datetime.date.today) conducted_by=models.CharField(max_length=4, default=None) remarks=models.TextField(max_length=500, blank=True, default=None) ctscan_date=models.DateTimeField(auto_now_add=True) And I have turned the conducted_by field into a radioselect field in forms.py: class CTScanForm(ModelForm): PARTY_SELECT = ( ('k', 'KCC'), ('o', 'OOPL'), ) conducted_by=forms.CharField(widget=forms.RadioSelect(choices=PARTY_SELECT, attrs={'class': 'form-check-inline'})) class Meta: model=CTScan fields='__all__' labels={ 'conducted_by':'Conducted By', } widgets={ 'date': DateInput(attrs={'type': 'date'}), } When I make a query in views.py like: ct_kcc=IpdReport.objects.filter(ctscan__date__range=(prev1, prev2), conducted_by='k') It throws a FieldError: Cannot resolve keyword 'conducted_by' into field. Choices are: approvedpackage, approvedpackage_id, claimedpendingcases, ctscan, ctscan_id, discharge, discharge_id, id, lockdata, lockdata_id, ongoingreport, package, package_id, patient, patient_id, radiations, radiations_id, realization, realization_id, reclaimedrepudiation, repudiatedclaims, unclaimedpendingcases What is wrong with my code? -
Typerror: object is not subscriptable Django test
I have some problems with my tests in Django. The ide is that I create questions for my learning platform, and I want to verify that the questions are actually created. The problem is that (from what I understand) I try to put a list, objects that in a list cannot fit. Do you have any ideas how I can correct this? Thank you very much! Error: response.context['latest_question_list'], TypeError: 'NoneType' object is not subscriptable The test: def test_two_types_questions(self): """ The questions index page may display multiple questions. """ lab1 = Lab.objects.create(lab_name="test lab past question", pub_date=datetime.now(), lab_theory="test lab past question") question1 = QuestionMultipleChoice.objects.create(lab=lab1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') question2 = QuestionFillText(lab=lab1, text1='1', text2='2', answer='1') response = self.client.get(reverse('labs:index')) print(response) self.assertQuerysetEqual( response.context['latest_question_list'], [question1, question2], ) -
Understand `_html_output()` from Django Forms Source Code
Below source code is from django/forms/forms.py class BaseForm(RenderableFormMixin): def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Output HTML. Used by as_table(), as_ul(), as_p()." How is this private method _html_output() used / invoked by as_table(), as_ul(), as_p() please ? I did not find out from the source code. -
MultiValueDictKeyError while trying to add image to my blog post
I am trying to add image to my blog post but when i added this to my code image = request.Post['image'] And i keep getting errors. -
Django: Unable to save the model instance
I have models defined like the below: class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) owner = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class DeviceReadings(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) reading = models.FloatField() timestamp = models.DateTimeField() And I am trying to save models like below: device = Device.objects.get(pk=device_id) r = DeviceReadings(device_id=device, reading=reading, timestamp=timestamp) r.save() It gives an error that Invalid UUID format. It works if I set device.pk. I am not so well-versed in Django, unable to understand why the instance is not being saved. -
How can I make a model method editable through a dependent field in django admin list display
The scenario: I have a model like this from django.db import models from django.contrib import admin class Appointment(models.Model): time = models.DateTimeField(blank=True, null=True) topic = models.CharField( max_length=255, null=True, help_text="Topic to be discussed at the meeting" ) medium = models.URLField(blank=True, null=True, help_text="Meet link") def __str__(self): return f"{self.date_and_time}" @property @admin.display( ordering="time", description="Date and time of the appointment", ) def date_and_time(self): return self.time.strftime("%b %d, %I:%M %p") With an admin model from django.contrib import admin from .models import Appointment @admin.register(Appointment) class AppointmentAdmin(admin.ModelAdmin): date_hierachy = "time" list_display = ( "date_and_time", "medium", ) list_editable = ( "date_and_time", "medium", ) As shown in the code, I want to use a derived model method (date_and_time) in the Django list display, while making it editable through its dependent field "time". Of course, as expected, the above code throws an error because I included "date_and_time", which is the derived model method and not a field, in the list_editable tuple, I cannot add "time" as it doesn't exist in the list_display at all, instead it is represented as the date_and_time method which only formats the time field btw. My question: Is there a way to have the formatted DateTime (which is what the date_and_time does) displayed in the list table, allowing editing … -
Django OAuth2 Toolkit
I am using django oauth2 toolkit. Can anyone please help me in understanding? I am able to Signup the user based on the extended AbstractUser model. Based on Signup details, I'm able to authenticate the user by entering username, password, client_id, client_secret & grant_type. After entering login credentials, id & secret in these (127.0.0.1:8000/o/token/), I'm able to get the access & refresh token When getting the access_token, How can I pass the user details along with access_token. Can anyone please help me in sorting out these. I'm using Postman. Serializers.py from rest_framework import serializers from django.contrib.auth import authenticate from rest_framework.response import Response from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_staff': {'write_only':True}, 'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py from django.shortcuts import render from rest_framework import generics, permissions, serializers, viewsets from rest_framework.response import Response from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from users.serializers import UserSerializer from users.models import User # Create your views here. class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() Urls.py from django.urls import path, include from rest_framework import routers from rest_framework.routers import DefaultRouter from users.views import UserAPI from users import views router = DefaultRouter() router.register('users', views.UserAPI, … -
"unique = True" - Django models - Unique for each user not unique for all data submitted by everyone
I have a models in Django currently and I have made a field "unique=True" so that no duplicates are submitted to the database. My problem is that it extends to all users. By this I mean that User 1 should be able to submit "Example1" and "Example2" and should never be able to submit "Example1" or "Example2" again and then User2 should come along and also be able to submit "Example1" and "Example2" but they cant because User 1 already submitted it. It there a way where I can get somewhat of a "unique=True" but separately for each user and not just conjoined like it is now. Thanks in advance. Code Below. The problem resides in "type = " and my users are being defined by ForeignKey also. class Field_Repo1(models.Model): user = models.ForeignKey(User, default=True, related_name="Field_Repo1", on_delete=models.PROTECT) title = models.CharField(max_length=20, verbose_name='Title of Field') type = models.CharField(max_length=200, blank=True, unique=True, null=True, verbose_name='Field') class Meta: ordering = ['-type'] def __str__(self): return str(self.user) or 'NONE' def get_absolute_url(self): return reverse('repo1') -
Useful design patterns for creating a neat Python Web App
We decided to refactor our code as almost every new feature was implemented as a form of a hack. Would to get some tips on what design patterns would be useful to have in a web app. Things like Factory or Facade don't suit, I feel those are more suited for libraries and not a web app. The gist of the web app is that it is a sort of translator that understands a user's queries and creates large queries to our DBs. It's a sort of search service. We have a ton of features and configuration that keep stepping on each other's functionalities and we have to add ugly hacks to overcome them. Hoping to have a good base that lets creating long complex chain of rules easier to modify. -
DJANGO how to REMOVE url parameters?
What would be the best way to remove parameters from url in django? For instance when facebook adds fbclid? I am trying to do a redirect directly in urlpatterns but the parameters keep getting passed through. For some reason I assumed this would be some simple command like 'allow_parameters=False' or something. -
how i solve django 3.x admin autocomplete error
I have tried python manage.py collectstatic but no effect.It seems to be the problem about app_label from error message. this is the Traceback: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/utils/datastructures.py", line 76, in getitem list_ = super().getitem(key) KeyError: 'app_label' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 61, in process_request app_label = request.GET['app_label'] File "/usr/local/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'app_label' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 250, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 232, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 417, in autocomplete_view return AutocompleteJsonView.as_view(admin_site=self)(request) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 20, in get self.term, self.model_admin, self.source_field, to_field_name = self.process_request(request) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/views/autocomplete.py", line 65, in process_request raise PermissionDenied from e … -
Free way to send SMS using Django
hope you are doing well. I need help im Django. I need to send messages for free without using an API or email server. What I had tried: I use multiple API such as Twillio etc. But it is quite an expensive solution. I use an SMTP server to send messages Via Email. But in our area no SMS service provider is available. If you have any free or cheap solution to the above problem, so please state it there while mentioning me. I will do consider it. Thanks -
access to pk in a template form
I want to display all elements of a form including the pk and I have not found a satisfying method to do so: class SomeForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField(required = True) self.fields["id"] = forms.IntegerField(disabled = True) self.fields["data"] = forms.CharField(required = False) class Meta: model = SomeModel fields = ["id", "number", "data"] So now I just call the form in the view with: class SomeView(TemplateView): template_name = "app/sometemplate.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) obj = MODEL.objects.get(pk = context["pk"]) MODEL_data = {} MODEL_data["number"] = obj.number MODEL_data["id"] = obj.pk MODEL_data["data"] = obj.data context["form"] = SomeForm(initial = MODEL_data) return context and now in the templatetags I have a filter get_pk: @register.filter(name='get_pk') def get_pk(obj): return obj.initial["id"] and I get the pk in the template with {{ form|get_pk }} and I feel like this is not smart. I tried stuff like {{ form.instance.id }} like suggested here. I still feel there must be an easy way to achieve this? -
Django REST API doesn't output JSON but <Response status_code=200, "text/html; charset=utf-8">
I am using Django REST framework for a ML model and I input JSON data and I want to get output JSON results as response_dict. But when I print(Response(response_dict, status=200)), it prints <Response status_code=200, "text/html; charset=utf-8"> instead of whatever JSON results that my model predicts. BUT on the local Django server page, I can see my JSON output. How can I can output response_dict instead of this text/html? views.py class FraudDetection(APIView): def post(self, request): data = request.data df = pd.json_normalize(data) # some preprocessing fds_model = ApiConfig.model ypred = fds_model.predict_proba(df) response_dict = {"Fraud score: {:.3f}, Normal Transaction, Processing request".format(ypred[i][1]*100)} print(Response(response_dict, status=200)) return Response(response_dict, status=200) -
Django Rest Framework is throwing 400 before I can handle exception for ModelViewSet
I have a user model in my app with a unique field on email. However, I need to catch when a user is trying to do a duplicate request so I can do some processing in a different way. I am making a POST call to create this user. DRF of course throws a 400 with an existing email message. But even when I create a validate_email method in my model or try to catch it with a custom exception it doesn't catch. I created a custom ValidationError cause the general ValidationError didn't seem to have a way to filter it out specifically besides a generic code, unique, or matching the message string. How can I catch this specific validation in Django Rest Framework? Error Message: { "email": [ "user with this email address already exists." ], "status_code": 400 } User model: class User(AbstractBaseUser, PermissionsMixin): """ User Model """ USERNAME_FIELD = "email" REQUIRED_FIELDS = [] email = models.EmailField(_("email address"), unique=True) name = models.CharField(_("name"), max_length=30, blank=True) def validate_email(self): email = self.email valid_email = email is not None and email.endswith(self.email_domain) if not valid_email: raise ValidationError( _("Email is not valid"), code="invalid.email", ) if Users.objects.filter(email=email).exists(): import ipdb; ipdb.sset_trace() #does not get called raise EmailExists() … -
How i can to convert instance to dict with model method and relationship?
How i can to convert instance to dict with model method and relationship? class Customer(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50,,null=True,blank=True) birthdate = models.DateField(max_length=100,null=True,blank=True) status = models.ForeignKey('status ',on_delete=models.CASCADE) something = models.ManyToManyField('Something',blank=True) def get_age(self): diff = relativedelta(datetime.date.today(),self.birthdate ) return diff i want to convent to below { uuid : "value", name : "value", birthdate = "value", status = { status_id : "value" status_text : "value" }, something : [{ something_id : "value", something_value : "value" },{ something_id : "value", something_value : "value" }], get_age : "value" } thank for every expert -
Django relationship failing on IntegrityError even though the connected object was already created
So I'm running the following code: def decorate(func): method_inst = Method.objects.create(name=func.__qualname__, class_m_id=cls_id) @wraps(func) def wrapper(*args, **kwargs): for arg in args: arg_inst = Argument() arg_inst.method_id = method_inst.id arg_inst.save() return func(*args, **kwargs) return wrapper return decorate and I'm getting the following error: django.db.utils.IntegrityError: The row in table 'main_argument' with primary key '1' has an invalid foreign key: main_argument.method_id contains a value '11' that does not have a corresponding value in main_method.id. It seems like Django is not finding the Method instance that I have created before. Even though it is obviously created because the method_inst.id would not exist otherwise (it is generated automatically only after the object was created). Also, we know it is populated, because the error message is clearly saying main_argument.method_id contains a value '11'. Also, looking at the database I can see it was created. Any ideas why this is happening? -
Django - reverse_lazy & multiple parameters
I stuck in the redirect url after adding a new object. I have a simple class bassed create method and form. urls.py: path('', views.home, name='home'), path('<int:branch_id>/<int:doc_type_id>/', views.documents, name='documents'), path('<int:branch_id>/<int:doc_type_id>/add', testForm.as_view(), name='document_add'), path('<int:branch_id>/<int:doc_type_id>/<int:pk>', detailsView.as_view(), name='details_view'), form.py: class TestDocumentForm(ModelForm): class Meta: model = Document fields = '__all__' views.py: class testForm(FormView): template_name = "template/add.html" form_class = TestDocumentForm success_url = reverse_lazy('app:home') And this works perfectly. But I don,t know how to change a success_url based on reverse_lazy and arguments in the class-based function. I need this to redirect to the details page after clicking the save button. In the HTML code, I know how to do this. I tried using this solution (i.a. https://stackoverflow.com/a/41905219), so in the testForm function I commented the sussec_url field, I added something like this (): def get_success_url(self, **kwargs): reverse_lazy('archive:details_view') params = urlencode({'branch_id': self.object.branch.id, ...}) ... And I got the error: 'testForm' object has no attribute 'object'. I tried many solutions but I can't redirect the page with multiple. Thanks for any advice! -
How can I solve this error, since I want to migrate the models.py to be able to continue but that stuck there
(info) C:\Users\adruz\OneDrive\Escritorio\nuevo blog\proyecto\nuevo_blog>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django\apps\config.py", line 243, in create app_module = import_module(app_name) File "C:\Users\adruz\AppData\Local\Programs\Python\Python39\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\proyecto\nuevo_blog\manage.py", line 22, in main() File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\proyecto\nuevo_blog\manage.py", line 18, in enter code heremain execute_from_command_line(sys.argv) File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django\core\management_init_.py", line 401, in execute django.setup()enter code here File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\adruz\OneDrive\Escritorio\nuevo blog\entorno\info\lib\site-packages\django\apps\config.py", line 245, in create raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'base'. Check that 'aplicaciones.base.apps.BaseConfig.name' is correct. -
Django REST framework generic views vs custom function based views
I am wanting to refactor views.py in my Django project. Currently it is all function based views with different backend logic for each api endpoint. Most of the logic deals with taking in some input, running queries, and then manipulating the data before sending back to the front end. Wondering how to standardize this as I would like to have better structure. Also wondering how useful these views are? Can't see using it all that much and if I want a list I can just query the database accordingly and do whatever I want with it inside one of my function based views (e.g. merge with other data or filter). Also wondering how necessary serializers are? Before understanding what their full function was I found alternatives and have been able to send data back and forth to the front end just fine (mainly using things like values_list() or values() at the end of a query and creating dictionaries to send to the front end). Using React for the front end and connecting with Axios. -
What is the difference between django channels Asynchronous and Synchronous consumer
I was trying the django channels official tutorial. I completed upto Synchronous consumers and I found that its working fine. I have also tried in incognito. Here is a demo of the code: . In the documentation it's said: This is a synchronous WebSocket consumer that accepts all connections, receives messages ... For now it does not broadcast messages to other clients in the same room. But when I send message, it is shown in other windows . I have a few more questions : Why is it necessary to have async consumer / or what's the point? How it helps Does is decrease server performance When should I use it and when not Am I missing anything? Apologies for any mistake. Thanks for any kind of help. Merry Christmas :) -
TypeError: __init__() got an unexpected keyword argument 'providing_args'
I am creating a Django website. I was recently adding permissions/search functionality using the allauth package. When I attempt to run the website through docker I receive the error message: File "/usr/local/lib/python3.9/site-packages/allauth/account/signals.py", line 5, in user_logged_in = Signal(providing_args=["request", "user"]) TypeError: init() got an unexpected keyword argument 'providing_args' What is causing this error? I know usually a type error is caused by incorrect models.py files but I can't seem to access this file since it is a part of an external package. Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/', include('accounts.urls')), path('', include('climate.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns Models.py class Country(models.Model): id = models.UUIDField( primary_key= True, db_index = True, default=uuid.uuid4, editable= False ) name = models.CharField(max_length=50) population = models.IntegerField(default=1) emissions = models.FloatField(default=1) reason = models.CharField(default="", max_length=100) flags = models.ImageField(upload_to='images/', default="") page = models.URLField(max_length=300, default="") def save(self, *args, **kwargs): super(Country, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'countries' indexes = [ models.Index(fields=['id'], name='id_index') ] permissions = { ("special_status", "Can read all countries") } def __str__(self): return self.name def flag(self): return u'<img src="%s" />' % (self.flags.url) def get_absolute_url(self): return reverse('country_detail', args =[str(self.id)]) flag.short_description = 'Flag' My settings.py that handles allauth. AUTH_USER_MODEL = … -
Django-Entangled multiple data in JsonField
Working with django JsonField. Using django-entangled in form. I need data format like below. Need suggestion to avail this. [ { "name": "Test 1", "roll": 1, "section": "A" }, { "name": "Test 2", "roll": 2, "section": "A" } ] -
How to loop trough objects in html
i wana loop trough my cateogrys in my html, im makeing a filter that will show all of the cateogys but i cant get my {% for %} to work i need some help heres my code. Ask if theres any more info that you need to solve this. HTML: <div class="filter-box"> <h1>Filter</h1><hr> {% for category in categorys%} <p class="checkbox-text">Hello</p> <h1>AAAAAAAAAAAAAAA</h1> {% endfor %} </div> Views: def category_all(request): categorys = Category.objects.all() return render(request, "product/dashboard_test.html", {"names": categorys}) Models: class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
How is it possible to clean the html code rendered with django-crispy form?
I have a django app and when i see the source html code on the browser it looks like this: it is ugly and not clean... and when using django-crispy forms, the generated form is worse.. I would like to show it like this: How is it possible to clean the html code rendered with django-crispy form?