Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up URL aliases for dynamically created URLs in DJANGO?
In my site, I have pages that are created on the fly using primary keys (for privacy/security reasons using uuid.uuid4()) as the URLs. I end up with .../reports/e657334b-75e2-48ce-8571-211251f1b341/ Is there a way to make aliases for all of these dynamically created sites to something like .../reports/report/. Right now my urls.py includes the following: path("reports/<str:pk>/", views.report_detail, name="report") I tried changing it to: re_path('reports/<str:pk>/', RedirectView.as_view(url='/reports/report/'), name="report"), path("reports/report/", views.report_detail), But I go to the site that has the links to the long URLs, I get the following error: NoReverseMatch at /reports/Reverse for 'report' with arguments '('e657334b-75e2-48ce-8571-211251f1b341',)' not found. 1 pattern(s) tried: ['reports/str:pk/'] The template for that site includes: <a class="card-title" href="{% url 'report' report.pk%}"> Without trying to make an alias, the site works fine. -
how to disable a specific button out of many button after click?
I have list of many users. i have table to dispalay user name and then one input field for email id and then submit button, when i enter email id of a specific user and click submit then user get userid and password in their mailbox. i want when i submit the submit button of that particular user get disabled. i am using django for loop in html so its disables submit button of all users. i want only that users button get disables. <a id="elementId" href="{% url 'urlabc' %}" onclick="" onclick="setTimeout(function(){document.getElementById('elementId').this.removeAttribute('href');}, 1);">Click -
Django Restframework serializing matrix of objects
I have a model which holds matrix data as JSON. class SomeModel(models.Model): matrix_data = models.TextField(...) @property def matrix(self): return json.loads(self.matrix_data) @matrix.setter def matrix(self, value: list): self.matrix_data = json.dumps(value) Form data is transferred as application/x-www-form-urlencoded: matrix[0][0][x]: 0 matrix[0][0][y]: 1 ... matrix of objects with properties x, y. Serializer looks like: class Cell(serializers.Serializer): x = serializer.IntegerField() y = serializer.IntegerField() class Row(serializers.ListSerializer): child = Cell(many=True) many = True class SomeSer(serializer.ModelSerializer): matrix = Row() class Meta: model = ... ... self.data at Serializer.save() has all data needed. I dont understand what I'm doing wrong. -
DJango form Select a valid choice. This is not one of the available choices
Here is my models.py class ProductEntry(models.Model): product=models.ForeignKey(Product, on_delete=models.CASCADE) size=models.CharField(max_length=50) # ...more fields This is my admin.py class ProductEntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductEntryForm, self).__init__(*args, **kwargs) self.fields['size'] = forms.ChoiceField( widget=forms.Select ) I am overriding the CharField with a Select widget and want to fetch the options of the select widget using javascript. But the problem is when I am going to save the model, I am getting the following error: DJango form Select a valid choice. This is not one of the available choices. Any form of work round will be appreciated. Yes I am aware that I can pass a choices arguments to the CharField but I don't want to do so because I want the choices to load dynamically based on the value of other fields. -
How to get uploaded absolute s3 image path in Django
How to get uploaded s3 image absolute path. I tried model_instance.image.file.path but it throws an error django backend doesn't support absolute paths I have multiple models with image (FileField) and wanted to get absolute path of it to be served to FE. Locally things won't get messed up but when I deploy it on production couldn't get absolute path. I was thinking to define a method get_image_path() in each model and concatenate related path something like f"https://{domain}/{static_location}/{self.image.file.url}" Please suggest if this is an ideal way to do this or is there any better approach. Thanks. -
TabError: inconsistent use of tabs and spaces in indentation while reading last object from model
TabError: inconsistent use of tabs and spaces in indentation strong text class DownloadPDF(View): def get(self, request, *args, **kwargs): patientInfo.objects.all() # data.update({'Pregencies':pInfo.Pregencies,'Glucose':Glucose,'BloodPressure':BloodPressure,'SkinThickness':SkinThickness,'Insulin':Insulin,'BMI':BMI,'DiabetesPedigreeFunction':DiabetesPedigreeFunction,'Age':Age,'username':request.user,'result':predict}) pdf = render_to_pdf('accounts/pdf_template.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response -
Run a function in parellel in Django
This is my views.py from django.shortcuts import render, redirect from . import x def index(request): return render(request,'a.html', {}) This is x.py def y() while(True): print("X") y() Currently the while loop takes all resources and blocks Django from serving a.html I need to run Django and x.py simultaneously.They are unrelated.How should do I that? I am stuck on this for 3 days.Plz help -
Handling inclusion tags though a View
So I have this index.html page that renders a sidebar though an inclusion tag, like so: {% extends "dash_base.html" %} {% load core_tags %} {% block title %} Dashboard {% endblock %} {% block links %}{% endblock %} {% block body %} <body id="page-top"> <div id="wrapper"> {% my_sidebar %} [... ... ] </body> /templatetags/core_tags.py. It doesn't make use the context for now, but eventually the sidebar.html template will: import django.template register = django.template.Library() @register.inclusion_tag('projectlibs/sidebar.html', takes_context=True) def my_sidebar(context): return {} So that works well, but ultimately I want to have different sidebars for different user profiles. My thinking is that my_sidebar should be rendered through a view, so that this view can leverage the User model to check permission & other details stored in the profile & display things accordingly. However I don't understand how I am supposed to process the included tag template (e.g. my_sidebar) through a view, since by the time I arrive at the place in the index.html template where I call my_sidebar, I'm already in the render() shortcut: views.py: from django.shortcuts import render from django.views.generic import View class IndexView(View): template_name = 'myapp/index.html' def get(self, request): return render(request, self.template_name) I know I could include that logic within the … -
trying to manipulate data for bar chart in python for test scores
trying to manipulate data for bar chart in python for test scores for the x-axis we have 0--100 % steps of 9 so if a user scores 4 it will be in the step 0 --9 , if another scores 3 it will be counted as 2 persons scored within the step. any help in implementing this will be appreciated. thanks -
sys.path don't locate local dir
thanks for your time. i've been trying to import a models file inside a seeder command. i've tried from ...models import Player, from winners.models import Player added init.py every thing that could be possible right. and keep getting or ModuleNotFoundError: No module named 'winners' or ImportError: attempted relative import with no known parent package although when i print the sys.path the local project ain't there. I've just started working on kali VirtualBox, could it be something wrong with the configuration? Please i'm 2 days stuck in a stupid problem. -
How use Django get_or_create on Foreign Key
i make simple bus reservation system, the models looks like this The problem im facing now is, about customer table, the client want make bookingform together with customerform, so the logic here is : find customer by phone number, if it found, put customer name into customerform, and make booking, if not found, then make new customer data.. and make booking, but im not sure how to create booking and customer in same time at same form, Here's my models.py BookingId = models.CharField(default = random_string, max_length=10, primary_key=True) noPolice = models.ForeignKey(Vechile, on_delete=models.SET_NULL, null=True) start_date = models.DateField(null=True, blank='True') end_date = models.DateField(null=True, blank='True') price = models.DecimalField(max_digits=10, decimal_places=0, null=True, blank='True') customer_name = models.ForeignKey(Customer, on_delete=models.SET_NULL, related_name='%(class)s_nama_pelanggan', null=True) customer_phone = models.ForeignKey(Customer, on_delete=models.SET_NULL, related_name='%(class)s_no_hp', null=True) views.py def create_book(request): booking_forms = BookingForm() customer_forms = CustomerForm() if request.method == 'POST': booking_forms = BookingForm(request.POST) customer_forms = CustomerForm(request.POST) if booking_forms.is_valid() and customer_forms.is_valid(): customer_forms.save() booking_forms.save() return HttpResponseRedirect('/success') else: print(booking_forms.errors) print(customer_forms.errors) context = { 'form': booking_forms, 'cform': customer_forms } return render(request, 'booking/create_book.html', context) based that code it wont allow me create new customer, maybe something wrong about my models design, i read about get_or_create here, but how to implement it on foreign key ? Thanks for help.. -
hello please am trying manipulate data for my bar chart with range from 0 - 100 in steps of 9 in python(django)
hello please am trying manipulate data for my bar chart with range from 0 - 100 in steps of 9 in python(django) what i have tried score = {"0 - 10": 0, "11 - 20": 0, "21 - 30": 0, "31 - 40": 0, "41 - 50": 0, "51 - 60": 0, "61 - 70": 0, "71 - 80": 0, "81 - 90": 0, "91 - 100": 0} OUTCOMES = {} for i in range(0, 10): OUTCOMES[i] = score["0 - 10"] = + 1 for i in range(11, 20): OUTCOMES[i] = score["11 - 20"] = + 1 for i in range(21, 30): OUTCOMES[i] = score["21 - 30"] = + 1 for i in range(31, 40): OUTCOMES[i] = score["31 - 40"] = + 1 for i in range(41, 50): OUTCOMES[i] = score["41 - 50"] = + 1 for i in range(51, 60): OUTCOMES[i] = score["51 - 60"] = + 1 for i in range(61, 70): OUTCOMES[i] = score["61 - 70"] = + 1 for i in range(71, 80): OUTCOMES[i] = score["71 - 80"] = + 1 for i in range(81, 90): OUTCOMES[i] = score["81 - 90"] = + 1 for i in range(91, 100): OUTCOMES[i] = score["91 - 100"] = + … -
Run python file on Django
I have created the Telegram bot on python. It works without any webhooks. I just run the .py file and the bot in telegram starts working. I need to deploy the bot on hosting. I want to install Django on my hosting and to run the file "bot.py" from Django so that the bot would work permantently and it wouldn't stop. How can I do that? Previously I just created venv on hosting and was running the app through SSH with nohup. But after autoreloading of server I needed to run the bot again with hands, so I decided to move to Django in order to escape this problem with manual restart. -
Removing additional double quotes in django rest response
I'm new to Django rest framework, I tried to create a view class TestView(APIView): def get(self, request, *args, **kwargs): return Response("Hello world") When I send a request with curl or request module in python like this: curl -X GET localhost:8000/test/ I get "Hello world" as a response, what I actually need is Hello world string without the additional double-quotes. I tried different content_types, but none of them worked so far. How can I get rid of the double-quotes? -
Can you write a Django ManyToMany Custom Cascade Delete?
I am using Django 3.1 with PostgreSQL. Here is an example setup: **Tables:** Batch (id, name) Data (id, Batch, Stuff(ManyToMany)) Stuff (id, name) Consider this scenario: If I add one record in Batch with the id of 1 and then I add 10,000 records in Data that is linking to Batch#1 and each item might reference some items in the Stuff table. Issue: If I delete Batch#1 it ends up creating a query like this for deleting the ManyToMany Relationships: DELETE FROM "data_stuff" WHERE "data_stuff"."data_id" IN (1, 2, 3 ... 9999, 10000) That is a lot of IDs listed out. I would prefer the query to be something like this: DELETE FROM "data_stuff" WHERE "data_stuff"."data_id" IN (SELECT U0."id" FROM "data" U0 WHERE U0."batch_id" = 1) Any ideas of how I can have it generate the SQL like my second example when deleting? -
Update multiple Django view variables
My Django app has several views dependent on the same input variables. In the example below, both my views depend on the 'animal' variable, which is set outside of each view. Now, the user needs the ability to change the 'animal' variable from 'Dog' to 'Cat' in the user interface. This essentially changes the universe of the app from "Dog" to "Cat", and the whole app pulls information based on the new variables. I can make this change manually from editing my views.py with no issues. However, I need the user to be able to switch back and forth themselves. I've read that SESSIONS is designed to handle this. But I had 2 primary questions... Since the views REQUIRE that variable to not be null, how to I set a default value for whenever a user logs into the application? Do I need to retype request.session.get() in every view? Or can I use sessions to update the 'animal' variable at the top of my views.py? Thanks in advance for all your help. animal = 'Dog' def index(request): animal_types = animals.objects.filter(type=animal) params = {'animals':animal_types,} return render(request, 'index.html', params) def summarypage(request): summarytypes = animailsummary.objects.filter(type=animal) params = {'animals':animal_types,} return render(request, 'summary.html', params) (additional … -
Django password reset fails on submitting email with error shared below
[Error Message][1] [1]: https://i.stack.imgur.com/N6Txl.png Exception Type: ProgrammingError at /accounts/password_reset/ Exception Value: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]An expression of non-boolean type specified in a context where a condition is expected, near ')'. (4145) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") -
Is there a way to implement a progress tracker in django or using js?
I have been trying to implement a user progress tracker like that used on online learning sites eg Udemy for tracking user progress on watching videos and increments automatically. How can I achieve the same thing using Django or JavaScript .Thank you -
order by method is not working on queryset
order by not working on queryset no working at all and i dont know where is the mistake seems everything is okay ! views.py class PostDetailView(DetailView): model = Post template_name = 'detail.html' #context_object_name = 'post' #form_class = CommentForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) post_comments = Comment.objects.filter(post=self.get_object()).order_by('-date_added') data['comments'] = post_comments if self.request.user.is_authenticated: data['comment_form'] = CommentForm(instance=self.request.user) return data def post(self, request, slug, *args, **kwargs): new_comment = Comment(comment=request.POST.get('comment'), name = self.request.user, post = self.get_object()) new_comment.save() return redirect('core:detail', slug=slug) models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.comment -
How to appropriately outline the path for django-duo-auth?
I am currently working on implementing Duo Two-Factor Authentication into my django project. Currently it looks like django-duo-auth is the best package for this. I installed the package and went through the basic instructions on their README: https://github.com/Elemnir/django-duo-auth/blob/master/README.rst However this has caused my project to continuously redirect to a nonexistent subdirectory of 'duo' which is what I named the path. For example my app is loaded in XX.XX.XX.XX:YYYY Going to that url auto redirects the page to: http://XX.XX.XX.XX:YYYY/duo/login/?next=/ Or, XX.XX.XX.XX:YYYY/admin auto redirects to: http://XX.XX.XX.XX:YYYY/duo/login/?next=/admin This simply will lead to django's generic base.html that duo_auth_form.html extends Here are some snippets of relevant code, though it doesn't differ to much from the package's README suggestions /urls.py urlpatterns = [ ... path('admin/', admin.site.urls), path('duo/', include('duo_auth.urls')), ] /settings.py INSTALLED_APPS = [ ... 'duo_auth', ] MIDDLEWARE = [ ... 'duo_auth.middleware.DuoAuthMiddleware', ] DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } The only difference anywhere from the read me is a slight redirection in the sample do_auth_form.html where I extend to a subdirectory of my templates i.e. {% extends "dir\base.html" %} at the top of the file. It appears like this package is fairly new and … -
How to simulate a POST to a URL using Django
I'd like to create a view function that simulates the user getting a form at url, setting one of the form's input variables (my_flag) and submitting that form. I've tried two different approaches and both have failed. Approach 1: use python requests to get and post to url def simulate_post(request): url = request.build_absolute_uri(reverse('my_app:form_view', args=[666])) response = requests.get(url) csrftoken = response.cookies['csrftoken'] print("TOKEN =", csrftoken) response = requests.post(url, data={'my_flag': True, 'csrftoken': csrftoken}, headers={'Referer': url}) return response This approach fails as follows. Obviously I'm not even passing on the CSRF token successfully: TOKEN = EXFI2xoKxHounDIRnqdrPwLpdXGe3zuZATErKINTuxJsgzV7Oj6lPP6kzsjQVc7z Forbidden (CSRF cookie not set.): /form_view/666/ [12/Feb/2021 16:44:02] "POST /form_view/666/ HTTP/1.1" 403 2868 Internal Server Error: /simulate_post/ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'Response' object has no attribute 'get' Approach 2: use RequestFactory def simulate_post(request): url = request.build_absolute_uri(reverse('my_app:form_view', args=[666])) factory = RequestFactory() factory.user = request.user response = factory.get(url) response = factory.post(url, data={'my_flag': True}) return response This approach fails as follows: Internal Server Error: /simulate_post/ Traceback (most recent call last): File "/Users/me/.local/share/virtualenvs/myapp-MCS7ouoX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) … -
How to secure Django Rest API
I created custom survey with React and I want to send data once survey is complete to Drip (user managing platform) https://developer.drip.com/ I can't connect website with Drip API directly - it'll expose API Key. I decided to use Python Django with REST as proxy. My question - what's possible threats and how can I secure my Backend? Thanks! -
Django templates : <how to create a view like this>
{% if node.post_type == "photo" %} {% get_file node as files %} {% if files.count == 1 %} {% for file in files %} <img class="r-8 cover" src="{{file.file.url}}" width="100%" height="150px"> {% endfor %} {% else %} <div class="form-row"> {% for file in files %} <div class="col p mrn-2"><img class="cover mbn-2 rlt-8" src="img/ic_profile_test.png" width="100%" height="74px"> <img class="cover rlb-8" src="img/ic_profile_test.png" width="100%" height="74px"></div> <div class="col p"><img class="cover mbn-2 rrt-8" src="img/ic_profile_test.png" width="100%" height="74px"> <img class="cover rrb-8" src="img/ic_profile_test.png" width="100%" height="74px"></div> {% endfor %} </div> {% endif %} {% endif %} ** This is what i want to achieve ** https://i.stack.imgur.com/6q5hd.png ** But i keep getting this ** https://i.stack.imgur.com/2TS9H.png Please how can i do something like this If user post two pictures i only display row 1 If user post three pictures i display row 1 and row 3 and hide the last child If user post four pictures i display all child -
How can I use a singe test file django
For testing, I am currently using TemporaryUploadedFile for the file field on one of my models. The issue is each time I run a test, there is a new file created. Is there a way that I can point the file field to a pre existing file named something like txt.txt stored in a pre-defined directory? In the test I define the file as : self.example_file.file = TemporaryUploadedFile( "temp.txt", size="100kb", content_type="txt", charset=b"This is the content of the file!" ) In the mdoel the file is created using models.FileField: example_file = models.FileField( blank=True, null=True, upload_to=UploadToPath('files'), ) What I would like to be able to do is in the test is simply point to a one off pre existing file. I can not figure out how to do it. If this can not be done and anyone knows of a better alternative where I do not need to upload a new file each time I use the file field in testing it would be great to know how to do that as well! -
how to Pick Address from Google Maps and auto fill in user address form in django webapp?
how could the client pick delivery order address from google maps in my website and auto fill the address in client address form User can drag the map and place a marker therein and then user can select details address from that location and set to anywhere else.