Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Should I use Node.js or Django for my application?
I'm planing to build a cross-platform app as my first big project. I'm not yet familiar with any of the former frameworks, but I am looking forward to learning them. So far I am familiar with C, C++ and Python. The app will function as following: User uploads a photo, from which text is extracted and stored in associated file (I want to process images on front end, because I can't afford to process everything on the back end) Data is sent to the back end where it is stored With machine learning, data is being analyzed and organized into new groups (in the future I also want to add some AI to find answers to questions posed in the written text on the image) User can access reorganized groups, answers, his profile... So basically I want to do heavy processing on front end; organize everything, enhance data and store profiles/images on back end; implement a smart organization system; be able to access everything again on front end in a package as addictive as Instagram. I know I can easily implement OpenCV and make machine learning algorithms in Python, but I don't know how to make that on front end; … -
Python library to use
I need fill the web application form so which library should I use in Python that help to automate the form filling of website. Python library to used for auto form filling . -
how to reset id whenever a row deleted in django?
i wanted to start id from 1 . whenever a row deleted it skips that number and jump to next number. like in this image it skips number from 1-6 and 8. i want to set it as 1,2,3 this is my models.py class dish(models.Model): id = models.AutoField(primary_key=True) dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) # dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to. dish_date = models.DateField() def __str__(self): return self.dish_name this is views.py def delete(request, id): dishs = dish.objects.get(id=id) dishs.delete() return HttpResponseRedirect(reverse('check')) -
Django toggle yes and no
I am having difficulty creating a toggle for Django. This Django is a Chores table listed from the description, category, and is_complete. The is_complete is what I am having trouble with. The toggle should be a href that when you click "yes" it will change to "no" Model.py class ChoresCategory(models.Model): category = models.CharField(max_length=128) def __str__(self): return self.category class Chores(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=128) category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) is_completed = models.BooleanField(default=False) I tried creating a view.py def toggle(request): -
Django channels consumer not receiving data
I'm trying to write a websocket consumer that gets all unread notifications as well as all notifications being created while the client is still connected to the websocket. I'm able to connect to the consumer and it's showing me all active notifications. The problem is that it doesn't show me new notifications when they're being created and sent from the model's save method. consumers.py class NotificationConsumer(WebsocketConsumer): def get_notifications(self, user): new_followers = NotificationSerializer(Notification.objects.filter(content=1), many=True) notifs = { "new_followers": new_followers.data } return { "count": sum(len(notif) for notif in notifs.values()), "notifs": notifs } def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name notification = self.get_notifications(self.scope["user"]) print("Notification", notification) self.accept() return self.send(text_data=json.dumps(notification)) self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) count = text_data_json['count'] notification_type = text_data_json['notification_type'] notification = text_data_json['notification'] print(text_data_json) await self.channel_layer.group_send( self.room_group_name, { "type": "receive", "count": count, "notification_type": notification_type, "notification": notification } ) models.py class Notification(models.Model): content = models.CharField(max_length=200, choices=NOTIFICATION_CHOICES, default=1) additional_info = models.CharField(max_length=100, blank=True) seen = models.BooleanField(default=False) users_notified = models.ManyToManyField("core.User", blank=True) user_signaling = models.ForeignKey("core.User", on_delete=models.CASCADE, related_name="user_signaling") def save(self, *args, **kwargs): if self._state.adding: super(Notification, self).save(*args, **kwargs) else: notif = Notification.objects.filter(seen=False) data = { "type": "receive", "count": len(notif), "notification_type": self.content, … -
instance in Django not working properly unable to get pre populate data
i am trying to populate the fileds in django automatically using the instance but its not working for me so someone help to solve this issue so here is the code def Editquestion(request): askit = askm.objects.get(question = "apple") print(askit) getformdata = editquestf(instance = askit) return render(request, "editquestpage.html", {'edit':getformdata}) -
Django filter queryset
Django framework has a product model with about ten values that need to be filtered (color, type..). I'm trying to create a filter like this: views: ` class FilterCctvView(QuerySetsFromCctv, ListView): paginate_by = 32 def get_queryset(self): queryset = Cam.objects.filter( Q(maker__in = self.request.GET.getlist("maker")) | Q(type_of_cam__in = self.request.GET.getlist("type_of_cam")) ) return queryset in html: <form action="{% url 'filter' %}" method = 'GET'> <ul> <p><strong>Manufacturers</strong></p> {% for cam in view.get_cctv_makers %} <li> <input type="checkbox" class="checked" name="maker" value="{{cam.maker}}"> <span>{{cam.maker}}</span> </li> {% endfor %} </ul> <ul> <p><strong>Type of cameras</strong></p> {% for cam in view.get_cctv_type %} <li> <input type="checkbox" class="checked" name="type_of_cam" value="{{cam.type_of_cam}}"> <span>{{ cam.type_of_cam}}</span> </li> {% endfor %} </ul> <button class="btn btn-success btn-sm" type="submit">Find</button> </form> ` enter image description here But the filter doesn't work correctly! How do I do this correctly? -
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 })