Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Save html form data in database' django
I'm trying to save name and email from HTML from using django in postgres database, in action tag, function name is mentiond but insted of using that function, django is passing that data to a new page of same function name HTML <form class="newsletter_form d-flex flex-md-row flex-column align-items-start justify-content-between" action="subscribe" method="post"> {%csrf_token%} <div class="d-flex flex-md-row flex-column align-items-start justify-content-between"> <div> <input name="subname" type="text" class="newsletter_input newsletter_input_name" id="newsletter_input_name" placeholder="Name" required="required"> <div class="input_border"></div> </div> <div> <input name="subemail" type="email" class="newsletter_input newsletter_input_email" id="newsletter_input_email" placeholder="Your e-mail" required="required"> <div class="input_border"></div> </div> </div> <div><button type="submit" class="newsletter_button">subscribe</button></div> </form> views.py def subscribe(request): if request.method == 'POST': subname = request.POST['subname'] subemail = request.POST['subemail'] sub = User.objects.create_user(subname=subname, subemail=subemail) sub.save(); return redirect('/') else: return redirect('/') url.py from django.urls import path from . import views urlpatterns = [ path("register", views.register, name='register'), path("login", views.login, name='login'), path("logout", views.logout, name='logout'), path("subscribe", views.subscribe, name='subscribe') ] this is error "image" [1]: https://imgur.com/a/8kh1Qbe "tooltip" -
How to split one form fields into multiple fields of a model in django?
This question is similar to Using multiple input fields for one model's attribute with django and How to render two form fields as one field in Django forms? What I need is basically the opposite of MultiValueField where I can save data from one form field - Name into two model fields - Firstname, Lastname. I'm unable to find any such thing like the opposite of MultiValueField. Can someone please suggest me what is the better way to do it. -
Value error on Image field when trying to comvert model to dict
I have 2 models, 1st is Garage class Garage(models.Model): name = models.CharField(verbose_name=_('Garage'), max_length=200) @property def cars(self) -> list: from django.forms.models import model_to_dict cars = [] for i in Car.objects.filter(garage=self.id): cars.append(model_to_dict(i)) return cars def __str__(self): return self.name class Meta: verbose_name = _('Garage') My 2nd model is Car, class Car(models.Model): name = models.CharField(verbose_name=_('Car Name'), max_length=200) garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2) image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None) def __str__(self): return self.name class Meta: verbose_name = _("Car") verbose_name_plural = _("Cars") Now, when I try to run, the property 'cars' in the Garage model throws ValueError. ValueError: The 'image' attribute has no file associated with it. The complete error log is: Traceback (most recent call last): File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 107, in render allow_nan=not self.strict, separators=separators File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/json.py", line 28, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.7/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File … -
CSRF Fails after setting up Django app on Apache
After creating app in django and ensuring that everything works i tried to serve my app on remote server. The stack over there is Apache with mod-wsgi-py3. After setting up Apache with documentation provided by mod_wsgi i am having problems with mod-wsgi To make sure that i dont have any problem with my app i checked on standard admin page in Django. The only open domain from that server to access is 'https://app.web.corpnet.pl:15003/app/' so all my uri's use this as a root. I think that the problem is either in django settings (allowed hosts?) or apache conf so im pasting these: ALLOWED_HOSTS = ['localhost', 'app.tnweb.corpnet.pl', 'app.tnweb.corpnet.pl:15003', 'app.corpnet.pl', 'corpnet.pl'] Problem is described by django debug as: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Referer checking failed - https://app.tnweb.corpnet.pl:15003/app/admin/login/?next=/app/admin/ does not match any trusted origin -
how to validate a user in URL field
This is my URL and that 21 is the id of my current user if I make a change in that number I put 20 it shows me the profile of id 20th user. what validation should I use? http://127.0.0.1:8000/profile/21 path('profile/<int:pk>', views.profile, name='profile') Do not tell me to remove int pk because I need it for another reason. -
How to add text input field in django admin page?
I am trying to add Id field whenever I add new user in django admin user page. I have done this in forms.py but it is showing me whenever I add new user in it. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id'] -
Django fresh login required on accessing profile page
I am new to django and writing authentication system for my application. Right now I have built the basic login/logout functionality. What I want is that whenever a logged in user wants to access their profile page, they should be asked to confirm their password. I have searched this on django docs but I was not able to find any resource on how to achieve. I know flask has a fresh_login_required decorator which does this, just wondering if it is possible to do the same thing with django as well. -
Filtering an API List View queryset according to latest timestamp AND Q lookup fields
I am trying to overwrite my get_queryset method in my generic API List View. I want to query by two fields and get the most recent item. More specifically I want to Query by project name and by graph name and get only the most recent element. I am trying to achieve this with Q lookup fields like so: class ListGraphDataAPI(ListAPIView): serializer_class = GraphSerializer def get_queryset(self, *args, **kwargs): queryset_list = Graph.objects.all() query = self.request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(name__icontains=query)& Q(project__graph__name__exact=query) ).distinct() return queryset_list This works in so far that I can filter by name of my graph. the line Q(project__graph__name__exact=query) does nothing though. THe problem is that it is a foreign key relation. Like so: class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) timestamp = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.name @property def nodes(self): return self.node_set.all() @property def edges(self): return self.edge_set.all() In my URL I type http://localhost:8000/graph-data/list/graph/?q=Graph2&q=project2 My data struture (unfiltered) looks like so: [ { "project": "project1", "name": "Graph1", "description": "Graph belongs to Projekt1", "nodes": [ { "id": 43, "name": "25", "graph": 94 } ], "edges": [ { "id": 24, "name": "EdgeForGraph1", "graph": 94, "source": 43, "target": 43 } ] }, { … -
How to run a function in the background-Django
I want to run an API call after every 5 mins in the app. I want to generate a notification whenever new data is added to the database through the API.So to check this I need to run the task in background to make it a real time application. How can I achieve this task in Django? I am facing multiple errors while using django background_tasks so I don't want to use it. Celery is not compatible with windows. Is there any other option whose tutorial is available also -
Как правильно написать модель Order в Django? [on hold]
Я написал некоторую логику работы интернет магазина на Django. На данный момент при создании заказа, в панели администратора создается заказ, который содержит в себе корзину, в свою очередь в корзине содержатся items, которые выступают в роли товарных позиций в заказе. Номер заказа - Order.id(self.id) сейчас он выглядит так (Заказ № 20), я пытаюсь вместо общего заказа, вывести в панель все товарные позиции и присвоить им номера по типу: Заказ № 20 - 1, Заказ № 20 - 2 и так далее. Все позиции должны быть должны быть в каждой строчке, и со своим порядковым номером. def str(self):return "Заказ № {0} - {1}".format(str(self.id), self.items.items.count()) В данном случае возвращается общее количество items в заказе: Например: В заказе под № 20 есть 4 позиции => Заказ № 20 - 4 Мой models.py class Category(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(blank=True) def __str__(self): return self.name class Meta: verbose_name = 'Категории товаров'# Единственное число verbose_name_plural = 'Категории товаров'# Множественное число def get_absolute_url(self): return reverse('category_detail', kwargs={"category_slug": self.slug}) def pre_save_category_slug(sender, instance, *args, **kwargs): if not instance.slug: slug = slugify(translit(str(instance.name), reversed=True)) instance.slug = slug pre_save.connect(pre_save_category_slug, sender=Category) Здесь модель брендов категорий товаров: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name = 'Производители' verbose_name_plural = 'Производители' … -
Modelformset with dynamic form addition saves only the first form
I have two forms on one page, each with its own submit button. With JS script I can dynamically add a new formset for each of the two form. I am faced with a situation where I can add as many new forms as I want for the form that is displayed first on the page and all are saved. For the second forms list, only the first form from the formset list is saved. template.html <form method="post" action="">{% csrf_token %} {{ formset_planguage.management_form }} <div id="form_set_lang"> {% for form in formset_planguage.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more_lang"> <div id="empty_form_lang" style="display:none"> <table class='no_error'> {{ formset_planguage.empty_form }} </table> </div> <input class='btn btn-primary' type="submit" name="language" value="Submit"/> </form> <form method="post" action="">{% csrf_token %} {{ formset_framework.management_form }} <div id="form_set_framework"> {% for form in formset_framework.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more_framework"> <div id="empty_form_framework" style="display:none"> <table class='no_error'> {{ formset_framework.empty_form }} </table> </div> <input class='btn btn-primary' type="submit" name="framework" value="Submit"/> </form> <script> $('#add_more_framework').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set_framework').append($('#empty_form_framework').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> <script> $('#add_more_lang').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set_lang').append($('#empty_form_lang').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) … -
Customize django admin select foreign key popup
I need to customize popup for select raw_id_field foreign key I have my admin like this: class SecondMyModel(models.Model): name = models.CharField(max_length=30) class MyModel(models.Model): switch_date = models.DateField() old_value = models.ForeignKey(SecondMyModel) class MyModelAdminForm(forms.ModelForm): class Meta(object): model = MyModel fields = ('old_value', 'switch_date') @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm list_display = ('id', 'old_value', 'switch_date') ordering = ('switch_date',) fieldsets = ( (None, { 'fields': ('old_value', 'switch_date'), 'classes': ('suit-tab', 'suit-tab-general'), }), ) raw_id_fields = ('old_value',) When I'm trying to add new MyModel I need to select 'old_value'. How can I change select foreign key popup for having opportunity to select 'old_value' by click on its id field or its name field? (not only 'id' or only 'name') -
Django passing multiple ids through URL
For POST/GET (etc) requests I have the following URL for one user: v1/users/userid123 registered as so: router.register(r"v1/users", accounts_views_v1.UserViewSet) What modifications should I make so that I can pass multiple user IDs like: v1/users/?ids=["userid123","userid456"]? It worked without any modification for another model of mine, with the same criteria, but this one keeps giving a 403 error when I try it -
I have problem using Celery, Redis and Django
I have problem using Celery, Redis and Django. I am trying to use them to create a simple task. However, an error occurs shortly after the task has been executed. I will specify below a part of the code to better understand.I thank you for your attention. CELERY_BROKER_URL = 'redis://:password@REDIS:6379/0' CELERY_RESULT_BACKEND = 'redis://REDIS:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Recife' CELERY_BEAT_SCHEDULE = { 'task-send': { 'task': 'app.tasks.task_send_email', 'schedule': crontab(hour=5, minute=44) } } Console Celery [config] app: sistema:0x7fa254a5d6f4 transport: redis://:**@redis:6379/0 results: redis://redis:6379/0 concurrency: 1 (prefork) task events: OFF (enable -E to monitor tasks in this worker) [queues] exchange=celery(direct) key=celery [tasks] app.tasks.task_send_email INFO/MainProcess] Connected to redis://:**@redis:6379/0 INFO/MainProcess] mingle: searching for neighbors INFO/MainProcess] mingle: all alone After execute the task a error occur RuntimeWarning: Exception raised outside body: ResponseError('NOAUTH Authentication required.',): The task is not completed. -
How to fix django inconsistent date fields?
I have a model that has attribute models.DateField(db_index=True) i insert datetime.strptime("2019-07-08", "%Y-%m-%d") into it. Now, when I get() on it I get: datetime.date(2019, 7, 1) as opposed to datetime.datetime(2019, 7, 1, 0, 0) Why is it inconsistent? :( -
Redirect celery task to other queue but don't consume it
I wish to create task which will redirects itself to other queue in case of error. The purpose of this is to store failed task message with all tasks data and for example use CLI to redirect data to proper queue or remove all of them. But the problem is that if I run task on the other queue the tasks is consumed and RabbitMQ doesn't store any data. Is there any way to prevent queue from consuming messages from RabbitMQ? @shared_task(bind=True) def my_task(self, arg): try: ... except MaxRetriesExceededError: my_task.apply_async([arg], queue='failed_queue') my_task.apply_async(['arg'], queue='my_queue')``` -
What do I put for 'ALLOWED_HOSTS' in django settings when deployed using a proxy server?
I got my React/Django website running on an AWS EC2 instance using Nginx and Supervisor. I'm trying to do a proper deployment rather than just put up my development environment. When I set DEBUG to False in Django's settings.py, the supervisor logs give me the error "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False." However, every combination I've tried so far has given me errors. I know that Nginx is essentially sending every request I get through my IP to localhost on the server (right?) so I figured just having 'localhost' would work but that gives me 404 errors when trying to retrieve the static files. Then I tried using my domain (currently just my public DNS from AWS since I haven't connected the domain yet) and that gives me a 400 (Bad Request) error. Using both also gets me a 404. Then I tried the wildcard ('*') since I figure Nginx is handling the traffic anyway but I STILL get a 404. TL;DR table ALLOWED_HOSTS value Result ----------------------------------------------------- ['localhost'] 404 (Not Found) ----------------------------------------------------- ['http://....amazonaws.com/'] 400 (Bad Request) ----------------------------------------------------- ['localhost', 404 (Not Found) 'http://....amazonaws.com/'] ----------------------------------------------------- ['*'] 404 (Not Found) ----------------------------------------------------- all three 404 (Not Found) ----------------------------------------------------- ['34.xxx.xx.xx'] 400 (Bad … -
Django Rest Framework HTTPResponse Download File
I am trying to process an XML file that is uploaded by the user on the fly and return the processed XML as download to the user. The following django code works as expected and after coversion, the user is prompted with Save Dialog from OS to save the file. def processXML(request): if request.method == "POST": input = request.FILES['upload'] translator = xmlProcessor.Translator() path = default_storage.save('tmp/somename-'+str(int(round(time.time() * 1000)))+'.xml', ContentFile(input.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) try: response = HttpResponse(content_type="application/atom+xml") translator.Translate(tmp_file, response) response['Content-Disposition'] = 'attachment; filename=export.xml' return response except RuntimeWarning as e: message = "Error encountered during conversion."+str(e) except: message = "Error encountered during conversion" context ={ 'status':message, } return render(request, 'pages/error.html', context) Now, I want to convert this build the Rest API equivalent using django rest framework. So far, I have been successful in receiving the upload from user via api, do the conversion. However, after the conversion, I want to provide response as a file download so that user will be prompted with Save Dialog of their OS. This is the Rest API code I have come up with. @api_view(["POST"]) def processXMLAPI(request): if request.method == 'POST': input = request.FILES['upload'] translator = xmlProcessor.Translator() path = default_storage.save('tmp/somename-'+str(int(round(time.time() * 1000)))+'.xml', ContentFile(input.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) … -
How can i set the initial value of a form to be html or Template Language in Django?
I have this form, where i set the MyField value to be non-editable, so that it can be sent to my database without being edited by the user. I want the default value to be retrieved from my db. For example, if, on that html template, i add the following line: {{value.number}}, on the template i will see 909. Now i want the same to happen with the form, the problem is that my actual code won't render 909, for example, but instead it will render the whole string: {{value.number}}. Is there a way to solve this? class MyForm(forms.ModelForm): MyField = forms.CharField( initial="{{value.number}}", disabled=True, widget=forms.TextInput) -
Django: Counting the number of objects changed in a migration
I have a Django app. I'd like to add a decorator around each of my migrations that will count the number of objects that were changed by my migration. So basically, disregarding migrations right now, I need a way to tell Django: "Starting at this point, please count the number of ORM objects that had any fields modified" and then at the end, get a count of these objects. Is that possible with Django? -
Django - access parameters of the previous request
The problem: I am working on a webapp that has a 'StudentListView' that should have the following features: Display a list of students Have a searchbox above that allows the user to filter / search this list (Submitting 'Peter' should return all students with 'Peter' in their name) An 'export' button should allow the user to export this (possibly filtered!) list to a .csv file I've implemented the code below to allow the user to filter the list, which works as intended. I've also created an export_students function that creates an .csv file of all students in the supplied queryset. This function also works as intended. However, when exporting a filtered list the program does not behave as the user expects. The user will first filter the list by providing search parameters, which will trigger an request and refresh the page. The user than presses the 'export' button, but since he did not re-submit the search parameters (why would he, the list he sees is already filtered) none are provided in the request and thus the csv file contain all students in the database, instead of the filtered selection he expects. Possible solution This problem would be solved if I … -
Dynamically path: Ensure that urlpatterns is a list of path
I have tons of generic pattern like this: urlpatterns = [ path('json/ay/<int:pk>', AyView.as_view(), name='json_ay'), path('json/by/<int:pk>', ByView.as_view(), name='json_by'), ... ] (Of course, the classes are not simply Ay or By this is for the sake of clarity), I'm trying to convert them into a generic function like this: first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') def convert(name): s1 = first_cap_re.sub(r'\1_\2', name) return all_cap_re.sub(r'\1_\2', s1).lower() def json_view(view_class): view_name = '_'.join(convert(view_class.__name__).split('_')[:-1]) return path(f'json/{view_name}/<int:pk>', view_class.as_view(), name=f'json_{view_name}'), and then call it like this: urlpatterns = [ json_view(AyView), json_view(ByView), ... ] I get this error: ERRORS: ?: (urls.E004) Your URL pattern (<URLPattern 'json/ay/<int:pk>' [name='json_ay']>,) is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. HINT: Try using path() instead of a tuple. I dont know why, any idea? -
How can I solve openid auth connection failed in django and keycloak?
I'm getting this error every time I logged into secured page using django and keycloak : OpenID Connect authentication has failed Error message is: Invalid response invalid_grant. Query content was: Also this error: Exception: this login is not valid in this application ERROR:django.request:Internal Server Error: /openid/callback/login/ this is my settings.py # OIDC auth_uri = "http://localhost:8080/auth/realms/test" client_id = "test" public_uri = "http://localhost:8000" scope = ['openid', 'profile', 'email'] from bossoidc.settings import * configure_oidc(auth_uri, client_id, public_uri, scope) Am logged in I can see this from my keycloak server session. But it doesn't redirect to the page where I want to give it. My keycloak redirect url is okay i guess http://localhost:8080/* I've used these 3 libraies: $ pip install git+https://github.com/jhuapl-boss/django-oidc.git $ pip install git+https://github.com/jhuapl-boss/drf-oidc-auth.git $ pip install git+https://github.com/jhuapl-boss/boss-oidc.git -
Django admin: detect which inline fields have been changed
I have two models named A and B: class A(models.Model): name = models.CharField(max_length=250) description = models.TextField() class B(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=250) deadline = models.DateTimeField('Deadline', null=True) and in the admin.py class BInline(admin.TabularInline): model = B extra = 0 fields = ('project', 'title', 'deadline') @admin.register(LunchRule) class A(admin.ModelAdmin): list_display = ('name', 'description') inlines = (BInline, ) def save_model(self, request, obj, form, change): """Here I can access to the fields that have been changed""" print('changed_data', form.changed_data) def save_related(self, request, form, formsets, change): """here I need to access to the fields of Model B""" I have tried to use for form_set in formsets: if form_set.has_changed(): print('Form_set',form_set) It shows new changed values but not shows the fields that has been changed I need to check the value of filed if it has been changed. For example, if project's deadline has been changed I need to validate if the time has passed etc Is it possible? -
Wagtail admin: Linking to tabbed section via language formatted id
I want to be able to go to a certain tab in the admin interface, but Im unsure how to go about it since Its language specific. I have this in my tabbed interface: edit_handler = TabbedInterface( [ ObjectList(content_panels, heading=_("Content")), ObjectList(form_content_panels, heading=_("Forms")), ObjectList(event_registration_panels, heading=_("Participants")), ObjectList(message_panels, heading=_("Messages")), ObjectList(promote_panels, heading=_("Promote")), ObjectList(TranslatablePage.settings_panels, heading=_("Settings")), ] ) I now want to link directly to the messages tab for example. But the id for this is based on the gettext formatted heading, in swedish: <section id="tab-meddelanden" class=" "> in english: <section id="tab-messages" class=" "> This makes it hard to link correctly. How can I supply a non-language formatted id?