Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Django Forms to filter by models' field with many to many relationship
I have a problem with a form in Django that would like to filter objects from a Dish model. I would like to filter by objects from the Dish model through the main_ingredient field which has a many-to-many relationship with the MainIngredient model The form now allows you to display separate forms for each of the main_ingredient types However, the bug is in the filter_dishes method. I want this form to return only dish objects for which the main_ingredient selected by the user is 60% of all main_ingredients in the Dish object. For example, the program should return a Dish1 object that has the main_ingredient objects [x1, x2, x3, x4, x5, x6, x7, x8, x9, x10] only when the user selects 6 of these objects in the form. If the user would only select e.g. 4 objects or 10 objects other than those assigned to Dish1 then Dish1 should not be returned. enter image description here **class Dish(models.Model):** name = models.CharField(max_length=50) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) **main_ingredient = models.ManyToManyField(MainIngredient)** **class MainIngredient(models.Model):** name = models.CharField(max_length=50) type = models.ForeignKey(Type, on_delete=models.CASCADE) def __str__(self): return self.name **class Type(models.Model):** name = models.CharField(max_length=50) def __str__(self): return self.name **class DishFilterForm(forms.Form):** def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) types = … -
Receive input in file format from swagger form (Django)
# model class User(AbstractBaseUser, PermissionsMixin, CommonModel): phone = models.CharField(max_length=20, unique=True) nickname = models.CharField(max_length=20, unique=True) certification_profile = models.URLField(null=True) objects = UserManager() USERNAME_FIELD = "phone" # view class UserCreateView(generics.CreateAPIView): serializer_class = UserCreateSerializer parser_classes = (MultiPartParser,) # serializer class UserCreateSerializer(serializers.ModelSerializer): certification_profile = serializers.FileField(required=False) class Meta: model = get_user_model() fields = ( 'phone', 'nickname', 'certification_profile', ) def create(self, validated_data): certification_profile = validated_data.pop('certification_profile', None) user = get_user_model().objects.create(**validated_data) if certification_profile is not None: image_uuid = str(uuid4()) ## upload file ... user.certification_profile = certification_profile_url user.save() self._create_interests(interests, user) return user The certification_profile column of the User model is URLfield. I would like to receive certification_profile in the form of a file and save it in the form of a url later. So, I specified certification_profile = serializers.FileField(required=False) in UserCreateSerializer. However, as shown in the picture below, the swagger form continues to receive string input. How can I receive input in the form of a file in swagger form? thanks for reading the long post! -
'User matching query does not exist' when adding a like to database
As the title says, I'm trying to make a like button as a many to many where if a certain verse(or post) is liked by a certain user, a like is added to the database, and if a user unlikes a verse, a like is deleted from the database. I have deleteUserLike working, but am not able to create a like on the frontend, as when I do I get the error above on the backend, and user_id appears null in the payload under the network tab in dev tools. VerseCard: const handleCheckChange = (event) => { const { checked } = event.target; if (checked) { createUserLike({ verseId: id, ...userId }); console.warn(userId); } else { const userLike = userLikesArray.find((ul) => ul.verse_id === id); if (userLike) { deleteUserLike(userLike.id); } } }; return ( <> <Card className="text-center" style={{ width: '25rem' }}> <Card.Header>{firstName} {lastName}</Card.Header> <Card.Body> <Card.Title>{verse}</Card.Title> <Card.Text>{content}</Card.Text> <Card.Footer>{version}</Card.Footer> <div style={{ margin: 'auto', display: 'block', width: 'fit-content', }} > <FormControlLabel control={( <Checkbox icon={<FavoriteBorder />} checkedIcon={<Favorite />} name="checkedH" checked={!!userLikesArray.find((ul) => id === ul.verse_id)} onChange={handleCheckChange} /> )} /> userLikeData: const createUserLike = (userLike) => { const userLikeObj = { verse_id: Number(userLike.verseId), user_id: Number(userLike.userId), }; return fetch(`${clientCredentials.databaseURL}/userlikes`, { method: 'POST', body: JSON.stringify(userLikeObj), headers: { 'Content-Type': 'application/json', }, … -
cant pass data between Django and Chartjs
I wanted to pass an array to chartjs for a chart the data is getting passed but for some strange reason the data gets changed, the array contains days of the month [1,2,3,so on] but on chart it displays "[ 0 1 3 5 7 9 0 so on ]" the data is good when I print it to console return render(request, 'notes/home.html',{ 'day':daysOfMonth, }) <div class="mainChart"> <canvas id="myChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const ctx = document.getElementById('myChart'); const days = '{{day}}'; new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ // label: '# of Votes', data: [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,], borderWidth: 10 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div> -
Unable to see Django project on domain/ip address after Linode deployment - what could be wrong?
I am trying to deploy my django project on linode for my domain address.But I couldn't see project on domain/ip address. I created the existing domain on Linode servers. I set the records as default (A/AAAA Record, MX Record, NS Record and SOA Record). Added the Linode name servers to domain ragistrar's dns settings. I added domain name as reverse dns under Linode Network. In the Django project, I added domain name, and ip address as allowed hosts to settings.py. I've been getting the "This site can't be reached" error for a long time. I used to see the default django page before, now I can't see it either. What could be problem? -
django use aws bucket for static and media files
I've got custom admin panel and api rest-framework django project. S create aws account, user, S3 bucket. My django aws settings: AWS_USERNAME = 'my_username' AWS_GROUP_NAME = 'django_s3_group' # Aws config AWS_ACCESS_KEY_ID = config("SERVER_AWS_ACCESS_KEY_ID", '') AWS_SECRET_ACCESS_KEY = config('SERVER_AWS_SECRET_ACCESS_KEY', '') AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'photo_crm.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'photo_crm.aws.utils.StaticRootS3BotoStorage' S3_DEFAULT_BUCKET = config("S3_DEFAULT_BUCKET", "") AWS_STORAGE_BUCKET_NAME = config('SERVER_AWS_STORAGE_BUCKET_NAME', S3_DEFAULT_BUCKET) S3DIRECT_REGION = 'us-east-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = S3_URL + 'media/' STATIC_URL = S3_URL + 'static/' # ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' ADMIN_MEDIA_PREFIX = STATIC_URL AWS_S3_FILE_OVERWRITE = False two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()),), } I move all env to .env file I've got folders in my bucket after command: python manage.py collectstatic It looks like some default staff rest_framework/ django_extensions/ ckeditor/ admin/ In my project I save staticfiles in local static folder: css/ fonts/ js/ img/ svg/ I open template index.html and see that all static imports lights up. So as I understand, django didn't match the static files and S3 bucket. Just example of the file import in … -
How to calculate the number of hours spend inside and the number of hours spend outside for the employee face recognition attendance?
In my company we need to develop an application for the employee face recognition attendance. Per day, an employee after his first entry at 7:30AM can exit and entry several times before the leaving time (3:30PM). So, in this application, we need to record the entries and exits times per employee and per day and calculate the duration hours inside and outside. Here is ours models: class Profile(models.Model): first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) date = models.DateField() phone = models.BigIntegerField() email = models.EmailField() # ranking = models.IntegerField() # profession = models.CharField(max_length=200) agence = models.ForeignKey(Agence, on_delete=models.CASCADE, null=True) direction = models.ForeignKey(Direction, on_delete=models.CASCADE, null=True) status = models.CharField(choices=types,max_length=20,null=True,blank=False,default='employee') present = models.BooleanField(default=False) image = models.ImageField() updated = models.DateTimeField(auto_now=True) # shift = models.TimeField() def __str__(self): return self.first_name +' '+self.last_name class LastFace(models.Model): last_face = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) entry = models.TimeField(blank=True, null=True) exit = models.TimeField(blank=True, null=True) def __str__(self): return self.last_face This function code is bellow is working but it just records last_face id and the date however it is recording the entry and exit time. def scan(request): global last_face known_face_encodings = [] known_face_names = [] profiles = Profile.objects.all() for profile in profiles: person = profile.image image_of_person = face_recognition.load_image_file(f'media/{person}') person_face_encoding = face_recognition.face_encodings(image_of_person)[0] known_face_encodings.append(person_face_encoding) known_face_names.append(f'{person}'[:-4]) video_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW) … -
Langchain cannot create index when running inside Django server
I have a simple Langchain chatbot using GPT4ALL that's being run in a singleton class within my Django server. Here's the simple code: gpt4all_path = './models/gpt4all_converted.bin' llama_path = './models/ggml_model_q4_0.bin' embeddings = LlamaCppEmbeddings(model_path=llama_path) print("Initializing Index...") vectordb = FAISS.from_documents(docs, embeddings) print("Initialzied Index!!!") This code runs fine when used inside the manage.py shell separately but the class instantiation fails to create a FAISS index with the same code. It keeps printing the llama_print_timings 43000ms with the ms increasing on every print message. Can someone help me out? -
Can someone please fix my search bar in Flutter?
I'm trying to make a searchbar, where I can search data from my Django API. Right now I can find shows by name, and when I'm deleting my prompt it doesn't update. I would also like to find shows by their directors for example. Can someone help me with this? This is my search screen: List<ShowsModel> showsList = []; List<DirectorModel> directorList = []; Future<void> getShows() async { showsList = await APIHandler.getAllShows(); setState(() {}); } Future<void> getDirectors() async { directorList = await APIHandler.getAllDirectors(); setState(() {}); } @override void didChangeDependencies() { getShows(); getDirectors(); super.didChangeDependencies(); } void updateList(String value) { setState(() { showsList = showsList .where((element) => element.name.toLowerCase().contains(value.toLowerCase())) .toList() ; //i would like to add more elements here but don't know how }); } //skipping widget build // my search bar Container( padding: const EdgeInsets.all(2), decoration: BoxDecoration( color: const Color.fromRGBO(244, 243, 243, 1), borderRadius: BorderRadius.circular(15), ), child: TextField( onChanged: (value) => updateList(value), decoration: const InputDecoration( border: InputBorder.none, prefixIcon: Icon( Icons.search, color: Colors.black87, )), ), ), -
Why is my React app not getting data from the Django backend after uploading to the server?
After uploaded the React app to the server, it does not get data from Django Backend. I uploaded my Django backend to the server. After that I checked the API endpoint, it works. Then uploaded the React frontend and replaced the '.htaccess' code with this bunch of codes Old htaccess PassengerAppRoot "/home/mod**/mainapp" PassengerBaseURI "/" PassengerPython "/home/mod**/virtualenv/mainapp/3.8/bin/python" PassengerAppLogFile "/home/mod**/logs/passengar.log)" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> </IfModule> New htaccess Options -MultiViews </br> RewriteEngine On </br> RewriteRule ^(get-ticket)($|/) - [L] </br> RewriteCond %{REQUEST_FILENAME} !-f </br> RewriteRule ^ index.html [QSA,L] </br> After the rewrite htaccess everything redirect to index.html. How can I solve this issue? does anyone help? Where should I neeed to change? Before the react app upload, django works fine. I checked it. -
Django+docker compose+NGINX+aws+RDS+postgreSQL deployment and ports flow
Hi I developed a simple personal blog with Django and Nginx as a reverse proxy server and want to deploy It with AWS in the most costo effettive way. Which Is It? And I don't understand the ports flow between localhost, Django (uwsgi+gunicorn), Nginx, docker (compose), postgrSQL and AWS RDS...can someone give me help or advice on this? Other infos (this is how I imagined it and tried to put all in a flow but I think there's something wrong, and sorry for the bad formatting but I didn't know ho to do it, i'm a beginner coder): AWS RDS’s endpoint:5432 Client’s requests(incoming/inbound traffic):80 <-- LB(Load Balancer):8000 <-- Nginx <-- (Gunicorn + uwsgi (django app/web container)) 0.0.0.0:8000:9000 <-- docker container:8000 <-- (localhost(0.0.0.0):8000 <-- Gunicorn) django_app:8000 <-- uwsgi:9000 <-- Nginx80:8000 <-- load balancer:8000 (defaults traffic from listener HTTP port 80 redirect to 443 (HTTPS) and then from this to TG1):8000 <-- TG1(Target Group 1) <-- TG2 <-- Client Some debugging logs: $ docker-compose -f docker-compose-prod.yml up nginx_1 | 2023/06/02 15:20:44 [error] 10#10: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /wpad.dat HTTP/1.1", upstream: "uwsgi://172.18.0.3:9000", host: "wpad.homenet.telecomitalia.it" nginx_1 | 172.18.0.1 - - [02/Jun/2023:15:20:44 +0000] … -
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.