Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django only able to handle 3 actions at same time?
Hello apologies as I am incredibly new to Django. I have a Django site deployed to an AWS ec2 with Gunicorn and Nginx. Essentially within the app the user clients a button some python code kicks off and ~10 seconds later the work is done. This works perfectly until there are more than 3 actions going on at the same time. If I were to open 3 tabs and click 3 buttons at roughly the same time, the entire site can't do anything else. No other pages will load or anything. The aws EC2 has 2 codes. Gunicorn is set to 5 workers. I tried increasing the size of the ec2 to an instance with more cores thinking that might be it but unfortunately no dice. Would anyone have a clue what might be going on? -
Django Direct assignment to the reverse side of a many-to-many set is prohibited. Use .set()
I have two models, StudyConditions and studies, and there exists a many to many relationship between the two, declared in studies. I am trying to create new conditions in my StudyConditionViewSet and link them to the studies. When doing a post request with the JSON object below, I get the error Direct assignment to the reverse side of a many-to-many set is prohibited. Use .set(). Is this just not possible, i.e I can only do this in my StudyViewSet, or is there something I'm missing/misunderstanding? There aren't many issues I've seen concerning this specific case. I've tried both study_obj.conditions.add(new_condition) and new_condition.studies.add(study_obj), trying to add the condition to the study in the first, and trying to add the study to the condition in the second. I've also tried them using set, but with no success. { "name": "Post w/ studies", "studies": [ { "id": "1" }, { "id": "2" } ] } models.py class Study(models.Model): featured = models.BooleanField(default=False) conditions = models.ManyToManyField('StudyCondition', related_name='studies', db_table='Study_Condition') class Meta: db_table = 'Study' class StudyCondition(models.Model): name = models.TextField(null=False) class Meta: db_table = 'Condition' views.py class StudyConditionViewSet(viewsets.ViewSet): def list(self, request): queryset = StudyCondition.objects.all() result = StudyConditionSerializer(queryset, many=True) if result: return Response(result.data) else: return Response(data=result.data, status=200) def retrieve(self, … -
Try to sum the incoming data
from django.db import models from django.urls import reverse from django.contrib.auth.models import User from datetime import date class Goals(models.Model): calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) user = models.ForeignKey(User, on_delete=models.CASCADE) class Macros(models.Model): name= models.CharField(max_length=100) calories= models.FloatField(max_length=10) protein=models.FloatField(max_length= 4) carbohydrates= models.FloatField(max_length= 4) fats= models.FloatField(max_length=4) goals = models.ForeignKey(Goals, on_delete=models.CASCADE) here is my models and trying sum the macros like calories protein carbohydrates fats by += -
Django - Display a pandas dataframe into django template
everybody. I'm trying to use Django to display a pandas dataframe example, but it doesn't render. I tried use for statement, the function df.to_html, with no success. I hope you help me, I would appreciate it. views.py from django.shortcuts import render import pandas as pd # Create your views here. def index(request): df = pd.DataFrame( {'Nome': ['Beatriz', 'Ana', 'Flávia', 'Bianca'], 'Idade': [23, 24, 24, 19], 'Profissao': ['Analista de Sistemas', 'Advogada', 'Promotora', 'Jornalista'], 'Renda_mensal': [5000, 8000, 15000, 4500] }) df = df.to_html() return render(request, 'index.html') index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home</title> </head> <body> <h1>Em construção</h1> {{ df }} </body> </html> Thank you since now. -
how to Extract days from DateField in django
interval = Attribute.objects.filter(Q(register_date__gte='2021-07-01')) \ .annotate(input_interval=Cast('create_at', DateField()) - F('register_date')).values('student_id', 'input_interval') The date you registered the student is register_date and the model property is DateField . The date/time that each student's enrollment date was entered into the actual program is create_at and the model property is DateTimeField . The two fields have different model properties, so I converted the create_at field to a DateField using the Cast function. And (actual input date) - (student enrollment date) was obtained. The result is as below. <QuerySet [{'student_id': 1, 'input_interval': datetime.timedelta(days=1)}, {'student_id': 2, 'input_interval': datetime.timedelta(0)}, {'student_id': 3, 'input_interval': datetime.timedelta(0)}, {'student_id': 4, 'input_interval': datetime.timedelta(0)}]> Is there a way to extract only the days value of input_interval from here? I googled and tried functions such as ExtractDay, days, etc., but the date returned using the Cast function is Is it impossible to extract... Please help. -
Django: If an object from a database is deleted do the remainer objects keep the same id/order?
This might be a stupid question but here I go: I have a SQLite database with Django. Let's say in one table i have four objects: ID=1 name=dog ID=2 name=cat ID=3 name=lion ID=4 name=rat If I were to delete an object let's say animals.objects.get(id=3).delete() Do the id's from the other objects change? Would it be: ID=1 name=dog ID=2 name=cat ID=3 name=rat They change right? I am supposing they do. And if they do is this so in other databases like MySQL? -
Logging activity django backend react
I have a react application that uses django rest framework as a backend. Problem is the server the react application is hosted on is a flask application (long story..not my monster). I would like to keep a log of activity from the react app, but I would also like to add some custom data from the react front end when these logs are generated that goes to the back end. Any help would be appreciated. -
I am using the justdjango chat app and as I follow his works suddenly I received this kind of error from django as I tried to send a message?
Traceback (most recent call last): File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\staticfiles.py", line 44, in call return await self.application(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\routing.py", line 71, in call return await application(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\sessions.py", line 47, in call return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\sessions.py", line 263, in call return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\auth.py", line 185, in call return await super().call(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\middleware.py", line 26, in call return await self.inner(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\routing.py", line 150, in call return await application( File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 58, in call await await_many_dispatch( File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch await dispatch(result) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\asgiref\sync.py", line 444, in call ret = await asyncio.wait_for(future, timeout=None) File "c:\users\ralphjohn\appdata\local\programs\python\python39\lib\asyncio\tasks.py", line 442, in wait_for return await fut File "c:\users\ralphjohn\appdata\local\programs\python\python39\lib\concurrent\futures\thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\asgiref\sync.py", line 486, in thread_handler return func(*args, **kwargs) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\consumer.py", line 125, in dispatch handler(message) File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\channels\generic\websocket.py", line 59, in websocket_receive self.receive(text_data=message["text"]) File "C:\Users\RalphJohn\Documents\ChatApp\source\privateChat\consumers.py", line 75, in receive self.commands[data['command']](self, data) File "C:\Users\RalphJohn\Documents\ChatApp\source\privateChat\consumers.py", line 23, in new_message author_user = User.objects.filter(username=author)[1] File "C:\Users\RalphJohn\Documents\ChatApp\env\lib\site-packages\django\db\models\query.py", line 318, in getitem return qs._result_cache[0] IndexError: list index out … -
Django floatformat with forms.FloatField objects
{{ value }} works in my template. {{ myForm.myFloatField }} works. myForm inherits from forms.Form and myFloatField is a forms.FloatField object. {{ value|floatformat:3 }} presents the value with three numbers after the decimal, as expected. {{ myForm.myFloatField|floatformat:3 }} does not work, not even rendering the field. How do I get myForm.myFloatField to present with three numbers after the decimal? -
How can i fix Django Postgresql migrations error?
I can import migrations with Sqlite3 in my Django project, but when I try to import it with postgreql, I get an error like this. How can I fix this? I installed before pip install psycopg2 pip install django psycopg2 Error conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError DB Settings Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'lordplusdb', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Django Pagedown; Form looks highlighted
Not sure what is going on here. The form from django-pagedown looks highlighted. I followed the docs here; section: Outside Django Admin. I just cannot figure this out and I can't find and forms about the issue to help resolve this. When I click on the textarea to, the box turns white. forms.py from pagedown.widgets import PagedownWidget # Django from django import forms # local Django from .models import ExampleModel class ExampleForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) """Form for Blog posts""" class Meta: model = ExampleModel fields = ['content'] views.py def get_form(request): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/success/') else: form = ExampleForm() return render(request, 'example.html', {'form': form}) example.html <!DOCTYPE html> <html lang="en"> <head> {{ form.media }} </head> <body> {{ form }} </body> </html> -
How to fix can't find CSS path in Django app?
When deploy Django project to Heroku, Style is not working fully and I have some errors "not found" If you have good experience, please explain to me. Thanks. -
Django Model Calculation Performing however .save() not updating postgresql database
I have some code that is basically supposed to execute on a button click. if response.POST.get("calculate"): sh.isEdit=False temp=[] for link in sh.tablink_set.all(): temp.append([link.link, link.tournName]) print(link.link) sh.createdsheet=finalCalc(temp) sh.save(update_fields=['isEdit', 'createdsheet']) everything is working fine, except for the last line to save. I know the rest of it is working, as a) the calculation performs fine as I printed the result to the console, and that looked totally fine. Moreover, I know that the saving issue is associated with the 'createdsheet' and not the boolean 'isEdit', as prior to adding 'createdsheet', my script was working fine. In my model, createdsheet is an 3-d arrayfield, and similarly, the function I call, 'finalCalc' returns a 3-d array. class eloSheet(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, related_name="elosheet", null=True) name= models.CharField(max_length=500) startYear=models.CharField(max_length=4) endYear=models.CharField(max_length=4) createdSheet=ArrayField( ArrayField( models.CharField(max_length=100) ) ) isEdit=models.BooleanField(default=True) The error I get from the terminal is raise ValueError("The following fields do not exist in this " ValueError: The following fields do not exist in this model or are m2m fields: createdsheet however I know that the field does exist (I went to the admin page to confirm it was in the model) however I am unclear on what a ManyToMany field is. Any advice to make this work would be … -
Django Update fileinput widget doesnt work when field is required
I have a FileField in the form that I'm passing to my updateview. The default widget clearablefileinput is visually disgusting, so I changed it to the simple fileinput. The issue is that when I set my field to required in init method, the update doesnt work. Nothing happens when I push the update button. I only have 2 ways to make it work it seems: widget = fileinput but required = false widget = clearablefileinput and required = true I have no idea how these things work behind the scenes and honestly I'm angry that django is making me tackle the stupid clearable file input. Is there any way to make the fileinput work even when required = true? -
How to filter a condition in class based view
class PostDetailView(HitCountDetailView): model = PostForNewsFeed template_name = 'feed/post_detail.html' context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context.update({ 'popular_posts': PostForNewsFeed.objects.filter(visibility='Public').order_by('-hit_count_generic__hits')[:3],'page_title': 'Shared Post' }) return context I am able to see even the Private Post instead of just Public Post. -
Docker and Django PermissionError: [Errno 13] when running collectstatic
Django version: 3.2.5 Python Image: python:3.9-alpine3.14 Nginx Image: nginxinc/nginx-unprivileged:1-alpine Docker version: 18.09.1, build 4c52b90 I am trying to configure my application to to use static files served via an Nginx proxy image within Docker. (Apologies if I explain this badly, I will explain it as well as I currently know how.) I have set up a volume within my docker-compose-prod.yml with the aim of serving static content here via those volumes and nginx. As part of that I have added the creating of the volumes to Dockerfile and edited the urls.py and settings.py to look for the relevant url patterns and set the STATIC_ROOT. The application builds fine but when I run docker compose -f docker-compose-prod.yml up I get a looping error conatining multiple references to collectstatic.py and with the error: PermissionError: [Errno 13] Permission denied: '/app/app/static/admin/css/nav_sidebar.css' Full stack trace is below. I have run chown -R 755 richard:richard on my home system just to be sure but this had no effect. collectstatic is run via a /static/run.sh script in the root of my project and is initialised from my Dockerfile. From what i understand, collectstatic should be going through each of my apps and collecting all the content from … -
Django payment calculation getting error query does not exist
info I try to make monthly billing app. i have get total_amount from property price. customer has multiple payments so i am trying to adding all payments amount of specific customer into customer collect_amount and collect_amount deducts from total amount. if i remove any payment from a customer the total_amount will update automatically. problem When i try to update the exiting payment the calculation create a mess. if anybody have a better solution to the reported post. I would be grateful for any help.. if i try to edit the exiting payment i want only that to updated particularly i don't want any changes in remaining balance. henceforth after i complete the updating exiting payment then the remaining balance can get updated it self. anybody know the better to calculate the amount...? please help me models.py: class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) total_amount = models.IntegerField(default=0) collect_amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.total_amount = self.prop_select.price self.total_amount -= self.collect_amount super().save(*args, **kwargs) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.customer.collect_amount += self.amount self.customer.save() super(Payment, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.customer.collect_amount … -
Django: show instance string value in ModelField
I initialize a ModelForm before to send it to front-end. Everything works ok but the generated form shows 'associative_subscription' and 'course' ids, but I want to show the strings converded values(more readable for the user). Here's my code: models.py class CourseSubscription(models.Model): start_date = models.DateField(default=datetime.date.today, null=False, blank=False, verbose_name="Data di inizio") associative_subscription = models.ForeignKey(AssociativeSubscription, on_delete= models.CASCADE, null=False, blank=False, verbose_name="Iscrizione Associativa") course = models.ForeignKey(Course, on_delete= models.CASCADE, null=False, blank=False, verbose_name="Corso") fee_paid = models.DecimalField(max_digits=7, decimal_places=2, null=False, blank=False, verbose_name="Quota versata") payment_completed = models.BooleanField(default=False, verbose_name="Pagamento Completo") expiration_date = models.DateField(editable=False, null=False, blank=False, verbose_name="Scadenza") payment_method = models.CharField( max_length = 4, blank=False, verbose_name="Modalità di pagamento", choices=PAYMENTS ) class Meta: unique_together = ("associative_subscription", "course") def __str__(self): return u'%s / Iscrizione corso %s dal %s al %s' % (self.associative_subscription.member, self.course, self.start_date.strftime('%d/%m/%Y'), self.expiration_date.strftime('%d/%m/%Y')) forms.py class CourseSubscriptionForm(ModelForm): def __init__(self, max_value, *args, **kwargs): super(CourseSubscriptionForm, self).__init__(*args, **kwargs) self.fields['fee_paid'] = forms.DecimalField( max_digits=7, decimal_places=2, required=True, label="Quota Versata", min_value=0.01, max_value=max_value, help_text= f"Valore Massimo: {max_value}", widget = forms.NumberInput() ) class Meta: model = CourseSubscription exclude = ('expiration_date','payment_completed') widgets = { 'associative_subscription': forms.TextInput(attrs={'readonly':'readonly'}), 'course' : forms.TextInput(attrs={'readonly':'readonly'}) } views.py def add_course_subscription(request, associative_subscription_id, course_id): if request.method == 'POST': ... return JsonResponse(context) associative_subscription = AssociativeSubscription.objects.get(id= associative_subscription_id) course = Course.objects.get(id = course_id) remaining_fee = course.inscription_price form = CourseSubscriptionForm( initial={ 'associative_subscription': associative_subscription, 'course':course, 'fee_paid': 1.00, }, … -
Using Weasyprint to create file response
I am making a web application with Django relating to guitar chord sheets. One of the features is the ability to generate a PDF from a chord sheet and download it. I am using Weasyprint to generate the PDF, but I'm getting a problem where instead of downloading the file, the view just shows a really long sequence of digits. Here's my view function: def download_pdf(request, song_id): song = get_object_or_404(Song, pk=song_id) song.chordsheet.open("r") chordsheet_html = HTML(string=chopro2html(song.chordsheet.read())) # Generates HTML from a text file, not relevant here chordsheet_css = CSS(string="div.chords-lyrics-line {\n" " display: flex;\n" " font-family: Roboto Mono, monospace;\n" "}\n") song.chordsheet.close() return FileResponse(chordsheet_html.write_pdf(stylesheets=[chordsheet_css]), as_attachment=True, filename=song.title + "_" + song.artist + ".pdf") And when I run the code, I get this: <html> <head></head> <body> (a 53,635-digit number here) </body> </html> For what it's worth, I have a similar view function that does the same thing except without the PDF generation (downloads the raw file) and it works fine. How can I fix this? -
How i can compare models in template
Why this compare code not work? I want to display all departments where departments filial = filial, but i got failure only. Thanks very much for you answers! {% for filial in filials %} {{ filial }} {% for dep in departments %} {{ dep }} {% if dep.Filial == filial.pk %} IFIFIFIFIF{{ dep.fullname }} {% endif %} {% endfor %} <br> {% endfor %} models: class Filials(models.Model): Fullname=models.CharField(max_length=30,blank=False) Entity=models.CharField(max_length=20,blank=True) City=models.CharField(max_length=15,blank=True) INN = models.IntegerField(max_length=20,blank=True,null=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' class Department(models.Model): Filial=models.ForeignKey(Filials, on_delete=models.CASCADE,related_name='department', blank=True) Fullname = models.CharField(max_length=30,blank=False) def __str__(self): return self.Fullname -
LEFT JOIN with other param in ON Django ORM
I have the following models: class Customer(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length = 255, default='example@example.com') authorized_credit = models.IntegerField(default=0) balance = models.IntegerField(default=0) class Transaction(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) payment_amount = models.IntegerField(default=0) #can be 0 or have value exit_amount = models.IntegerField(default=0) #can be 0 or have value transaction_date = models.DateField() I want to query for get all customer information and date of last payment. I have this query in postgres that is correct, is just that i need: select e.*, max(l.transaction_date) as last_date_payment from credit_customer as e left join credit_transaction as l on e.id = l.customer_id and l.payment_amount != 0 group by e.id order by e.id But i need this query in django for an serializer. I try with that but return other query Customer.objects.filter(transaction__isnull=True).order_by('id') But that i need is this rows example -
Django- how to render images in templates uploaded from admin?
I want to render images that I uploaded from my Django admin in my template views. Since I need to upload multiple images at a time, I declared a separate model, ShowPhoto, with a foreign key attached to my Problem model: models.py class Problem(models.Model): slug = models.SlugField(null = False, unique = True, max_length = 255) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) free = models.CharField(max_length = 1, choices = Free) #problem when introducing UUID field traceID = models.UUIDField(default=uuid.uuid4, editable = True) #use meta tags to optimize SEO metaTags = models.TextField(default = "") questionToProblem = models.TextField() class ShowPhoto(models.Model): show = models.ForeignKey(Problem, on_delete = models.CASCADE, related_name = "photos") photo = models.ImageField() class Meta: verbose_name = 'Solution Image' verbose_name_plural = 'Solution Images' Thus, in my admin.py, I also added: class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None, renderer = None): output = [] if value and getattr(value, "url", None): image_url = value.url file_name = str(value) output.append(u' <a href="%s" target="_blank"><img src = "%s" alt="%s" width="600" height="600" style="object-fit: cover;"/></a> %s ' % \ (image_url, image_url, file_name, _(''))) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) class ShowPhotoInline(admin.TabularInline): model = ShowPhoto formfield_overrides = {models.ImageField: {'widget': AdminImageWidget}} @admin.register(Problem) class ProblemModelAdmin(admin.ModelAdmin): form = ProblemForm list_display = ('questionToProblem', 'topic', 'free', 'traceID') search_fields = … -
How to Save A Post from 2 forms
How to save a Post from 2 forms # iterable VISIBILITY_CHOICES =( ("1", "Private"), ("2", "Public"), ("3", "Selected Friends"), ("4", "Everyone"), ("5", "Only One Friend"), ) # creating a form class VisibilityForm(forms.Form): geeks_field = forms.ChoiceField(choices = VISIBILITY_CHOICES) Views: def create_post(request): user = request.user if request.method == "POST": form2 = VisibilityForm(request.POST) form = NewPostForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user_name = user data.save() messages.success(request, f'Posted Successfully') return redirect('home2') else: form = NewPostForm() form2 = VisibilityForm(request.POST) return render(request, 'feed/create_post.html', {'form':form,'form2':form2, 'page_title': 'Share a Post' }) class PostForNewsFeed(models.Model): title = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=255, blank=False, null=False) #slug = models.SlugField(unique=True, max_length=100, blank=True,null=True) pic = models.ImageField(upload_to='path/to/img', default=None,blank=True) youtubeVideo = models.CharField(max_length=200, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation2', default=1) visibility = models.CharField(max_length=10, blank=False, null=False, default="Private") <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form|crispy }} {{ form2|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form> -
book appointment functionality
I have Django project, which contains two classes in model.py file, one is clinic(which has a contact number as a field) and other one is patient. I have rendered all the clinics in cards and each card has a button book-appointment. here is my model.py: class Clinic(models.Model): clinic_name = models.CharField(max_length=200, blank=True, verbose_name='Name') poster = models.ImageField(blank=True, null=True, upload_to='uploads/%Y/%m/%d', verbose_name='Picture') address = models.TextField(max_length=500, blank= True) contact_no = models.CharField(max_length=12, blank=True, verbose_name='Mobile') def __str__(self): return self.clinic_name class Patient(models.Model): clinic = models.ForeignKey(Clinic, on_delete=CASCADE) patient_name = models.CharField(max_length=200, blank=True) contact_no = models.CharField(max_length=12, blank=True) appointment_time = models.DateTimeField(auto_now=True) def __str__(self): return self.patient_name Now what I want is, when a authentic user which is patient in this case, clicks on book-appointment , A message should be sent on the clinics phone number saying this guys have booked an appointment with you on this date. how this can be achieved??? please guide me. -
convert django fileobject.chunks() into image
i am trying to create a progress bar for my file upload, so I need a way of know the state of the file been uploaded at any point in time. def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] fs = FileSystemStorage() for chunk in file.chunks(): image = ImageFile(io.BytesIO(chunk), name=file.name) filename = fs.save(file.name, content=image) I am looking for a way of saving the chunk and later converting them into an image to be saved, I don't want to use the python read and right interface because i will be uploading the file to aws. can someone point me in the right direction.