Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model verbose_name as API rows response names
As I can't save special characters in fields in django model I have to bypass it. For example: I would like to have "km/h" field. So I'm using it like: class Unit(models.Model): kmh = models.FloatField(null=True, db_column='km/h', verbose_name='km/h') then I have example serializer: class UnitSerializer(serializers.ModelSerializer): class Meta: model = Unit fields = ['kmh'] and when I'll use it with APIViews response which will include the field will look like: { "kmh":10, } I would like to make it look like my verbose_name so: { "km/h":10 } How can I do it? -
Multiple Image Upload with Preview in JS does not work to upload images to the database
I just implemented a Multiple Image Upload with Preview, it was the easiest option I had as I don't know JS. The point is that I am using it with my project in Django. The question is, how do I save those images to my database? For example, the Multiple Image Upload With Preview has a button that says "browse" that, when clicked, serves as an input where the preview of the images appears, but it does not work like this: <input type="file" name="guarantee" class="form-control" multiple="" accept="image/*" required="" id="id_guarantee"> and I want that "browse" button to do what the input (called "Elegir archivos") I put above does so that it loads the images to the database -
StaticFiles vs MediaFiles
What is the difference between static files and media files? Django says that the SATIC_ROOT and MEDIA_ROOT must be different. I just know that in static folder we can have css files and images or other files to be uploaded goes to media folder. I have directory as static |-->images |-->css in settings.py >> STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') Is the ROOT and URL for static and media files are okay or not? -
Writing custom ASC recommendations using Azure Python SDK
I am trying to write custom recommendations into Azure Security Center from my own product but I can't find any real reference in the SDK documentation to say how to do this. I can see references to IoT but not "normal" recommendations. Has anyone else managed to do this? -
How can I save requests when using login_required in django
I am making community site with django. I required login for creating answer. However when I answed with non-login user it required login and next redirect to first answer page but already written answer disappeared. So I want to save requests before login_required decorator. Here is the code @login_required(login_url='common:login') def answer_create(request, question_id): question = get_object_or_404(Question, id=question_id) if request.method == "POST": form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.author = request.user answer.create_date = timezone.now() answer.question = question answer.save() return redirect('pybo:detail', question_id=question_id) else : form = AnswerForm() context = {'question':question, 'form':form} return render(request, 'pybo/question_detail.html', context) -
Is there a way to automatically generate a whole system for different users
I am done with a hostel management system in Django which consist of payments, users registering for rooms, etc. But with this, i want it in a way that, when a user or a hostel manager wants to buy such a system, they buy it from our website so it automatically generates the whole hostel management system for him or her in which it will be different from another person also buying the same system from us. and also if in case i will want to add a yearly subscription how will it be done. Thank you for your help -
Django js tabs keep selected tab on page refresh
I'm working with js tabs in Django and they work fine but I'd like to keep the selected tab active on that moment on page refresh. I found this example but it doesn't work https://www.tutorialrepublic.com/faq/how-to-keep-the-current-tab-active-on-page-reload-in-bootstrap.php This is the script I'm using: {% extends "bioinfointerface/base.html" %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Keep Selected Bootstrap Tab Active on Page Refresh</title> <script> $(document).ready(function(){ $('a[data-toggle="tab"]').on('show.bs.tab', function(e) { localStorage.setItem('activeTab', $(e.target).attr('href')); }); var activeTab = localStorage.getItem('activeTab'); if(activeTab){ $('#myTab a[href="' + activeTab + '"]').tab('show'); } }); </script> </head> <body> <div class="m-3"> <ul class="nav nav-tabs" id="myTab"> <li class="nav-item"> <a href="#sectionA" class="nav-link active" data-toggle="tab">Section A</a> </li> <li class="nav-item"> <a href="#sectionB" class="nav-link" data-toggle="tab">Section B</a> </li> <li class="nav-item"> <a href="#sectionC" class="nav-link" data-toggle="tab">Section C</a> </li> </ul> <div class="tab-content"> <div id="sectionA" class="tab-pane fade show active"> <h3>Section A</h3> <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p> </div> <div id="sectionB" class="tab-pane fade"> <h3>Section B</h3> <p>Vestibulum nec erat eu nulla rhoncus fringilla...</p> </div> <div id="sectionC" class="tab-pane fade"> <h3>Section C</h3> <p>Nullam hendrerit justo non leo aliquet...</p> </div> </div> </div> </body> </html> {% endblock %} In base.html I load: <!-- Bootstrap core JS--> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS--> <script src="{% static 'bioinfointerface/js/scripts.js' %}"></script> <link … -
Customer registration with dynamic forms django
By entering the phone number in the customer registration form , if the customer already exists then should fill the rest of the fields by fetching it from the backend. if the user does not exists then have to register. help me with the script used for this this is the model i have. class Customers(models.Model): customer_id = models.AutoField(primary_key=True) cname = models.CharField(max_length=100) cnumber= models.IntegerField() caddress= models.CharField(max_length=100) I m using the modelform here. class CustForm(forms.ModelForm): class Meta: model=Customers fields = '__all__ this is my view def customer(request): form=CustForm() if request.method=='POST': form = CustForm(request.POST) form if form.is_valid(): form.save(commit=True) messages.success(request,'successfully customer added') return render(request,'hello.html') else: messages.error(request,'Invalid') return render(request,'custdata.html',{'form':form}) This is my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% block content %} <div> <center><h2><b>Add Customer</b></h2></center> <p><form method='post'> {% csrf_token %} <center> {{form.as_p}} <button type="submit" style="width:200px; height:30px; font-size: 20px;">ADD</button> </center> </form> </div> {% endblock %} </body> </html>``` -
Django template | safe filter behaving differently on different environments
In the template I have <div>{{ my_var | safe }}</div>, where my_var is being set as my_var = format_html("<p>my variable</p>") and rendered using render_to_string function. In the production environment, the result is produced as &lt;p&gt;my variable&lt;/p&gt;. It works correctly in the local environment. I understand format_html produces safe string which shouldn't be escaped by the template, even providing | safe filter isn't solving the issue. The baffling thing is it behaves correctly on staging/local env but not on prod -
Testing Django Wagtail - assert that a child of the given Page type can be created under the parent, using the supplied POST data
I've defined a custom page model (a blog post) as a child of a parent model (a blog index page) and I want to test that the child can be created under its parent. The BlogPage and BlogIndexPage models are copied from the wagtail "basic blog" example in the documentation, and works as expected. I'm trying to follow the documentation but I get the following validation error: AssertionError: Validation errors found when creating a cms.blogpage: E date: E This field is required. E intro: E This field is required. E slug: E This field is required. E title: E This field is required. I suspect that I'm defining my fixture incorrectly, but I am not what the correct form is. Any help is greatly appreciated! Can someone explain why it isn't working? fixture (apps.cms.tests.fixtures.blogPage.json): [ { "model":"wagtailcore.page", "pk": 1, "fields":{ "date":"2022-02-28", "intro":"intro to the post...", "slug":"slug/", "title":"the title", "body":"body of the post...", "categories":[ 1 ], "content_type": ["cms", "blogpage"], "depth": 2 } }, { "model": "cms.blogpage", "pk": 1, "fields": {} } ] the test class (apps.cms.tests.test_pages.py): class MyPageTests(WagtailPageTests): def setUp(self): self.login() page = BlogIndexPage(title="Home page", slug="home", path="foo", depth=1) page.save() def test_create_blog_post(self): cwd = Path.cwd() root_page = BlogIndexPage.objects.first() with open(f"{cwd}/lettergun/apps/cms/tests/fixtures/BlogPage.json") as json_file: … -
Nginx WebServer and API Server
A system I am designing is composed of a Django application that serves a web page for the user, and a Flask server that exposes a set of REST API that are meant to be used from other external programs. For deployment I would like to make both web page and API use HTTPS protocol. To achieve this in test environment I started an Nginx instance and make it communicate with Django through uwsgi help, then configured Nginx to listen on a port in ssl mode. I guess I should do something very similar with Flask, but I am not confident what is the best way to do it. -
How to enable POST,PUT for django rest framework viewset
I have simple viewset like this in views.py class MyFileViewSet(viewsets.ViewSet): http_method_names = ['post','get','put'] def list(self, request): queryset = MyFile.objects.all() serializer = MyFileSerializer(queryset, many=True) return Response(serializer.data) models.py from xml.dom.minidom import DOMImplementation from django.db import models class MyModel(models.Model): name = models.CharField(verbose_name='NAME', max_length=30) file = models.FileField(upload_to='file/%Y/%m/%d') is_transfer_finish = models.BooleanField(default=False) created_at = models.DateTimeField(verbose_name='created', auto_now_add=True) Now I can see the list of MyModel. However I want to set post and push for this model, I set http_method_names = ['post','get','put'] But currently, there is only 'GET' on html. I want to enable POST or PUT to create new entry. Is it possible? how can I make this? -
Django or flask which is easier to learn first [closed]
I am new in python I would like to learn django but some of my friends told me that I should learn flask before learning Django. what should i do? -
Django widget for sensitive fields
I am working on a Django website that presents users a form to store their API keys and API secrets. At the moment both fields are showing as CharField generated by django-crispy-forms so both the API key and API secrets are visible. I would like a behaviour where by default the fields are showing ****** or ●●●●●● when not focused and revealing the content when focused. I have tried making this field a PasswordInput() widget in forms.py with self.fields["my_field"].widget = forms.PasswordInput() However this brings a couple of problems: Browsers consider the API keys and an API secrets as actual passwords and save them at the browser level When the field is focussed, the contents of the fields are not shown Is creating a custom widget the only solution for this? -
Trying to load a simple html in Django but it appears GET /homepage/ HTTP/1.1" 500 145
I'm quite new in Django development. I did the Tutorial for the polling app on the official Django web page and everything worked out fine. Since I already have some HTML from my old website I wanted to reuse some of that. I decided to create an app called "homepage" for the main page you get when you visit the page (if this is bad practice, let me know). Since the main page is more or less just some introductory text and a navigation menu without any fancy functionality I did not create a DB (models) in this case. Furthermore I was sure that Django is able to simply deliver some plain static html without a database provided. The urls.py in the hompage app folder looks like: from django.urls import path from . import views urlpatterns = [ path('', views.index1, name='index1'),] and the view.py like this from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Hello, world. You're at the polls index.") Everything works out fine. As soon as I try to load a html file (here a simple one just to check if it works) I get the error message. The new view.py looks like in the … -
Could not import 'rest_framework_jwt.authentication' when running python manage.py migrate
Following a tutorial to use JWT to handle user authentication through tokens. I have got as far as making changes to my Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DATETIME_FORMAT': "%m/%d/%Y %I:%M%P", 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) my urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views from rest_framework_jwt.views import obtain_jwt_token router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) # router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('token-auth/', obtain_jwt_token) When I try to run python manage.py migrate I get the error: ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (C:\Users\15512\anaconda3\lib\site-packages\django\utils\encoding.py). I already pip installed djangorestframework-jwt -
Watchlist showing in admin interface but not showing on the site django
I am working on a project and the features is that the user should be able to add the item to their “Watchlist.” If the item is already on the watchlist, the user should be able to remove it and users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. When I click on the 'add to watchlist' button, it successfully registers on the admin panel ( screenshot included) but on my webpage, it shows me an empty image (it's supposed to show the listings image) and when I click on that image, it shows me an error message 'No Auction matches the given query.' and I noticed it gives me a different url id (screenshot included and different url from the actual url id of the details page and actual url id of the details page which i'm supposed to be linked to(which is 1)). Also, when I delete one of the products/listing (still by clicking on the add to watchlist button - i would later improve this), it removes everything in the watchlist (even if there were other items in … -
Key removed from dict despite dict.copy()
I'm recently experimenting with session variables instead of writing everything in base. I'm building an app for counter sales (car, user, customer session variables). After the order and its items are saved in DB, I want to save the customer and clear its related session variables of the related customer from request.session['customers'] dict list. def save_customer(request, store): # save only customers != Client Magasin customers = request.session['customers'].copy() print(customers) current_customer = list(filter( lambda i: i['user'] == request.user.pk and i['store'] == store, customers))[0] id = current_customer.pop('id') nom = current_customer['nom'] if nom != 'Client Magasin': current_customer.pop('store') current_customer.pop('user') customer = Customer.objects.create(**current_customer) # return Customer for adding it to order return customer else: # return Client Magasin return Customer.objects.get(pk=1) When I print out request.session['customers'] I can see ID, STORE and USER keys. But after the lambda, those keys are removed from the original request.session['customers'] I know that because further in my code, I wan't to filter again this list def remove_same_customer(request): customers_list = request.session['customers'].copy() print(customers_list) # new_customers = list(filter( # lambda i: i['store'] != request.session['cart_warehouse'] and i['user'] != request.user, customers_list)) # request.session['customers'] = new_customers # request.session.modified = True I have commented the 4 last lines because they trigger an error because ID, STORE and USER … -
How do you add user-defined S3 metadata in when using django-storages
I am using django 3.1.0 with django-storages 1.12.3. I am using an S3 backend to store media files (Minio). I am trying to post the file to S3, and include additional user metadata to the S3 object. This additional metadata comes from the POST request used to upload the file to django. With S3, custom metadata can be added by including additional key-value pairs to the HTTP header for the POST request sent to the S3 server when the file is uploaded, where the custom keys would be prefixed with 'X-Amz-Meta-'. I am using a FileField in a django model, and files are uploaded using a REST API endpoint. As far as I understand it, when django receives the file, it stores it temporarily, and then, when saving the FielField on the model instance, the file is posted to the S3 server. I want to modify the flow, so that the custom metadata is taken from the request and included in the post to the S3 server. Any idea how I can take data from the initial request, and pass it to the header of the POST request being sent to S3? -
What is the simplest way to fake a Django model field?
Currently my Django models looks like this: class Car(Model): horse_power = IntegerField() I have lots of models similar to this, they are used all over the application, there are serializers of DRF endpoints using these model fields as well. Of course the field names are different in other models. However, the horse_power value as well as other fields are no longer IntegerField, but a foreign key to another table containing more complex information like below: class Car(Model): horse_power_complex = OneToOneField(ComplexDataModel, on_delete=CASCADE) To avoid lots of code change in every place the Car model is manipulated, I would like to keep the same getter and setter interfaces as before, in other words, I would like car.horse_power to return a simple integer calculated from the ComplexDataModel, and I also would like car.horse_power = 23 to access the ComplexDataModel and save the processed data so that I dont have to go over the entire application to update all references. It is important to keep in mind that the model constructor should still work, for example, car = Car(horse_power=50). I have tried python descriptors like below: class HorsePower: def __get__(self, obj, objtype=None): return obj.horse_power_complex.get_value() def __set__(self, obj, value): obj.horse_power_complex.set_value(value) class Car(Model): horse_power = HorsePower() … -
Is there a way to create a global counter variable on django templates?
I don't see any other solution other than creating a global variable counter, this counter would be then checked if it meets the criteria (let's say 9 items per page) then do a page break Ideally, here is what I expect to do: I have fruit_items define like this: Class FruitVendor(Model): .... @property def fruit_items(self): return chain( self.appleitem_set.all(), self.bananaitem_set.all() ) Then in django template I do this to list: {% for item in fruit_vendor.fruit_items %} {% if forloop.counter|divisibleby:9 %} <p style="page-break-before: always"></p> {% endif %} <table> {% for apple in appleitem_set.all() %} <tr> <td> {{apple.name}} </td> </tr> {% endfor %} </table> <table> {% for banana in bananaitem_set.all() %} <tr> <td> {{banana.name}} </td> </tr> {% endfor %} </table> {% endfor %} As you can see in above, this would page-break but the overhead looping of fruit_items generate multiple tables which is not intended. What I think I should do remove the forloop in fruit_items and have a global counter that adds + 1 in each for loop, then check if the global counter is divisible by 9 then page-break, but I'm not sure if this is possible. counter = 0 {% if counter|divisibleby:9 %} <p style="page-break-before: always"></p> {% endif %} <table> … -
inline-formset doens't get diplayed in my form
I have a model Company and a model Address, related by a one-to-one relationship in Address: class Company(CompanyParent): # some attributes class Address(AddressParent): company = models.OneToOneField(Company) # some attributes Since these are closely related, I want the user to create a Company object, an Address object and the relationship between the two by just submitting one form; so I looked into Inline Formsets. Here my forms.py: class CompanyModelForm(forms.ModelForm): class Meta: model = Company fields = # ... labels = { # ... } def __init__(self, *args, **kwargs): super(HubModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal style-form centered' self.helper.add_input(Submit('submit', 'Submit')) class AddressModelForm(forms.ModelForm): class Meta: model = Address fields = # ... labels = { # ... } AddressFormSet = inlineformset_factory(Company, Address, form=AddressModelForm) All the logic is handled by a view: class CreateCompanyView(SuccessMessageMixin, CreateView): model = Company form_class = ComapnyModelForm template_name = # ... success_url = '/' success_message = # ... def get_context_data(self, **kwargs): ctx = super(CreateCompanyView, self).get_context_data(**kwargs) if self.request.POST: ctx['formset'] = AddressFormSet(self.request.POST) ctx['formset'] = AddressFormSet() return ctx def form_valid(self, form): ctx = self.get_context_data() formset = ctx['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(CreateCompanyView, self).form_valid(form) When I use {% crispy form %} in my template … -
How Do I Properly Submit Two Forms Within One HTML Structure?
I am trying to submit a create view with two forms. The code below works fine if everything is filled out and the form submitted. However if fields are omitted in form2...the form submission fails and the field that was filled out for "form"..."name"....gets reset. I've read you can do multiple forms and I've largely got this working...I just need to figure out how to incorporate form2 into the if_valid().... Here's my view... def tasklist_detail_view(request, id): context = {} context["tasklist"] = TaskList.objects.get(id=id) context["tasks"] = Task.objects.filter(task_list=id).all() obj = get_object_or_404(TaskList, id=id) form = UpdateTaskListForm(request.POST or None, instance=obj) form2 = TaskForm(request.POST or None) context["task_list_id"] = id if form.is_valid(): form.save() return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu")) context["form"] = form context["form2"] = form2 return render(request, "my_task_list_tasklist_detail.html", context) My HTML... <form method="POST" enctype="multipart/form-data" id="forms"> {% csrf_token %} {{ form.name }} {% include "my_task_list_task_create_form1.html" with tasklist=tasklist %} <button type="submit" class="button66" name="status" value="Submitted">Submit</button> </form> And then in my include HTML... <div id="task-list-form" hx-target="this" hx-swap="outerHTML"> <button class="button35" hx-post="{% url 'MyTaskLists:task-create' id=task_list_id %}">Save</button> {{ form2 }} I did try to do something like.... if form.is_valid() and form2.is_valid(): form.save() return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu")) But then nothing happens...the forms are not accepted at all even if the fields are filled out properly....From what I've read I understand the … -
Video not playing on Django when debug=False
Videos are not playing when I turn DEBUG to False on Django, but on DEBUG=True, everything is fine. The task is simple, the app receives youtube shorts link, downloads it to the MEDIA_ROOT (which declared in settings.py as BASE_DIR / 'media'). And it returns rendered template video.html, on template: <video height="450" autoplay="autoplay" controls style=""> <source src="{{ MEDIA_URL }}{{ file }}" type="{{ mime_type }}"> on html : ` views: {"MEDIA_URL": MEDIA_URL, "file": str(video.video).split('/')[-1],} settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = Path(__file__).resolve().parent.parent / 'media' As I said when debug mode turned on everything works perfect, but I turned it off video is not playing. Did I forget something? Or any mistake I have? how to solve this problem? P.S. I am pretty new on django, I searched for many sources, tried them all, but I couldn't solve this problem -
Paragraphs get lost when posting a form
Hey, I'm creating a forum using django. When a user posts a thread the written text (in the input field {{obj.content}}) by the user should be displayed exactly as he typed it in. The text is displayed through {{form.content}}. That means the paragraphs which were made by the user should be maintained. But in the moment they get lost and the text is displayed without paragraphs. create_thread.py (on this page a thread can be created): {% extends "forum/index.html" %} {% load static %} {% block title %} {{post.title}} {% endblock %} {% block content %} {% for obj in objects %} <div class="container-thread"> <div class="username">{{obj.username}}</div> <div class="topic">{{obj.topic}}</div> <div class="content">{{obj.content}}</div> </div> {% endfor %} {% endblock %} thread.html (on this page the thread is displayed): <div class="container-create-thread"> <h2 class="heading-create-thread">Create a thread</h2> <form method="POST" action=""> {% csrf_token %} <label class="label-topic">Topic</label> {{form.topic}} <label class="label-title">Title</label> {{form.title}} <label class="label-content">Content</label> {{form.content}} <button class="btn submit" id="submit-create-thread" type="submit" value="submit">Submit</button> </form> </div>