Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Handling signals when an object with m2m relations is created
I wish to do the following. When a new project is created , i want to notify everybody that was assigned to the project that there's a new project available. Here is my simplified project model: class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) history = HistoricalRecords(excluded_fields=['version', 'project_status']) def __str__(self): return self.sales_project_name When a project is being created, i will send out the following signal : def CreateProjectNotification(sender, **kwargs): if kwargs['action'] == "post_add" and kwargs["model"] == UserProfile: for person in kwargs['instance'].userProfile.all(): #some check here to prevent me from creating a notification for the creator or the project Notifications.objects.create( target= person.user, extra = 'Sales Project', object_url = '/project/detail/' + str(kwargs['instance'].pk) + '/', title = 'New Sales Project created') The reason why im using the m2m_changed.connect instead of post_save is because i wish to access the M2M field , UserProfile to send out the notifications. Since the object would not be added to the through table at the point of creation , i can't use the post_save and instead i have to track the changes from the through table . problem With that said , this signal runs as long as the save() function is called and the model which changed … -
parse and store json data to django model
I am able to call an api within django with requests inside the view to get the data response back in dictionary format as below: {'name': 'John', 'Value': [2, 4, 3]} I am now confused on how to load this data to the mode I have existing: class Table_name(models.Model): person_name = models.CharField(max_length=100) person_value = models.CharField(max_length=30) Can someone please advise? Thank you -
Getting response 475 while making request
I am making XHR requests to the hotstar API https://api.hotstar.com/s/v1/scout?q={movie_name}&perPage=50 The headers I am using for the request are headers = { 'Host': 'api.hotstar.com', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://www.hotstar.com/in', 'x-country-code': 'IN', 'x-platform-code': 'PCTV', 'x-client-code': 'LR', 'hotstarauth': 'st=1591731250~exp=1591737250~acl=/*~hmac=30e290968fac98e02d39b937ec556c42d1692d6493d0ae29e49bcb1723829e23', } Making the request on my local machine, it runs fine and gives the desired results import requests response = requests.get('https://api.hotstar.com/s/v1/scout?q={}&perPage=50'.format(movie_name), headers=headers) The above code returns the desired results, but I have the Django app hosted on Heroku. But I get response code 475 on the heroku server. On Local Machine: Response 200 On Heroku Server: Response 475 I have other requests also on my Django App, and all are working fine. Only problem is with the above request. Can someone please explain me what am I doing wrong ? Also, I want to confirm what I am doing here is not something illegal ? -
Display relevant file to user - Django
I am trying to build a web app that creates a video programmatically on button click in browser and displays it in the same browser for the user once it's created. So far I have hooked up a script that makes the video when button is fired and that works. I also have a model where the same script uploads and stores the created videos and that works too. Now I'm stuck trying to display the relevant video to the user that created it ie clicked the button. How do I do this? What methods should I use? I am not sure how to proceed. In the example below I am able to display video with id=16. How can I adapt this so that the browser displays the relevant video rather than the video associated with id=16? .html {% load static %} <html> <head> <title>Title of the document</title> </head> <body> <video width="320" height="240" controls> <source src= "{{ MEDIA_URL }}{{ object.videofile }}" type='video/mp4'> </video> <p></p> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <button id="myClickButton" type="button">Click</button> <div id="myOutput"></div> <script> $("#myClickButton").click(function() { $.get("/output/", function(data) { $("#myOutput").html(data); }, "html"); }); </script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> </body> </html> models.py from django.db import models class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True) views.py … -
my auto-complete form only work for the first input using select2 js
i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms this is my snippet <tbody class="tbody tb1 " id="form_set"> {% for item in items.forms %} <tr class="p-0 col-12"> <td class=""> <div class="col-12 p-0 mt-3 inp"> <input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz"> </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.price | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.quantity | add_class:'col-12 '}} </div> </td> <td class=""> <div class="col-12 p-0 mt-3 inp"> {{item.model | add_class:'col-12 0model model' | attr:'id:model'}} </div> </td> </tr> {% endfor %} </tbody> <script type="text/javascript"> $(function(){ $('.tb1 tr:last').formset({ prefix:'{{items.prefix}}', addText:'add', deleteText:'remove', addCssClass:'btn btn-success', }); }) </script> <script type="text/javascript"> $(document).ready(function(){ $("#model").select2() }) </script> but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe? thanks -
I can’t understand what I’m doing wrong. Django + Python
Code review: def login_api(request): post = json.loads(request.body.decode()) try: email_user = CustomUser.objects.get(email=post['username']) username = email_user except: username = post['username'] user = authenticate(username=username, password=post['password']) if user: login(request, user) n_token=''.join(choice(ascii_letters) for i in range(12)) new_token = Token( token=n_token, user=user ) new_token.save() return JsonResponse({'login': True, 'token':n_token}) return JsonResponse({'login': False}) Login and adding a new user does not work, i need help. I think trouble in request body, cause my front send token and title, i bad in django and i don’t understand how it works at all -
Should I store dates for recurring local events in UTC, for different locations with different time zones?
I know there has been a lot of talk on this topic and there are no magic answers about it. But in the field of travel, we manage the local time of the place where we are traveling. for example. If I am in the United States and I reserve for an event in Japan I must adjust to the local time of that event in Japan. There are places that observe the summertime, but others do not. So whoever attends the event must adjust to the local time. So it does not matter much where the user is, but where the event will be. Should I save in UTC equivalent to the local time of the event in the database, and then display and convert from UTC to the local time of the event in the template? I am using with Django web framework -
How to Use Caching in Django Heroku App for entire website
How to cache for the Django site, I use caching for the website but it does not give me appropriate results. what is the best way to use caching for entire website? -
Python ModuleNotFoundError: I can't import my module
I have got a CRUD App, I'm learning API rest with Python and Django... I create this module: from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model: User fields = ['url', 'username', 'email', 'groups'] And after that, I write this: from django.contrib.auth.models import User, Group from rest_framework import viewsets from djangoCRUD.Api.serializer import UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().orderby('-date_joined') serializer_class = UserSerializer This is all right, but, when I write my url.py Here, I have got a problem: from django.contrib import admin from django.urls import path, include from rest_framework import routers from djangoCRUD.Api import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] And I have this error message: File "C:\PythonDev\pythoncrud\venv\djangoCRUD\djangoCRUD\urls.py", line 20, in from djangoCRUD.Api import views ModuleNotFoundError: No module named 'djangoCRUD.Api' -
django: how can i get the last id or row_id of a table?
I'm writing a website, i need to make a numbering system, i need to add the latest row_id/id + 1 to a charfield, alll work is nearly done but this. any idea how to get the number? its like getting the row id of the object before adding it to the table. letter_numbering = cjy + latest_row_id +1 ~~~ class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) title = models.CharField(max_length=200) jalali_date = models.CharField(max_length=10, default=current_full_j_date) -> letter_number = models.CharField(max_length=7, default=letter_numbering) from_to = models.CharField(max_length=200) file = forms.FileField() letter_type = models.CharField(max_length=8, choices=letter_direction, default='incoming') text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) -
How to make a django form field as a link field
How to change a django field which is a FileField button to a link as follows: to: My code is this: /main.css: lable[for="file"] { width: 90px; text-align: center; background-color: #900 padding: 5px; cursor: pointer; margin-top: 15px; color: blue; } input[type="file"] { display: none; } /forms.py class postform(forms.ModelForm): class Meta: model = Post fields = [ "title", "content", "image", ] /models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() published = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) imagefile = models.FileField(null=True, blank=True, upload_to='PostImg') And I guess the problem is in html file where I should put {{ form.image }} in input! /post_form.html <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">POST</legend> <!-- {{ form|crispy }} --> <label for="title">Title</label> {{ form.title }} <label for="content">Content</label> {{ form.content }} <label class="mt-4" for="file" style="color: blue">attach a picture</label> <input type="file" name="file" id="file"> <!-- {{ form.image }} --> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> -
How to implement an HTML widget for a django model field?
I would like to add a field in Django models and I would like to make it a field which will allow me to add some simple html tags such as Bold/UL/OL from the Admin page? The following is a field in an app model: body = models.TextArea(max_length=400, null=True, blank=False) I wold like to add some HTML tags to the input for the field for example if I need to add the following text: This is a body for an article I would like to add an HTML widget to the admin page to be able to change the style of the body text so: This is a body for an article and the field content in the database should be: body = <bold>This is a body for an article<bold> -
Django - how to handle administration form submition?
I have articles that I manage via the admin section of Django. My problem here is that I need to modify a field right after the administrator submited the form before it goes into database. My specific need is to replace a part of a string with something else, but I don't know how to handle admin form submittions. -
self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found
I am integrating geodjango in my real estate website, and I am tired of this error. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\pytuts\appdata\local\programs\python\python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\pytuts\appdata\local\programs\python\python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\pytuts\appdata\local\programs\python\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\db\models\base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\pytuts\.virtualenvs\geodjango-webpage-6RyR6Y5t\lib\site-packages\django\db\models\options.py", line 208, in … -
UnicodeDecodeError: when trying to save image to the django model
I have this model: class MyModel(Model): other_field = CharField(max_length=200) image = ImageField(upload_to='images/', null=True, blank=True, ) I enter into the shell Python manage.py shell Then: import os from django.core.files import File my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage1.png' my_image1_file = File(open(my_image1_path )) from myapp.models import MyModel model_ins = MyModel.objects.get(id=1) model_ins.image.save('myimage1.png', my_image1_file ) I encounter this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I have another ins in my model and I encounter no error with that other image file: import os from django.core.files import File import os from django.core.files import File my_image1_path = 'C:\\Users\\Amin\\PycharmProjects\\myproject\\myimage2.svg' my_image1_file = File(open(my_image2_path )) from myapp.models import MyModel model_ins = MyModel.objects.get(id=2) model_ins.image.save('myimage2.svg', my_image2_file ) Any clue what is the problem with the image1?! -
Getting __str__ returned non-string error after adding a form on a page
I have a search bar. After search an order code I want to open a new page with order information and a new form for items at the same page. Searching and getting order information works great. But after add a new form to the page I'm getting an error TypeError at /paketle/ __str__ returned non-string (type NoneType) Here is my models: class Siparisler(models.Model): siparis_no = models.CharField(max_length=80) .. class Meta: verbose_name = "Sipariş" verbose_name_plural = "Siparişler" def __str__(self): return self.siparis_no class Urunler(models.Model): urun_adi = models.CharField(max_length=250,blank=True,null=True) barkod = models.CharField(max_length=60,blank=True,null=True) class Meta: verbose_name = "Ürün" verbose_name_plural = "Ürünler" ordering = ['pk'] def __str__(self): return self.urun_adi class Paket(models.Model): siparis = models.ForeignKey(Siparisler,on_delete=models.CASCADE,related_name='siparis_paket') urun = models.ForeignKey(Urunler,on_delete=models.PROTECT,related_name='urun_siparis_paket') miktar = models.CharField(max_length=6,blank=True,null=True) class Meta: verbose_name = "Paket" verbose_name_plural = "Paketler" ordering = ['-pk'] def __str__(self): return self.siparis.siparis_no my forms.py from django import forms from .models import Paket class PaketForm(forms.ModelForm): class Meta: model = Paket fields = '__all__' my views here: my views here: my views class Paketleme(CreateView): model = Paket template_name = "siparis_paketle.html" form_class = PaketForm success_url = '/paketara/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: sorgu = self.request.POST.get('sorgu') query = get_object_or_404(Siparisler, pazar_yeri_kargo_kodu=sorgu) context['object'] = query return context class Paketle(TemplateView): template_name = "paketleme.html" def get_context_data(self, **kwargs): context … -
uploading an un-known CSV file to Django Model
I am trying to build a analytics tool in which user will upload a CSV file from browser as input data - the schema is un-known to the system. The file content will get loaded to Django Model and persist to the SQLLite DB as provided by default with Django system. More over I don't want Form Submit as the page has many control present. I checked with CSV Import and Django adaptor both work on fixed schema (i.e. The model need to be predefined) but in my case I don't know what CSV file user may upload for analysis. Please help with the approach - and few sample code is preferable. ( Note : I don't want to upload the file like Image upload - Otherwise I could able to do so in a Media root). Please Help. -
Incomplete HTML via r.text from Django template with python-requests
I'm using python-requests to get HTML from a page and later extract some links from it. Here's the modified part of the function: # views.py import requests def my_function(request): page = requests.get("http://some/url") html = page.text print(html) When I execute my_function, the printed page.text doesn't contain part of the HTML code that should be visible on the page. It appears that the code that is missing is that is within {% block content %} {% endblock content %} in my template file. What is the reason for this and how can I fix it? (I'm using Python 3.8.2, Django 3.0.6, requests 2.23.0) -
Unable to get posts to show based on category (Django)
I'm having trouble getting posts to list in their respective categories on my forum. I'm able to get the posts to list when I don't specify a category, but when I do try to specify a category, no posts are shown. For example, {% for post in posts|slice:":4" %} will list the 4 most recent posts. Whereas {% for post in gen_discussion|slice:":4" %} shows nothing. Would anyone be able to advise a solution based on my below code? Forum HTML: <section class="container"> <div class="my-3 p-3 bg-white rounded shadow-sm"> <h5 class="border-bottom border-gray pb-2 mb-0 forum-category-header"> Recent Posts </h5> <!-- A list of recent posts will display here. Limited to 4 most recent posts --> {% for post in posts|slice:":4" %} <div class="media text-muted pt-3"> <p class="media-body pb-3 mb-0 small lh-125 border-bottom border-gray"> <strong class="d-block text-gray-dark margin-bottom-5" ><a href="{% url 'forum_post_details' post.id %}" >{{ post.title }}</a ></strong > {{ post.content|truncatewords:30 }} </p> <hr /> </div> {% endfor %} </div> <div class="my-3 p-3 bg-white rounded shadow-sm"> <h5 class="border-bottom border-gray pb-2 mb-0 forum-category-header"> General Discussion </h5> <!-- A list of recent posts in 'General Discussion' will display here. Limited to 4 most recent posts --> {% for post in gen_discussion|slice:":4" %} <div class="media text-muted … -
"for" loop and "placeholders" aren't working in HTML, Django
placeholders and for loop in HTML aren't working, {%for product in products%} , {{product.name}} I was following Denis ivy course from youtube, I also cloned his repository , still I'm facing this problem , -
Displaying user generated video in Django
I am making a web app in Django where a user clicks a button to create a unique video programmatically. The video should then display in their browser. I have set it up so the created videos are uploaded to a model and assigned ids (videoupload object 1,2 etc). How do I now tell Django which video file to play in my template for the user? -
Django Runtime Error list IndexError macOS to Windows
I'm working with my Team on a Django Project and we have a Problem. So two of us, me included are working on macOS. Our Code is working just fine on macOS and we pushed it on git. But the others that are working on windows are getting a list index out of range error. Everybody have the same Version.. Is it maybe because macOS and windows have different Library's? def getStand(self, getränk): with open("machine/Lagerverwaltung.csv", "r") as file: reader = csv.reader(file) next(reader) count = 0 for line in reader: count += 1 if count == getränk: return float(line[2]) else: continue Traceback: Watching for file changes with StatReloader Internal Server Error: / Traceback (most recent call last): File "C:\Users\-\AppData\Local\Programs\Python\Python38\lib\site- packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\-\AppData\Local\Programs\Python\Python38\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\-\AppData\Local\Programs\Python\Python38\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\-\Desktop\vending\vendingmachine\machine\views.py", line 17, in main context = {"cola": l.getStand(1), "fanta": l.getStand(2), "sprite": l.getStand(3), "pepsi": l.getStand(4), "limit": l.literLimit} File "C:\Users\-\Desktop\vending\vendingmachine\machine\views.py", line 154, in getStand return float(line[2]) IndexError: list index out of range [14/Jun/2020 12:45:56] "GET / HTTP/1.1" 500 77982 -
HTTP Basic auth web request in django
I am new to programming.. I used python to create code that gets data from an API using requests package and the request uses HTTPBasicAuth. Below is the request which works fine in genral python. response = requests.get(url,auth=HTTPBasicAuth('username','password'),stream=True Can some please advise how can I implement this in django. when I use the same code as below, it gives me an error as "name HTTPBasicAuth is not defined" def index(request): if request.method == "POST": url = urlname response = requests.get(url,auth=HTTPBasicAuth('username','password'),stream=True data = response.json() -
Django: how can i show the data of two or three models
hi working on a project where data is inherited from multiple models. I don't know how to show the data of multiple models of a particular user.this is my first model user 1. class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader", null=True) pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, default='') this is the second model where user2 add price on above post class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices', on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) status = models.BooleanField(default=False) this is third model of user2 of booking class Booking(models.Model): post = models.ForeignKey(price, related_name='b_post', on_delete=models.CASCADE, default='', null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') approved_price = models.BooleanField(default=False) -
Custom Django url path converter (comma separated integers)
I am trying to create custom path converter to parse following type of url: http://127.0.0.1:8000/archives/tvseries/129/delete-image/352,353, 354/ in order to extract comma separated integers list from last part of the url /352,353, 354/ and use it in the view in self.kwargs. My url config: register_converter(archives.converters.CommaSeparatedIntegersPathConverter, 'int_list') urlpatterns = [ path( 'tvseries/<int:series_pk>/upload-image/<str:filename>/', archives.views.FileUploadView.as_view(), name='upload' ), path( 'tvseries/<int:series_pk>/delete-image/<int_list:image_pk>/', archives.views.FileUploadView.as_view(), name='delete-image' ), ] converter in converters.py class CommaSeparatedIntegersPathConverter: regex = '^(\d+(,\d+)*)?$' def to_python(self, value): return [int(v) for v in value.split(',')] def to_url(self, value): return ','.join(map(str, value)) I keep receiving exception 404 on this configuration . Tried few regex I found in internet on comma separated integers list -same 404. Whats wrong? Thanks.