Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template: src attribute doesn't work
I've been doing some practice with Django and lately I ran into a problem that I can't solve. I'll give you some context. I have this models (I think you can just focus on the fact that the model has a gitUrl function): class AllTemplates(models.Model): categories = [ ('landing-page', 'landing-page') ] id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True) category = models.CharField( max_length=200, choices=categories, default='landing-page') url = models.CharField(max_length=500, null=True) def __str__(self): return self.name @property def templateNumber(self): try: number = self.id except: number = '' return number @property def templateTitle(self): try: title = self.name except: title = '' return title @property def imageURL(self): try: url = self.image.url except: url = '' return url @property def gitUrl(self): try: gitPath = self.url except: gitPath = '' return gitPath The purpose of this model is to keep all the templates I develop in the database. Each template has various fields including 'url', in which I store the github url where the template in question is located. What I can't do is: dynamically make each template have an html file, in which there is an iframe tag whose src attribute points to the github url. Here's what I tried to do. My urls.py … -
Doesn't generate logs file in django
I don't know what to do but nothing works, what could be the problem? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters':{ 'simple':{ 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': "%Y.%m.%d %H:%M:%S", }, }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'console_prod': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'filters': ['require_debug_false'], 'level': 'ERROR', }, 'console_debug':{ 'class': 'logging.StreamHandler', 'formatter': 'simple', 'filters': ['require_debug_true'], 'level': 'DEBUG', }, 'file': { 'class': 'logging.FileHandler', 'filename': BASE_DIR / 'logs/forum_api.log', 'level': 'INFO', 'formatter': 'simple', }, }, "loggers" : { "django": { "handlers": ["console_debug", "file"], }, }, } This error is not clear to me File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\logging\config.py", line 572, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'console_debug' -
encode problem when I use NamedTemporaryFile
I want to create a temporary file then send it to the client. The file I send has an encoding problem. I create a temporary file with the function NamedTemporaryFile(). When I put encoding="utf-8" to NamedTemporaryFile, I get this error: ** PermissionError: [WinError 32] The process cannot access the file because this file is in use by another process: 'C:\\..\\AppData\\Local\\Temp\\tmpglkdf_2o' ( When i don't write encoding="utf-8", all goes well, I can download the file but with encoding problem ) views.py from django.http.response import HttpResponse from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper import mimetypes import pandas as pd import pdb; def page(request): object = pd.DataFrame(data={"ColumnWithé": ["éà"]}) fileErr(request, object=object) def fileErr(request, object=None): # Create a temp file if(isinstance(object, pd.DataFrame)): print("========== IF ==========") #pdb.set_trace() f = NamedTemporaryFile(delete=False, encoding="utf-8") object.to_csv(f, sep=',') request.session["errpath"] = f.name.replace("\\","/") # Send the temp file when the user click on button else: print("========== ELSE ==========") #pdb.set_trace() filename="err.csv" file_path = request.session.get("errpath") response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')), content_type=mimetypes.guess_type(file_path)[0]) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "Attachment;filename=%s" % filename return response .html <a href="{% url 'downloadfile' %}"> urls.py urlpatterns = [path("download-file", views.fileErr, name="downloadfile"),] The result when i don't write encoding="utf-8" -
WHY AM I GETTING SUBPROCESS ERROR WHEN I TRY TO INSTALL CERTAIN DJANGO PACKAGES IN CPANEL?
I am trying to host my django application on cpanel. I have moved the project into the file manager and done all configurations. Now, I need to run some pip installs in the cpanel terminal and thats where the problem is. Whenever I try to do pip install django-allauth, I get a subprocess error and I dont know why. Django-allauth is not the only package that gives me this kind of error. psycopg2-binary does as well. SOLUTIONS THAT I HAVE ALREADY TRIED: i have upgraded pip, wheel and setup tools. I have changed the python versions being used for my project. I have changed the django versions as wel. yet, the problem persists. Please I really need help. -
Django Field 'id' expected a number but got 'autobiography'
I am working on a project that allows me to upload books to database and sort them by them their collection. The problem is that whenever i upload and try to filter out books from a particular collection i get the error Field 'id' expected a number but got 'autobiography' models.py class BookDetails(models.Model): collections = models.CharField(max_length=255, choices=COLLECTION, default="") class Meta: verbose_name_plural = "BookDetails" def __str__(self): return self.collections class Books(models.Model): """ This is for models.py """ book_title = models.CharField(max_length=255, default="", primary_key=True) book = models.FileField(default="", upload_to="books", validators=[validate_book_extension], verbose_name="books") collection = models.ForeignKey(BookDetails, on_delete=models.CASCADE, default="") class Meta: verbose_name_plural = "Books" def __str__(self): return self.book_title forms.py class BookInfo(forms.ModelForm): class Meta: model = BookDetails fields = ["collections",] class BookFile(BookInfo): book = forms.FileField(widget = forms.ClearableFileInput(attrs={"multiple":True})) class Meta(BookInfo.Meta): fields = BookInfo.Meta.fields + ["book",] views.py def books(request): if request.method == "POST": form = BookFile(request.POST, request.FILES) files = request.FILES.getlist("book") try: if form.is_valid(): collection = form.save(commit=False) collection.save() if files: for f in files: names = str(f) name = names.strip(".pdf") Books.objects.create(collection=collection, book_title=name, book=f) return redirect(index) except IntegrityError: messages.error(request, "value exist in database") return redirect(books) else: form = BookFile() return render(request, "books.html", {"form":form}) def test(request): data = Books.objects.filter(collection="autobiography") template = loader.get_template('test.html') context = {"data":data} return HttpResponse(template.render(context, request)) so basically what i am trying … -
Django Model Data Only To XML
I have this simple model class TestData(models.Model): rcrd_pk = models.AutoField(primary_key=True) Name = models.CharField(max_length=50) desc = models.CharField(max_length=300, blank=True, null=True) I want to get XML of model data. so I have written this code from sms_api.models import TestData from django.core import serializers data = TestData.objects.all() XmlData = serializers.serialize("xml",data) print (XmlData) This code Export XML like this: <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="sms_api.testdata" pk="1"> <field name="Name" type="CharField">Roqaiah</field> <field name="desc" type="CharField">Rogaiah is Old Arabic Name</field> </object> <object model="sms_api.testdata" pk="2"> <field name="Name" type="CharField">Khadeejah</field> <field name="desc" type="CharField">Kahdejah is an Arabic Name</field> </object> </django-objects> This way exported the Model with datatypes and others unwanted deteails. I want the ouput to be simple like so <?xml version="1.0" encoding="utf-8"?> <django-objects"> <object> <Name>Roqaiah</Name> <desc>Rogaiah is Old Arabic Name</desc> </object> <object> <Name>Khadeejah</Name> <desc>Kahdejah is an Arabic Name</desc> </object> </django-objects> The last Thing if I can change the tags of the xml, so those tags <django-objects> <object> can be <RowSets> <Row> -
How to give a post (in a forum) a tag (django-taggit) with checkboxes?
In my Web Forum I have an add Post Page it looks like this: How can I get all clicked tags as a django-taggit object or whatever then send them to my backend and save them in the database? My views.py looks like that: def post_question_tags(request): current_user = request.user if request.method == "POST": Post.objects.create(title = request.POST["title"], description = request.POST["description"], tags = request.POST["tags"], author = current_user) all_tags = Tag.objects.all() return render(request, "post_question_tags.html", {'all_tags' : all_tags, 'current_user': current_user}) My Template <div class="tags"> {% for tag in all_tags %} <div class="tag"> <p class="tag-title">{{ tag.name }}</p> <input type="checkbox" class="checkbox-button" name="checkboxes" value="{{ tag.name }}" /> <p class="description">{{ tag.description }}</p> </div> {% endfor %} </div> -
class "is not defined" in django models that rely on eachother
I have two classes in my models.py. If I change the order I define the classes it makes no difference and at least one of them give an error about something not being defined. class Item(models.Model): offers = models.ManyToManyField(Bid) class Bid(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) -
How to fix MultiValueDictKeyError in django
This is my form <h1>ADD LIST</h1> <form action="addList/" method="post"> {% csrf_token %} <div class = "container"> <label>List Name</label><br> <input name="listname" class= "listNamec"><br><br></input> <label>List title</label><br> <input name="listtitle" class= "listTitlec"><br><br></input> </div> </form> And this my function def addList(response): listname = response.POST['listname'] list.name = listname list.save() return render(response, 'main/index.html', {}) error : raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'listname' i need to add these to Todolist database, and not workin :( -
Django Channels with Angular 14 Frontend
is there a way to create a socket with django and a angular 14 frontend? I've tried that with ngx-socket-io, but its not working so far. Any ideas how to solve this issue? I need to "poll" status from multiple celery tasks, so it's not effective to call the backend n (n=quantity of tasks) every x seconds to get the latest status. -
django_quill.quill.QuillParseError: Failed to parse value
Getting an error on my local server when testing using django-quill-editior for blogs in my project. I can't find out what the following error means. "django_quill.quill.QuillParseError: Failed to parse value" I do have .html|safe at the end of my codes, and the weird thing is that this is all working in my production version. Any body else experienced this error? -
Django: How to store data in Form #1 while filling up Forms #2 and #3 and import data from Forms #2 and #3 into Form #1?
I have a Vinyl model form (Form #1) that creates vinyl with the following fields: artist (ManyToManyField), title, record label (ForeignKey), cat.number, release date, cover art, price, genre, style, tracklist, quantity, and condition. Under artist and record label there are buttons that allow the user to create new entities. When pressing the "Add new artist" button, a new form (Form #2) is shown and I would like to have the already added data in Form 1 to be preserved and get the data from Form #2 populated into Form 1. Example: The artist I'm looking for is not on the list of artists in Form 1. I click "Add new artist" and Form #2 appears. I fill in the data and when clicking submit, I get redirected to Form #1. I want this new artist to be autoselected. Then I write the title. Then I see that the record label is not on the list of record labels so I click "Add new label". Form #3 is shown and I fill in the data. When clicking the submit button I'm redirected to Form #1. I would like to have all the previously added data and also the newly generated record … -
How to pass two parameters to the url for correct operation
How to pass two parameters to the url for correct operation through views classes (It seems to me that the error in views.py , also in template).The form is also used here to convey questions, this can be seen in html, but you need to abstract from the form views.py` class Question(LoginRequiredMixin, DetailView): model = Question context_object_name = 'questions' template_name = 'question.html' def get_queryset(self): return get_object_or_404(Question, quiz__slug=self.kwargs['quiz_slug'], quiz__pk=self.kwargs['pk']) ` question.html ` {% extends 'base.html' %} {% load static %} {% block content %} {{ questions }} <form action="{% url 'questions' quiz_slug pk %}" method="post"> {% for answer in questions.answers.all %} <div class="form-group"> <input type="checkbox" id="{{ answer.pk }}" name="{{ answer.pk }}" value="{{ answer.is_correct }}"> {{ answer }} </div> {% endfor %} <input href="{% url 'home' %}" class="btn btn-info btn-block badge-success" type="submit" value="Ответить"> {% csrf_token %} </form> {% endblock content %} urls.py `` path('', views.HomeListView.as_view()), path('category/<int:pk>', views.TestsListView.as_view(), name='tests'), path('test/<slug:quiz_slug>/question/<int:pk>', views.Question.as_view(), name='questions'), ] ` models.py ` class Category(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) class Quiz(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=255, default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) class Question(models.Model): STATUS_CHOICES = ( ('one_answer', 'One_answer'), ('multiply_answers', 'Multiply_answers') ) question = models.TextField() question_type = models.CharField(max_length=20, choices=STATUS_CHOICES) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, … -
How to disable downloading static files like pdf, videos in Django
I want to develop an application using Django DRF and react JS, the app would like udemy which should access the videos online but could not download it, I am looking for a good solution and idea to disable the file downloads. There are two kinds of files PDF VIDEO I think that I should store the file directly to database, not their path -
page not found when trying to access a site deployed on netlify
i made a project related to the creation of a book site and I uploaded it to github, then I deployed it to Netlify,iam trying to view my site ,all i see a error message Page Not Found Looks like you've followed a broken link or entered a URL that doesn't exist on this site. Back to our site If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips. what should be the reason i do everything,i by a domain i do it hen i wite index.html _redirects ama nothing this is my github rebo:https://github.com/GOCTIRONE/demo2000 and my netlify site:https://juliaxhabrahimi.cloud my deploy setings:4:58:16 PM: build-image version: 4c0c1cadee6a31c9bb8d824514030009c4c05c6a (focal) 4:58:16 PM: build-image tag: v4.15.0 4:58:16 PM: buildbot version: e6d57a43d406fdcaf8ee2df93f280acce2e07259 4:58:17 PM: Fetching cached dependencies 4:58:17 PM: Starting to download cache of 91.6MB 4:58:17 PM: Finished downloading cache in 618.519356ms 4:58:17 PM: Starting to extract cache 4:58:17 PM: Finished extracting cache in 84.726724ms 4:58:17 PM: Finished fetching cache in 759.256113ms 4:58:17 PM: Starting to prepare the repo for build 4:58:17 PM: Preparing Git Reference refs/heads/master 4:58:18 PM: Parsing package.json dependencies 4:58:18 PM: Section completed: initializing 4:58:19 PM: No … -
How to delete and update posts with a ForeignKey field?
Help! Browsed the entire internet There are two models. The Source model has a ForeignKey on the Groups table. How to properly delete or update an object from the Sources table via DeleteView and UpdateView? class Groups(models.Model): slug = models.SlugField('Url group') title = models.CharField('Name', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_groups', kwargs={'slug': self.slug}) def get_success_url(self): return reverse('list_groups', kwargs={'slug': self.slug}) class Sources(models.Model): group = models.ForeignKey(Groups, on_delete=models.CASCADE, verbose_name='Group', blank=True, null=True,) plug = models.SlugField('Url source') title = models.CharField('Name', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail_sources', kwargs={'slug': self.group.slug, 'plug': self.plug} Clicking on a link gives a 404 error path('list_groups/<slug>/<slug:plug>update', views.UpdateSources.as_view(), name='update_sources'), Tried everything!!!! -
Can I use a prevent default at a form that uses GET as a method in the Django HTML template?
I’m looking to create a section about searching for some movies in my database, however, this section is at the bottom of my page. However, when I search and find the movie that I was looking for, the page refreshed. Also, I do not know if “GET” is the ideal method for secure sections, but I read that POST is necessary just for database changes. In this case, I just want to bring the movie corresponding to what was searched at a search bar. This is my view and I am getting the search like this, in the context, to make it easier to render. It is working ok. class MoviesPage(TemplateView): template_name = "tailwind/movies-page.html" def get_context_data(self, **kwargs): context = super(MoviesPage, self).get_context_data(**kwargs) # Top Movies' section movies = Movies.objects.filter( name__in=[ 'Oldboy', 'Parasite', 'Lady Vengeance', ] ) context['movies'] = movies # Movie search's section query = self.request.GET.get('q', default='oldboy') results = Movies/.objects.filter(Q(name__icontains=query)) context['results'] = results This is my form in my HTML template: <form action="" method="GET" id="search-package-form" > <input type="search" name="q" placeholder="oldboy" /> <div> <button type="submit" > <span>Search</span> </button> </div> </form> {% if results %} <div> {% for movie in results %} <ul> <li>{{ movie.name }}</li> </ul> {% endfor %} </div> {% else … -
Creating a new empty directory folder with the record id number on the desktop for each record added with the form in Django
First of all, my english is not very good, sorry for that. I only have one field in my model. I want to create an empty directory folder on the desktop while creating a record using the form. Since I am new to Django, I would be grateful if you could write the complete codes. Thank you very much in advance. MODELS.PY class DosyaBilgileri(models.Model): sahisAdi = models.CharField(max_length=50, verbose_name='Şahıs Adı') def __str__(self): return self.sahisAdi def delilIndex(request): VIEWS.PY def delilIndex(request): dosyaEkleFormu = DosyaBilgileriModelForm(request.POST or None, files=request.FILES or None) if dosyaEkleFormu.is_valid(): dosyaEkleFormuD = dosyaEkleFormu.save(commit=False) dosyaEkleFormuD.save() messages.add_message(request, messages.INFO, 'Dosya ekleme işlemi başarıyla tamamlandı.') return redirect('delilIndex') return render(request, 'delil/index.html', {'dosyaEkleFormu':dosyaEkleFormu }) -
Django Rest Framewrok: got KeyError when write test for creating (post) nested serializer
I'm try to write test for creating sales data keep getting KeyError: 'content' when running python manage.py test. the test is to ensure user can add/create sales data with its details (nested) with this as reference to create writeable nested serializers models.py # abstract base table for transactions class Base_transaction(models.Model): is_paid_off = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) pass class Meta: abstract = True # sales table to store surface level sales information # consist of sales_id as pk, customer_name, sub_total, discount, user_id, # total, is_paid_off, created_at, updated_at class Sales(Base_transaction): sales_id = models.BigAutoField( primary_key=True, unique=True ) customer_name = models.CharField(max_length=25, blank=True) customer_contact = models.CharField(max_length=13, blank=True) user_id = models.ForeignKey( User, on_delete=models.PROTECT, null=True, db_column='user_id' ) def __str__(self) -> str: return f'{self.sales_id} at {self.created_at} | Lunas={self.is_paid_off}' class Meta: db_table = 'sales' # sales_detail table store the detail of sales per sparepart # consist of sales_detail_id as pk, quantity, individual_price, total_price # sales_id class Sales_detail(models.Model): sales_detail_id = models.BigAutoField( primary_key=True, unique=True ) quantity = models.PositiveSmallIntegerField() is_grosir = models.BooleanField(default=False) sales_id = models.ForeignKey( Sales, on_delete=models.CASCADE, db_column='sales_id' ) sparepart_id = models.ForeignKey( 'Sparepart', on_delete=models.SET_NULL, null=True, db_column='supplier_id' ) def __str__(self) -> str: return f'{self.sales_id} - {self.sparepart_id}' serializers.py class SalesDetailSerializers(serializers.ModelSerializer): sparepart = serializers.ReadOnlyField(source='sparepart_id.name') class Meta: model = Sales_detail fields = ['sales_detail_id', … -
Can't send a post requests
Hi everyone, I'm trying to send a post request through my localhost, my data is a json object, and my following code is: result = df_yahoo.get_history_data() df_yahoo_json = result.to_json() # Convert the Dataframe to JSON headers = { "Content-Type": "application/json", } # Send the POST request with the JSON data response = requests.post('https://localhost:8000/api_yahoo', json=df_yahoo_json, headers=headers) I try to send the request, and then I got the following error: requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)) I send the request through the views file in Django. After converting the Dataframe to JSON, I see that the Type of df_yahoo_json is str and not dict of JSON. I would appreciate your help, thank you. -
Django multiple sites using nginx and gunicorn
I am serving multiple websites using nginx and gunicorn and I would like to add another one. Sadly my lack of experience is limiting me, I have some experience with webdesign but always struggle on the server side...|-( (I am using Django because of my Python preference in scientific analysis). My problem: The new site seems to refer to the port used by another. Checking the gunicorn status I see that the site is running although nginx seems to be unable to refer to the correct Django folder. Could someone point me in the right direction? I have been looking around for the last hour or so... (I didn't include any code for now as I am not sure where the error might lie at this point...) -
Filter over jsonfiled with unknown keys in Django ORM
There is a model with JSONfield in Django model: class MyClass(models.Model): is_info = models.BooleanField() info = models.JSONField() The data inside table is like: is_info info false true {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} And I need to filter somehow a query set to receive a set of rows where compound key 'search_key'='text' and not include in result values from 'info' field where 'search_key' has some other values. My keys of 'info' field (key123, key456 and etc.) are always different and I don't know the exact value. Please, help me!!!) I've tried: q = queryset.filter(info__icontains='text') but it return for me all the field info: {'key123':{'a':'1', 'b':'2', 'search_key':'text'},'key456':{'a':'1', 'b':'2', 'search_key':'another_value'}} when I need to receive only: {'key123':{'a':'1', 'b':'2', 'search_key':'text'}} -
How to use objects.filter for (one-to-many) releation
I have 3 tables: Job, Flight, and Image One job can have multiple flights and a flight can have only one job. And a flight can have many images. I get all flights related to the job using the query: flights = Flight.objects.filter(job_id=job_id) and now I want all images in those flights to call a function for all images but I couldn't implement it without a loop: for flight in flights: images = Image.objects.filter(flight=flight) data = process_images(images) I want something like: images = Image.objects.filter(flight=flights) so I call process_images only once, is that possible? -
Not able to retrieve variable in template in Django ajax call
I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct. JS ajax func $(".pos").click(function(){ counter=counter+1; $(".add").html('add counter '+counter); $.ajax( { url :'page', type :'get' , data:{ quantity: counter }, success:function(response){ console.log(response); } } ); My view def page(request): counter=request.GET.get('quantity') print(counter) ## this is printing fine return render(request,'page.html',{'counter':counter}) html template <body> {{counter}} <button class="btn neg" name="neg-btn">-</button> <button class="btn add" name="add-btn" >add to box</button> <button class="btn pos" id="test" name="pos-btn">+</button> </body> getting this counter as None -
FileNotFoundError at / [Errno 2] No such file or directory while saving an image
I want to create a qr-code generator for hashed values. However, it works pretty strange, because sometimes everything works good, but sometimes it gives me an error: FileNotFoundError at / [Errno 2] No such file or directory. For example, it can save a few qr-codes and then throw that error. Here is the code: def qr_creator(request): for i in range(50): hash_uuid = uuid.uuid4 hash = Hasher.encode(self=Hasher(), password=hash_uuid, salt=Hasher.salt(self=Hasher())) data = f"{hash}" img = make(data) img_name = f"{hash}.png" img.save(str(settings.MEDIA_ROOT) + '/qr_codes/' + img_name) return HttpResponse("Done!") As I understand, the problem lies in img_name as if I change it for example, like this: img_name = f"{hash}.png", everything works as it should be. But I need my qr-codes to be named strictly as hash values. So my question is how can I fix this so I can save my qr-codes with its values? Thanks in advance