Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
version_id shows as null when creating a verse
Whenever I try to create a new verse, version_id appears as null in the payload under the network tab in dev tools, and this error also appears: POST http://localhost:8000/verses 500 (Internal Server Error). But when I console warn it it shows the correct information. VerseForm const initialState = { verse: '', content: '', version_id: { id: 0, label: '', }, }; const handleSubmit = (e) => { e.preventDefault(); console.warn('currentVerse.version_id:', currentVerse.version_id); if (verseObj.id) { updateVerse(user, currentVerse, verseObj.id) .then(() => router.push('/')); } else { const payload = { ...currentVerse }; createVerse(payload, user).then(setCurrentVerse(initialState)) .then(() => router.push('/')); } }; return ( <Form className="form-floating" onSubmit={handleSubmit}> <h2 className="text-black mt-5">{verseObj.id ? 'Update' : 'Create'} a Verse</h2> <FloatingLabel controlId="floatingInput1" label="Book, Chapter & Verse" className="mb-3"> <Form.Control type="text" placeholder="Book, Chapter & Verse" name="verse" value={currentVerse.verse} onChange={handleChange} required /> </FloatingLabel> <FloatingLabel controlId="floatingInput1" label="Content" className="mb-3"> <Form.Control type="text" placeholder="Content" name="content" value= {currentVerse.content} onChange={handleChange} required /> </FloatingLabel> <Form.Group className="mb-3"> <Form.Select onChange={handleChange} className="mb-3" name="version_id" value= {currentVerse.version_id.id} required> <option value="">Select a Version</option> {versions.map((version) => ( <option key={version.id} value={version.id}> {version.label} </option> ))} </Form.Select> </Form.Group> <Button type="submit" disabled={!currentVerse.version_id}> {verseObj.id ? 'Update' : 'Create'} Verse </Button> </Form> ); } VerseForm.propTypes = { verseObj: PropTypes.shape({ id: PropTypes.number, verse: PropTypes.string, content: PropTypes.string, version_id: PropTypes.shape({ id: PropTypes.number, label: PropTypes.string, }), }), user: PropTypes.shape({ … -
Troubleshooting an empty HTML console log bar in Django with Python asyncio
HTML console log bar is empty. I was trying to redirect the log messages from my terminal to an HTML console log on my Django webpage. the console log bar is created in the html page but is empty, not showing the log messages. i wanted to create a log console on upload.html that simply redirects each and every message that comes in my terminal of vscode to html. I tried the following code: in views.py: def home(request): return render (request, 'index.html') tracemalloc.start() ws_connection = None log_queue = asyncio.Queue() async def log_consumer(): while True: message = await log_queue.get() if ws_connection is not None: await ws_connection.send(message) def progress_callback(message, progress): sys.stdout.write(message + ' Progress: ' + str(progress) + '%\n') sys.stdout.flush() asyncio.create_task(log_queue.put(f"{message} Progress: {progress}%")) def calculate_features(file_path): total_steps = 10 completed_steps = 0 # Use os.path.abspath to get the absolute file path file_path = os.path.abspath(file_path) MERGED_DATAFRAMES = [] with open(file_path) as fasta_file: parser = fastaparser.Reader(fasta_file) seq_num = 1 ID_list = [] list_data = [] for seq in parser: ID = seq.id sequence = seq.formatted_fasta() sequence1 = seq.sequence_as_string() ID_list.append(ID) df_ID = pd.DataFrame(ID_list, columns=['ID']) completed_steps += 1 progress=int((completed_steps / total_steps) * 100) progress_callback(f"Sequence {ID} uploaded successfully", progress) return progress async def log(request): global ws_connection websocket = … -
Sorting warnings by accumulated count and date within a specified date range in Django
I have a Django project where I need to sort warnings based on the accumulated warning count (warning_count) and the date (date) within a specified date range (start_date and end_date). Here is my code: class LatestWarningListView(generics.ListAPIView): serializer_class = LatestWarningSerializer pagination_class = ListPagination filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] filterset_fields = ['student__school_year', 'student__attending', 'type'] search_fields = ["student__name"] ordering_fields = ['date', 'warning_count'] permission_classes = [IsTeacher] def get_queryset(self): self.pagination_class.page_size = 10 start_date_str = self.request.query_params.get('start_date', None) end_date_str = self.request.query_params.get('end_date', None) start_date = parse_date(start_date_str) if start_date_str else None end_date = parse_date(end_date_str) if end_date_str else None latest_warning = Warning.objects.filter(student=OuterRef('pk')).order_by('-date') if start_date: latest_warning = latest_warning.filter(date__gte=start_date) if end_date: latest_warning = latest_warning.filter(date__lte=end_date) students = Student.objects.annotate(latest_warning_id=Subquery(latest_warning.values('id')[:1])) warning_ids = [student.latest_warning_id for student in students if student.latest_warning_id is not None] warnings = Warning.objects.filter(id__in=warning_ids) return warnings class LatestWarningSerializer(serializers.ModelSerializer): student_name = serializers.SerializerMethodField() warning_id = serializers.IntegerField(source='id', read_only=True) student_id = serializers.IntegerField(source='student.id', read_only=True) warning_count = serializers.SerializerMethodField() class Meta: model = Warning fields = ['student_id', 'student_name', 'warning_id', 'type', 'date', 'content', 'warning_count'] def get_student_name(self, obj): return obj.student.name def get_warning_count(self, obj): start_date_str = self.context['request'].query_params.get('start_date', None) end_date_str = self.context['request'].query_params.get('end_date', None) start_date = parse_date(start_date_str) if start_date_str else None end_date = parse_date(end_date_str) if end_date_str else None warnings = Warning.objects.filter(type='경고', student=obj.student) if start_date: warnings = warnings.filter(date__gte=start_date) if end_date: warnings = warnings.filter(date__lte=end_date) return warnings.count() However, the … -
Not able to change IST to UTC
Current IST (Asia/Kolkata) is 5:23 PM and UTC is 11:53 AM same day. I wanted to convert IST to UTC. I tried following: from dateutil import tz from datetime import datetime from_zone = tz.gettz('IST') # also tried tz.gettz('Asia/Kolkata') to_zone = tz.gettz('UTC') t = datetime.strptime(t, '%Y-%m-%d %H:%M') t = t.replace(tzinfo=from_zone) t = t.astimezone(to_zone) print(t.strftime('%Y-%m-%d %H:%M')) Above still prints '2023-06-04 05:23'. That is no time zone change happened. Why is this so? -
Is there a way to exclude fields in nested serializers with a dictfield?
I am trying to serialize a dictionary in the structure of: dict = {'outer_dict': {'inner_dict1': {'key1': 'value1', 'key2': 'value2'}, 'inner_dict2': {'key3': 'value3', 'key4': 'value4'}}} But want to exclude key1 from my Response(dictserializer.data) I have tried to accomplish it like this class InnerDictSerializer(serializers.Serializer): key1 = serializers.CharField() key2 = serializers.CharField() def to_representation(self, instance): data = super().to_representation(instance) excluded_fields = ['key1'] for field in excluded_fields: data.pop(field, None) return data class DictSerializer(serializers.Serializer): dict = serializers.DictField(child=InnerDictSerializer()) Which successfully eats the dictionary data, but the to_representation of the InnerDictSerializer is not called and thus in the dictserializer.data the key1 information is given. After digging through the django source code I realized it is due to the kwarg 'data=..' of InnerDictSerializer not being given, but I have gained no information about how I could intercept the proccess and give it to the serializer or achieve the result in another way. While going through the sourcecode I am puzzled about when the to_representation method of a field is called in any case? In addition the default of django seems to be to make an ordereddict of it. For easier testing and due to not needing the order I would like to customize it to make a defaultdict of the … -
"DATETIME_INPUT_FORMATS" doesn't work in Django Admin while "DATE_INPUT_FORMATS" and "TIME_INPUT_FORMATS" do
I use DateTimeField(), DateField() and TimeField in MyModel class as shown below: # "models.py" from django.db import models class MyModel(models.Model): datetime = models.DateTimeField() # Here date = models.DateField() # Here time = models.TimeField() # Here Then, I set DATE_INPUT_FORMATS and TIME_INPUT_FORMATS and set USE_L10N False to make DATE_INPUT_FORMATS and TIME_INPUT_FORMATS work in settings.py as shown below: # "settings.py" LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False # Here USE_TZ = True DATE_INPUT_FORMATS = ["%m/%d/%Y"] # '10/25/2006' # Here TIME_INPUT_FORMATS = ["%H:%M"] # '14:30' # Here Then, DATE_INPUT_FORMATS and TIME_INPUT_FORMATS work in Django Admin as shown below: Next, I set DATETIME_INPUT_FORMATS and set USE_L10N False to make DATETIME_INPUT_FORMATS work in settings.py as shown below: # "settings.py" LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = False # Here USE_TZ = True DATETIME_INPUT_FORMATS = ["%m/%d/%Y %H:%M"] # '10/25/2006 14:30' But, DATETIME_INPUT_FORMATS does not work in Django Admin as shown below: In addition, from a MyModel objcet, I get and print datetime, date and time and pass them to index.html in test() in views.py as shown below: # "views.py" from django.shortcuts import render from .models import MyModel def test(request): obj = MyModel.objects.all()[0] print(obj.datetime) # 2023-06-04 08:49:09+00:00 print(obj.date) … -
Django checkboxes not saving to database: What am I doing wrong?
Value of checkbox when clicked is not saved in database Django. I am creating a website to track the progress of printing a book. The data is not being saved in the database and i don't know why. I have a table called Book which is working perfectly and another table called Progress which has the progress steps. In my template, I want to have the progress steps as checkboxes and the user clicks on the checkbox when that step is done (like how a to-do list works for example) My problem is that when I click on the checkbox , nothing happens. Models.py class Book(models.Model): BookName=models.CharField(max_length=200) Author=models.CharField(max_length=100) CopiesNum=models.IntegerField() PartsNum=models.IntegerField() CoverType=models.CharField(max_length=100) PaperType=models.CharField(max_length=100) BookSize=models.CharField(max_length=100) BookCompletion=models.IntegerField(null=True) def __str__(self): return str(self.id) class Progress(models.Model): BookID=models.ForeignKey(to=Book,on_delete=models.CASCADE,null=True,related_name='BookID') BookName=models.CharField(max_length=200,null=True) ISBNsent=models.BooleanField(default=False) ISBN_sentDate=models.DateField(null=True) ISBNdelivered=models.BooleanField(default=False) ISBN_deliveredDate=models.DateField(null=True) DepositNum=models.CharField(max_length=50,null=True) ISBN=models.CharField(max_length=50,null=True) Template: (note I just tried on the first checkbox) div class="container " dir="rtl"> <div class="section"> <div class="columns is-3 "> <!--############## FIRST COLUMN CARD ##############--> <div class="column"> <div class="card"> <header class="card-header is-info"> <p class="card-header-title is-centered"> رقم الايداع </p> </header> <div class="card-content" dir="rtl"> <form action="bookSteps" method="post"> {% csrf_token %} <div class="columns is-mobile"> <div class="content column is-5"> <label class="checkbox" dir="rtl"> **<input type="checkbox" name="ISBNsent" id="ISBNsent" value="True" onclick="this.form.submit({book_id:book_page.book_id})">** تم التسليم </label> </div> <div class="content column "> <label … -
Font awsome icons are not showing
In return () i used fa fa-pencil-square and fa fa-trash-o but icons are not showing kindly provide solution why its not showing the particular icons from font awsome import { useState, useEffect } from "react"; import { ListGroup, Card, Button, Form } from "react-bootstrap"; import API from "./API"; <tbody> {movies.map((movie, index) => { return ( <tr key=""> <th scope="row">{movie.id}</th> <td> {movie.name}</td> <td>{movie.genre}</td> <td>{movie.starring}</td> <td> <i className="fa fa-pencil-square text-primary d-inline" aria-hidden="true" onClick={() => selectMovie(movie.id)} ></i> <i className="fa fa-trash-o text-danger d-inline mx-3" aria-hidden="true" onClick={() => onDelete(movie.id)} ></i> </td> </tr> ); })} </tbody> </table> </div> </div> </div> ); }; export default AddMovie; kindly provide solution -
Apache showing the static and media file directory
I am hosting a django website on digital ocean using the apache server. And using the apache to sever my static and media files. For that i have edited the 000-default.conf file as follow `<VirtualHost *:80> ServerAdmin webmaster@localhost #DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:war Alias /static /var/www/project/staticfiles <Directory /var/www/project/staticfiles> Require all granted </Directory> Alias /media /var/www/project/media <Directory /var/www/project/media> Require all granted </Directory> <Directory /var/www/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess project python-home=/var/www/projenv python-path=/var/www/techshark WSGIProcessGroup project WSGIScriptAlias / /var/www/project/project/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined` this work fine, but when i visit the ip/static/ or ip/media/ on the browser, it shows the static and media directory to the user which i do not want. Can any one please help me to sever the static and media files without showing all the directory path to the users. -
How to override the view signup class in Django-Allauth to redirect the user to an error page when the form is not valid?
Does anybody know how to override view signup class (when form is not valid need redirect to some page)? class AccountSignupView(SignupView): template_name = 'example.html' form_class = UserSignupForm #if form field email is_valid its ok #else: #redirect('error-email.html') -
Checking if varchar column value containing IP address is in subnet
In SQL (tried in pgAdmin) I am able to do SELECT * FROM ... WHERE inet(s.ip_address) << `10.0.0.2/24` I tried to convert it to django ORM code which contained following: ... .filter(ip_address__net_contained=subnet_mask) But I am getting Unsupported lookup 'net_contained' for CharField I understand that this is because s.ip_address is of type varchar. In SQL, I am explicitly converting it to IP using inet(). How do I do the same in django ORM? Does this thread say its is unsupported? -
During mysqlclient installation I get this error
When I try to install mysqlclient, I usually get this error and don't know how exactly to solve this error. I tried many times and searched a lot about the error on google and youtube but they didn't help me. Is anyone to solve this error for me? if yes please help me -
Django model field name suggestions (autocomplete) in VSC
Is it possible to have in VSC help text during creation of object? Example: class Fruit(models.Model): name = models.CharField(max_length=100, unique=True) and now somewhere else in code: Fruit.objects.create(>>> dropdown suggestions of possible field names of Fruit model here fe. 'name') -
django many to many form not show model str
Models.py class Person(models.Model): name = models.CharField(max_length=128) email = models.EmailField(max_length=128, unique=True) courses = models.ManyToManyField('Course', through='Membership') def __str__(self): return self.email class Course(models.Model): title = models.CharField(max_length=128, unique=True) members = models.ManyToManyField(Person, through='Membership') def __str___(self): return self.title class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) Form.py class PersonForm(forms.ModelForm): class Meta: model = Person fields = ['name', 'email','courses'] courses = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple) Views.py class CourseFormView(generic.CreateView): model = Course fields = ['title'] class PersonFormView(generic.CreateView): model = Person fields = '__all__' reverse_lazy('hello:cookie') preview here Why the html that render show Object. How can I show the course title in that form I try to show course title in user view. -
Error seen when adding data to new model due to possible id issue
I am using Django and MongoDB. I have two models that are very similar. I decided to make a second one as a "v2" for some testing before wiping out my original. After I created it and then started to test it I noticed that it was not getting a id field added to it automatically like the original model is. Models: # Old Model (works) class Commands(models.Model): client_id = models.IntegerField(blank=False, default=None) command_id = models.CharField(max_length=100, default='') command_name = models.CharField(max_length=1024, blank=False, default='') command_status = models.CharField(max_length=32, default='') command_error = models.CharField(max_length=8, default = '0') command_response = models.TextField(default='') command_timestamp = models.BigIntegerField(default=0) # New Model class Command(models.Model): name = models.CharField(max_length=1024, blank=False, default='') status = models.CharField(max_length=1024, blank=False, default='') error = models.CharField(max_length=1024, blank=False, default='') response = models.CharField(max_length=1024, blank=False, default='') timestamp = models.CharField(max_length=1024, blank=False, default='') client = models.CharField(max_length=1024, blank=False, default='') kind = models.CharField(max_length=1024, blank=False, default='') Serializers # Old Serializer (works) class CommandSerializer(serializers.ModelSerializer): class Meta: model = Commands fields = ('id', 'client_id', 'command_name', 'command_status', 'command_error', 'command_response', 'command_timestamp', 'command_id', ) # New Serializer class CommandSerializer2(serializers.ModelSerializer): class Meta: model = Command fields = ('id', 'name', 'status', 'error', 'response', 'timestamp', 'client', 'kind', ) URLS # Old URL re_path(r'^api/addcommand$', views.add_command), # New URL path("test/add", views.CommandCreate.as_view()) Views # Old View @api_view(['POST']) def add_command(request): command_data … -
How to update post with multiple images in django templates
i have two models 1-post 2-postimage so the post can have multiple images so I'm having a trouble to update the post and its images in my templates i did like upload multiple images when i create a post put i dont know how to do it with the update post so can any one show me how to do it or give me a tutorial link Because I searched alot and couldn't find any tutorials this is my models class Post(models.Model, HitCountMixin): ch = [ ('pvp','pvp'), ('Default','Default'), ('bedrock','bedrock') ] xch = [ ('x1','x1'), ('x4','x4'), ('x8','x8'), ('x16','x16'), ('x32','x32'), ('x64','x64'), ('x128','x128'), ('x256','x256'), ('x512','x512'), ] vch = [ ('1.7','1.7'), ('1.8','1.8'), ('1.9','1.9'), ('1.10','1.10'), ('1.11','1.11'), ('1.12','1.12'), ('1.13','1.13'), ('1.14','1.14'), ('1.15','1.15'), ('1.16','1.16'), ('1.17','1.17'), ] author = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() mainimage = models.ImageField(null=True ,upload_to=thumbnail_upload_to) rpfile = models.FileField(null=True, upload_to=file_upload_to) version = models.CharField(max_length=50, null=True) xnumber = models.CharField(max_length=50, choices=xch, null=True) category = models.CharField(max_length=50, choices=ch, null=True) discord_id = models.CharField(max_length=150) date_added = models.DateTimeField(auto_now_add=True) hit_count_generic = GenericRelation( HitCount, object_id_field='pk', related_query_name='hit_count_generic_relation') likes = models.ManyToManyField(User, related_name='blog_posts') private = models.BooleanField(default=False) proved = models.BooleanField(default=False) def total_likes(self): return self.likes.count() def __str__(self): return str(self.title)[:30] def save(self, *args, **kwargs): if self.pk is None: saved_image = self.mainimage self.mainimage = None rpfile = self.rpfile self.rpfile = None super().save(*args, … -
how to sort results by 2 columns, limit prefetch result to one record and sort by prefetch column
I have multiple issues that I couldn't solve by my own. in CaseManager.get_queryset() : I'm trying to add a where clause that the case__id is equal to movement__case__id as: queryset=Movement.objects.filter(case__id=models.F('case__id')).order_by('-date'), but the query becomes as ... WHERE ("cm_movement"."case_id" = ("cm_movement"."case_id") AND ... Full query: SELECT "cm_movement"."id", "cm_movement"."case_id", "cm_movement"."direction", "cm_movement"."date", "cm_movement"."reason_id", "cm_movement"."details", "cm_movement"."created_at", "cm_movement"."updated_at", "cm_case"."id", "cm_case"."police_station_id", "cm_case"."number", "cm_case"."year", "cm_case"."kind", "cm_case"."registered_at", "cm_case"."created_at", "cm_case"."updated_at", "cm_movement_reason"."id", "cm_movement_reason"."direction", "cm_movement_reason"."reason", "cm_movement_reason"."created_at", "cm_movement_reason"."updated_at" FROM "cm_movement" INNER JOIN "cm_case" ON ("cm_movement"."case_id" = "cm_case"."id") INNER JOIN "cm_movement_reason" ON ("cm_movement"."reason_id" = "cm_movement_reason"."id") WHERE ("cm_movement"."case_id" = ("cm_movement"."case_id") AND "cm_movement"."case_id" IN ('41', '35', '29', '26', '44', '40', '34', '39', '32', '38', '31', '33', '30', '28', '27', '25', '43', '37', '36', '42')) ORDER BY "cm_movement"."date" DESC how can I get only the earliest or latest (only one movement) which is in prefetch_related in CaseManager.get_queryset() how can I sort the result by latest_movement that is being generated by CaseManager.get_queryset() and used in: CaseAdmin.latest_movement() in CaseAdmin.ordering should sort the results by year in DESC order, and if there is more than one record with the same year they should be sorted by their number in DESC order that's why I used CaseAdmin.ordering = ['-year', '-number'] but what happened is they got sorted by year only. … -
multiple order instances created when the page is refreshing
I'm getting the billing address and display it in the payments page but the problem is that when i refresh the page it's create an other instance in the admin panel I tried the get_or_create but it still the same def placeorder(request, total=0, quantity=0): current_user = request.user cart_itemes = CartItem.objects.filter(user=current_user) cart_count = cart_itemes.count() if cart_count <= 0: return redirect('store') # order_data=request.session.get('context') # if order_data: # return render(request,'orders/payments.html') for cart_item in cart_itemes: total += (cart_item.product.price*cart_item.quantity) quantity += cart_item.quantity totale = total finaltotal = totale+50 if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.user = current_user data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.email = form.cleaned_data['email'] data.phone_number = form.cleaned_data['phone_number'] data.address_line1 = form.cleaned_data['address_line1'] data.address_line2 = form.cleaned_data['address_line2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] # data = Order(first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, # address_line1=address_line1, address_line2=address_line2, country=country, state=state, city=city) data.order_total = totale data.ip = request.META.get('REMOTE_ADDR') data.save() yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime('%Y%m%d') order_number = current_date + str(data.id) data.order_number = order_number data.save() order = get_object_or_404(Order, user=current_user, is_ordered=False, order_number=order_number) context = { "order": order, "cart_itemes": cart_itemes, "total": totale, "finaltotal": finaltotal } # request.session['context']=context return render(request, 'orders/payments.html', context) else: pass else: return redirect('checkout') … -
Django/HTMX - How to stop resetting selected option when search form is submitted?
I want to implement a search form that has a Product ID field and a and Product locations select field in which the list of locations should be populated based on the Product ID entered. For the Product ID, I'm using HTMX, to get the list of available locations dynamically. Which means, whenever I type any Product ID, I want to get all the available Locations for that ID without having to click on a button. And when the Location is selected and the Search button is clicked the search result should be displayed in the page. BUT the problem is, whenever I click select an option and click on the Search button, It reloads the page and resets the selected option! and this is not what I want, I want to keep the location as selected when the search result is displayed. How can I stop resetting the select input after selecting when the Search button is clicked and the page is reloaded? Template: <form method="get" action="{% url 'shop:product_list' %}"> {% csrf_token %} <div class="d-flex"> <div class="me-2">{{filter_form.name}}</div> <div class="me-2">{{filter_form.category}}</div> <div> <button name="product_search_btn" type="submit" class="btn btn-primary"> Search </button> </div> </div> </form> Form: class ProductSearchForm(forms.Form): id=forms.IntegerField(widget=forms.NumberInput(attrs={"hx-get":reverse_lazy("shop:product_locations"), "hx-trigger":"load, change", "hx-target":"#locations_select", "class":"form-control"})) locations=forms.ChoiceField(widget=forms.Select(attrs={"id":"locations_select", … -
How to update a post in Django using the same manual-written form for creating it?
I have a form in which I can create a new post, which works perfectly. Now I want the same form to be filled when clicking on a link in order to update the post. I've found lots of tutorials, but all of them were using the form in 'form.py'. I don't have a form base on my model, I've created the form myself and now I want it to go to the same form-page and fill up the data, so it can edit the post. When this link is clicked, which each post has one, I want it to go to the form-page and fill the form, so I can edit it. This link is in home.html <a href=""><img width="48" height="48" src="https://img.icons8.com/fluency/48/pogchamp.png" alt="pogchamp"/></a> This is my form. I use it for creating a new post, but I also want to use it for editing. It's add_edit.html <form class="form text-center" action="{% url 'addEdit' %}" method="POST"> {% csrf_token %} {% if messages %} {% for message in messages %} <p class="text-danger text-center fs-3 vov fade-in-up">{{ message }}</p> {% endfor %} {% endif %} <div class="mb-3 col-11 col-md-4 col-lg-3 mx-auto"> <label for="title" class="form-label float-start" id="title_lable">TITLE</label> <input type="text" class="form-control" name="title" id="title" placeholder="U_U" required> … -
DJango: Textarea/Form get, process and show
Good evening, i'm currently working on a small DJango project, and am currently facing an issue: The whole of the project is to provide a textarea to the user: 1- let the user write down the text that will be worked with. 2- store the data to process/work on it using python. 3- store the processed data on another variable. 4- show the text on a second textarea provided on screen. Currently, I've tried using a simple to get the information and store it, but the site keeps spinning and there's no progress Base .html section with the textareas: <section id="det"> <div class="theText"> <textarea id="text" placeholder="Type/Paste to Summarize"></textarea> <br> <button type="submit">Start</button> <br><br> <button type="submit">Clean</button> <br><br> </div> <div class="theText"> <textarea id="text" placeholder="Your summarized text"></textarea> <br> <button type="submit">Export</button> <br><br> <button type="submit">Copy</button> <br><br> </div> </section> Alternative tried: <form method="POST"> {% csrf_token %} <label for='TPre'>PreSummarizarion</label><br> <input id="TPre" name="TPre" type="text"><br> <button>Submit</button> </form> Current views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request, "first/home.html",{ "text":text, }) def taking(request,tex,tex_slug): tex= textPre.objects.get(slug = tex_slug) return render(request, "first/home.html", { "tex":tex }) Current models on the django project: from django.db import models class textPre(models.Model): preText = models.TextField() #preText2 = models.CharField(max_length=1500) class … -
What am I missing to have 'move_up_down_links' display on 'ListAdmin' page using django-ordered-model?
I use django-ordered-model==3.7.4 in my project to create an ordered model. I want to have a way to reorder list items via Django Admin. I tried to use example code from django-ordered-model's docs, but unfortunatelly it doesn't work as expected. Here's my code: # models.py class ListItem(OrderedModel): """ Represents an item of the user-created book list. """ list = models.ForeignKey( verbose_name=_("список"), to=List, on_delete=models.CASCADE, related_name="items", ) book = models.ForeignKey( verbose_name=_("книга"), to=Book, on_delete=models.CASCADE, related_name="list_items", ) description = models.TextField( verbose_name=_("описание"), blank=True, null=True, default=None, ) created = models.DateTimeField(verbose_name=_("создана"), auto_now_add=True) updated = models.DateTimeField(verbose_name=_("изменена"), auto_now=True) class Meta: ordering = ["order"] verbose_name = _("элемент списка") verbose_name_plural = _("элементы списков") # admin.py class ListItemInline(OrderedTabularInline): model = ListItem fields = [ "book", "description", "order", "move_up_down_links", ] readonly_fields = [ "order", "move_up_down_links", ] ordering = [ "order", ] extra = 0 @admin.register(List) class ListAdmin(OrderedInlineModelAdminMixin, admin.ModelAdmin): """ Configures admin views for List. """ model = List list_display = [ "title", "user", "is_public", "created", ] inlines = [ListItemInline] readonly_fields = [ "created", "updated", ] @admin.register(ListItem) class ListItemAdmin(OrderedModelAdmin): """ Configures admin views for ListItem. """ model = ListItem list_display = [ "book", "list", "order", "move_up_down_links", "created", ] readonly_fields = [ "created", "updated", ] As a result, I can see move_up_down_links on ListItemAdmin page: … -
Is there a way to define the creation log recrods in database process in MIDDLEWARE?(Django)
I am working on a Django project, in which has a customized logging class. I need to save all the logs on my database. I have a separate app for my customized log class. In settings.py: INSTALLED_APPS = [ ... 'CustomDBLogger', ... ] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, }, 'handlers': { 'db_log': { 'level': 'DEBUG', 'class': 'CustomDBLogger.db_log_handler.DatabaseLogHandler' }, }, 'loggers': { 'db': { 'handlers': ['db_log'], 'level': 'INFO' # we want to see info logges and beyond } } } In CustomDBLogger/models.py: import logging from django.db import models from six import python_2_unicode_compatible from django.utils.translation import gettext_lazy as _ LOG_LEVELS = ( (logging.NOTSET, _('NotSet')), (logging.INFO, _('Info')), (logging.WARNING, _('Warning')), (logging.DEBUG, _('Debug')), (logging.ERROR, _('Error')), (logging.FATAL, _('Fatal')), ) @python_2_unicode_compatible class StatusLog(models.Model): logger_name = models.CharField(max_length=100) level = models.PositiveSmallIntegerField(choices=LOG_LEVELS, default=logging.ERROR, db_index=True) msg = models.TextField() trace = models.TextField(blank=True, null=True) create_datetime = models.DateTimeField(auto_now_add=True, verbose_name='Created at') # new fields username = models.CharField(max_length=128, null=False, blank=False) user_ip = models.CharField(max_length=128, null=True, blank=True) page_url = models.TextField(max_length=200) page_name = models.TextField(max_length=200, null=True, blank=True) json_data = models.JSONField(default=dict, null=True, blank=True) segment0 = models.TextField(max_length=128, null=True, blank=True) segment1 = models.TextField(max_length=128, null=True, blank=True) segment2 = models.TextField(max_length=128, null=True, blank=True) segment3 = … -
Django channels consumer how to disconnect at server side
I'm trying to write a log file viewer with django, channels, but only the first connection works well, while I refresh the frontend, websocket will connect fail. After some search, I found the loop is still running in my code(the first websocket connection not cleaned up rightly). I was thinking that disconnect would be called when I close the websocket client, but it's not. My consumer code: import time from channels.exceptions import StopConsumer from channels.generic.websocket import WebsocketConsumer class LogConsumer(WebsocketConsumer): end = False def connect(self): self.accept() filename = self.scope['url_route']['kwargs']['filepath'] file_fullname = "/tmp/" + filename print('file name: %s' % file_fullname) with open(file_fullname, 'r') as f: while True: time.sleep(1) if self.end: break new_line = f.readline() print('Loop is still running ....') if new_line: print('sending data: %s' % new_line) self.send(text_data=new_line) def disconnect(self, event): print('websocket disconnected...', event) self.end = True raise StopConsumer() daphne output: 192.168.1.2:63267 - - [03/Jun/2023:16:25:09] "WSCONNECTING /ws/message/" - - 192.168.1.2:63267 - - [03/Jun/2023:16:25:09] "WSCONNECT /ws/message/" - - file name: /tmp/message Loop is still running .... sending data: Loop is still running .... sending data: 1 Loop is still running .... sending data: 2 Loop is still running .... sending data: 3 192.168.1.2:63267 - - [03/Jun/2023:16:25:14] "WSDISCONNECT /ws/message/" - - 192.168.1.2:63273 - - [03/Jun/2023:16:25:14] … -
DRF ORM: Aggregate, annotate and remove duplicates all in the same query
Knowing that I have the following models: class Merchant(BaseModel): business_name = CharField() user = ForeignKey( User, related_name='merchant' # ... ) # other fields... class Sale(BaseModel): merchant = ForeignKey( Merchant, related_name='sale_merchant' # ... ) statue = CustomCharField( max_length=20, choices=[(DRAFT, DRAFT)), (COMPLETED, COMPLETED), (FAILD, FAILD)], # ... ) # other fields like total, discount, data... class SaleItem(BaseModel): quantity = PositiveIntegerField() product = ForeignKey( Product, # ... ) sale = ForeignKey( Sale, related_name='sold_item' # ... ) # other fields... As well as a Product model, and a User model (alongside other information, the User model stores the user's city as a reference to the City model). As you can see, a Sale, may have multiple SaleItems, a SaleItem refers to a single Product and the Sale itself, and has a quantity. Finally, a Sale represents a set of products that were sold by us to a specific merchant . I want to get the number of items of each product that were sold to each merchant. An example of the output I'm trying to achieve (id replesents the id of the first SaleItem that links product X to merchant Y): +--------------------------------------------------------------------+ | id | Merchant Name | Denomination | Quantity | Merchant City …