Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Altering the database with only one pytest-django session
I am using pytest-django 4.1 with Django 2.2 in my app. I have two databases for my tests: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'default_db', 'USER': '', 'PASSWORD': '' }, 'second': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'second_db', 'USER': '', 'PASSWORD': '' }, } During each test session these two databases are created: Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')... Creating test database for alias 'second' ('file:memorydb_default?mode=memory&cache=shared')... I don't want to use them all the time, only for a few tests. So I am looking for a way to enable creation of second database only for some sessions. Unfortunately I couldn't find a way to do this. Django documentation about tests recommends to use modify_settings or override_settings but it's not working for pytest-django. I tried to use django_db_setup fixture or pytest_sessionstart hook but I ended up with the situation where the db_router is correctly changed but the database is not, so the django configuration isn't really reset by editing settings.DATABASES after pytest is configured. I could make it work only for the whole configuration like: # project/conftest.py def pytest_configure(config): from django.conf import settings settings.DATABASE_ROUTERS = [] settings.DATABASES.pop('second', None) Is there a way to alter the django.conf.settings.DATABASES between the sessions in … -
Send post request using data from mapbox
How can I send data from marker on the map by POST request. I'm using Django and I want to get coordinates from marker which set by user. -
Is there a Ternary Operator in python
I'm trying to do a ternary like operator for python to check if my dictionary value exist then use it or else leave it blank, for example in the code below I want to get the value of creator and assignee, if the value doesn't exist I want it to be '' if theres a way to use ternary operator in python? Here's my code : in_progress_response = requests.request("GET", url, headers=headers, auth=auth).json() issue_list = [] for issue in in_progress_response['issues'] : # return HttpResponse( json.dumps( issue['fields']['creator']['displayName'] ) ) issue_list.append( { "id": issue['id'], "key": issue['key'], # DOESN'T WORK "creator": issue['fields']['creator']['displayName'] ? '', "is_creator_active": issue['fields']['creator']['active'] ? '', "assignee": issue['fields']['assignee']['displayName'] ? '', "is_assignee_active": issue['fields']['assignee']['active'] ? '', "updated": issue['fields']['updated'], } ) return issue_list -
django: Dynamically and securely change form value from template for loop for form saving to database
So I have a database of "stuff" that is essentially static and not editable by users, this is a repo of things that users are allowed to save. However, users can save copies of this stuff to a separate "user_stuff" database as the user unique stuff will have data that is unique to each user. class public_stuff(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(blank=True) def __str__(self): return self.name class user_stuff(models.Model): name = models.CharField(max_length=100) stuff = models.ForeignKey(public_stuff, on_delete=models.DO_NOTHING) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.name On my actual page I am rendering a list of all public stuff (for now, I only have two things in public_stuff at the moment for test purposes), as well as a list of all of a users stuff. For each public stuff entry, I would ideally like to have a button that the user can click to "save" a copy of that entry to their stuff, but the problem is I am not sure how to do this securely. The main roadblack is that I would ideally like to display each entry via a foor loop, as the list will be dynamic in both size and composition. As a result, I … -
format count integar into percentage inside annotate in Djnago rest
I have to send the percentage of counts in the api call in DRF. I have calculated the counts and attach to the queryset using annotate. But actaully I need the percentage rather than the count. TYPES = ((1,'cold'), (2,'humid'), (3,'hot')) from django.db.models import Q,Count class Destinations(models.Model): continent = models.CharField() /............/ class Packages(models.Model): location = models.Foreignkey(Destination,on_delete=models.CASCADE,related_name='packages') place_type = models.CharField( max_length=1, choices=TYPES, default="" My view: I have use list function inside modelviewset, something like this: Destiantion = Destination.objects.all().annotate(total_packages=Count('packages'), cold_count=Count('packages',filter=Q(packages__place_type=1)), humid_count=Count('packages',filter=Q(packages__place_type=2)), hot_count =Count('packages',filter=Q(packages__place_type=3))) Here I get the response as counts of package types in the attributes, but I want is the percentage of package type like 25% by doing cold_count*100/total_packages but cant use this inside annotate. There is a count() method which might be useful but if I used that I have to make 4 separate queries and might be writing another api just for that. So I have to use annotate. But how?? -
Django Admin Sortable 2 - Inline Tabular - not save order and display hidden field
I was using Python 3.9, Django 3.2.8, and Django-admin-sortable2 1.0.3. I was facing issue that my custom order field (I named it "sort_order") was visible in inline tabular forms but it should have been hidden as per Django-admin-sortable2 implementation. And although I was able to drag-and-drop items, but upon saving the parent object, the sort order wasn't getting saved. What worked for me? -
Why does Django's union mess up the column order?
If I have 2 models: class Hero(models.Model): hero_name = models.CharField(max_length=50) hero_age = models.PositiveSmallIntegerField() hero_identity = models.TextField(max_length=50) def __str__(self): return self.hero_name class Villain(models.Model): villain_name = models.CharField(max_length=50) villain_age = models.PositiveSmallIntegerField() villain_identity = models.TextField(max_length=50) def __str__(self): return self.villain_name and I create some test instances: Hero(hero_name="Superman", hero_age=30, hero_identity="Clark Kent").save() Hero(hero_name="Iron Man", hero_age=35, hero_identity="Tony Stark").save() Hero(hero_name="Spider-Man", hero_age=18, hero_identity="Peter Parker").save() Villain(villain_name="Green Goblin", villain_age=45, villain_identity="Norman Osborn").save() Villain(villain_name="Red Skull", villain_age=38, villain_identity="Johann Schmidt").save() Villain(villain_name="Vulture", villain_age=47, villain_identity="Adrian Toomes").save() Listing them individually works fine, but listing them using a union breaks the order somehow: >>> from django.db.models import F >>> from myapp.models import Hero, Villain >>> for hero in Hero.objects.all().annotate(name=F("hero_name"), age=F("hero_age"), identity=F("hero_identity")).values("name", "age", "identity"): ... print(hero) {'name': 'Superman', 'age': 30, 'identity': 'Clark Kent'} {'name': 'Iron Man', 'age': 35, 'identity': 'Tony Stark'} {'name': 'Spider-Man', 'age': 18, 'identity': 'Peter Parker'} >>> for villain in Villain.objects.all().annotate(name=F("villain_name"), age=F("villain_age"), identity=F("villain_identity")).values("name", "age", "identity"): ... print(villain) {'name': 'Green Goblin', 'age': 45, 'identity': 'Norman Osborn'} {'name': 'Red Skull', 'age': 38, 'identity': 'Johann Schmidt'} {'name': 'Vulture', 'age': 47, 'identity': 'Adrian Toomes'} >>> all = Hero.objects.all().annotate(name=F("hero_name"), age=F("hero_age"), identity=F("hero_identity")).union(Villain.objects.all().annotate(name=F("villain_name"), age=F("villain_age"), identity=F("villain_identity"))) >>> for person in all.values("name", "age", "identity"): ... print(person) {'name': 1, 'age': 'Green Goblin', 'identity': 45} {'name': 1, 'age': 'Superman', 'identity': 30} {'name': 2, 'age': 'Iron Man', 'identity': 35} {'name': 2, … -
How do I match a title of post and text of post in django
I started learning django a few weeks ago and I have run in to a problem that I can't figure out. Here is the exercise:enter image description here Models.pyenter image description here Views.pyenter image description here Blogs.htmlenter image description here Blog.html enter image description here urls.pyenter image description here Thanks in advance! -
Django: render a word document that is saved in a query object
I have an app where in my models.py I included a welcome text: welcome_text = models.FilePathField(path="/text") The file is located at app/static/text/welcome_text.docx I thought I could use {{app.welcome_text}} in my html-template, but it doesn't give anything back. Which pre-and suffix can be used to define a word document? Is it possible to render the word document that is correctly saved in the database ?