Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamically created temporary image not displaying
I want to dynamically create an image based on user inputs and display this to the user. views.py: class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] context['image'] = result[2] print(context['image']) return context It is at find_treatment(context["patient_id”]) that the image is generated by subfunction of find_treatment fig = sns_plot.get_figure() img_in_memory = BytesIO() fig.savefig(img_in_memory, format="png") #dunno if your library can do that. image = base64.b64encode(img_in_memory.getvalue()) And the template contains: <img src="data:image/png;base64,{{image}}" /> The image is not displaying however, is this an issue with how i am referencing the image in the template? -
decompress gzipped data from multipart/form-data with django
I'm having quite a lot of trouble trying to decompress gzipped data in django. I've tried a number of the solutions proposed in Download and decompress gzipped file in memory? but i think i'm running into difficulty in how it interacts with Django I'd like to be able to upload data.csv.gz and then if it is a gzip, extract out the compressed data into a django File to continue along its routine (Saving to FileField) What I have so far in my serializer def create(self, validated_data): file: File = validated_data.get("file") ext = file.name.split(".")[-1].lower() if ext == "gz": compressedFile = io.BytesIO() compressedFile.write(file.read()) decompressed_fname = file.name[:-3] decompressedFile = gzip.GzipFile(fileobj=compressedFile) with open(decompressed_fname, "wb") as outfile: outfile.write(decompressedFile.read()) outfile.flush() with open(decompressed_fname, "rb") as outfile: file = File(outfile) ext = decompressed_fname.split(".")[-1].lower() ... When I do this, outfile is empty when I check its contents on disk, and throws an error in later routines f.seek(0) ValueError: seek of closed file I get a similar error if I use shutil instead too if ext == "gz": compressedFile = io.BytesIO() compressedFile.write(file.read()) decompressed_fname = file.name[:-3] import shutil shutil.copyfileobj(gzip.GzipFile(fileobj=file), open(decompressed_fname, "wb")) with open(decompressed_fname, "rb") as outfile: file = File(outfile) ext = decompressed_fname.split(".")[-1].lower() the curl command i'm using: curl http://0.0.0.0:8000/upload/ -X 'POST' … -
How can I set the DEBUG level in a Django application
I am new to logging and am having difficulty setting the logging level to debug. I have created my own logger # logger.py from pathlib import Path import logging # Create a custom logger logger = logging.getLogger(__name__) logger.propagate = False logging.basicConfig(level=logging.DEBUG) # Create handlers c_handler = logging.StreamHandler() f_handler = logging.FileHandler('my_log_file.log') c_handler.setLevel(logging.DEBUG) f_handler.setLevel(logging.DEBUG) # Create formatters and add them to handlers c_format = logging.Formatter('myapp: %(message)s') f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') c_handler.setFormatter(c_format) f_handler.setFormatter(f_format) # Add handlers to the logger logger.addHandler(c_handler) logger.addHandler(f_handler) def log(frame, obj): """Create log message and return the object.""" path = Path(frame[0][1]) module = path.stem line = frame[0][2] message_text = f'{obj} <{module}> {line}' logger.warning(message_text) return obj I can create log messages in my application with log(inspect.stack(), f'Something happened here {myobj.name}: {myobj.value}') but it will not create messages unless I use the warning level logger.warning(message_text) in the logger. If I change it to logger.debug(message_text) nothing happens I searched the application for WARNING, DEBUG and level but can find nothing that should affect my logger I assume there is another logger that is over-ridding my level (Django perhaps) Can anyone help? -
i want to populate data in my django modelform but i m not sure about that how?
class update_question(View): def post(self, request, pk): question = Question.objects.get(id=pk) form = QuestionForm(request.POST, instance = question) if form.is_valid(): form.save() context = {'form':form} return render(request, 'file/updateQ.html', context) def get(self, request, *args, **kwarg, ): print(kwarg) form = QuestionForm() context = {'form':form} return render(request, 'file/updateQ.html', context) How to get object in get method to populate data in my QuestionForm -
Dynamic key fields
If a new input tag generated by user, then a dynamic field should be created in database. Example: When Booking railway ticket if user gives number of passenger’s then automatically field should be created like their name , age ,address should be got as input and stored in data base. The question is how to create key dynamically during runtime according to the user input. -
How to add middle IDs in third table with ManyToManyField in Django when using Serialaizer?
I have tables like this: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) price = models.ManyToManyField(Price) class Price(models.Model): cost = models.CharField(default=None, max_length=20) And from client get a request and try to save it in three tables, I have no problem with two tables Education and Price but because I'm using serializer i don't know how to update third table(middle). def post(self, request): cost = request.POST.get('cost') price = Price.objects.create(cost=cost) education_serializer = EducationSerializer(data=request.data) if education_serializer.is_valid(): education_serializer.save() Good, here i have updated two tables, In the following i don't know how update third table. If i didn't use serializer i have could write it like this: education.price.add(price) -
How to generate S3 presigned URL with boto3 resource instead of client
I using Django and S3Boto3Storage S3Boto3Storage creates connection attribute using boto3's resource method. connection = getattr(self._connections, 'connection', None) if connection is None: session = self._create_session() self._connections.connection = session.resource( 's3', region_name=self.region_name, use_ssl=self.use_ssl, endpoint_url=self.endpoint_url, config=self.config, verify=self.verify, ) return self._connections.connection But only Client class has the generate_presigned_url method. So, how can I get presigned URL with S3Boto3Storage.connection (by the way connection is ServiceResource)? PS I know that I can get presigned URLs by using Model.FileField.url attribute, but I need operate with temporary files that no exist in DB. In the internet many examples how to get presigned URL with client but nothing with s3 = boto3.resource('s3'). -
How to filter reverse foreign key with more one conditions by prefetch_related in Django
I created tow models class GroupModel(models.Model): group_name = models.CharField(max_length=2, null=False, default="A") class MemberModel(models.Model): name = models.CharField(max_length=8, null=False, default="") group = models.ForeignKey( to=GroupModel, on_delete=models.CASCADE, related_name="members", db_column="member", ) isActive = models.BooleanField(null=False, default=False) country = models.CharField(max_length=8, null=False, default="CN") I run queryset = GroupModel.objects.prefetch_related( Prefetch("members", MemberModel.objects.filter(isActive=False)) ).distinct() I got the all groups with the field isAcitve is Flase in MemberModel. Now, I want to get all groups with the field isActive is False and country is CN in MemberModel. I run queryset = GroupModel.objects.prefetch_related( Prefetch("members", MemberModel.objects.filter(isActive=False, country="CN")) ).distinct() But I get the result is [{'group_name': 'GROUP_A', 'id': 1, 'members': []}, {'group_name': 'GROUP_B', 'id': 2, 'members': []}, {'group_name': 'GROUP_C', 'id': 3, 'members': [{'country': 'CN', 'isActive': False, 'name': 'ENWK'}, {'country': 'CN', 'isActive': False, 'name': 'LKMP'}]}] I want to get [{'group_name': 'GROUP_C', 'id': 3, 'members': [{'country': 'CN', 'isActive': False, 'name': 'ENWK'}, {'country': 'CN', 'isActive': False, 'name': 'LKMP'}]}] What can I do? -
How do write this function view in Auth view LoginView?
I have written function based view i need this to be written in class based view LoginView views.py def manager_login(request): current = User.objects.filter(is_manager = True) if request.method == 'POST': pm_form = AuthenticationForm(data=request.POST) if pm_form.is_valid(): username = pm_form.cleaned_data.get('username') password = pm_form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: if user in current: login(request,user) return redirect(reverse('pm_dashboard')) else: messages.error(request,"Invalid Username or Password") else: messages.error(request,"Invalid Username or Password") return render(request, 'app/pm_login.html',context={'form':AuthenticationForm(),}) -
How to disable upstream buffering Nginx + Docker + Gunicorn?
I'm trying to use Nginx as proxy server between client and Gunicorn. Nginx, Gunicorn (Django) are Docker's containers. Problem is I can't disable buffering of upstream when I send large file from Client to Django App. TTFB time is quite small, thus my progress bar (which use xhr.upload.progress event) becomes 100% very fast (less than second). Then I have to wait 30 sec while file will be upload to server. Here are my settings. Please, help. I've tried many configurations trying to set buffer size to zero etc., check many answer on StackOverflow, but nothing helps. docker-compose.yaml ... services: db: image: postgres:12.4 volumes: - postgres_data:/var/lib/postgresql/data/ restart: always ports: - ${DB_PORT}:${DB_PORT} env_file: - ./.env backend: build: ./src/backend volumes: - RUDZASV0021:/code/storage/RUDZASV0021 - logs:/code/logs restart: always depends_on: - db env_file: - ./.env nginx: build: context: . dockerfile: ./src/frontend/Dockerfile volumes: - ./docker-settings/default.conf:/etc/nginx/conf.d/default.conf:ro restart: always ports: - 80:80 - 443:443 depends_on: - backend Backend Dockerfile FROM python:3.8.7-slim WORKDIR /code COPY . . RUN pip install -r /code/requirements.txt RUN apt-get update && apt-get install -y mc CMD gunicorn entrypoints.wsgi:application --workers=4 --worker-class=gevent --timeout=90 --graceful-timeout=10 --bind 0.0.0.0:8000 Nginx Dockerfile FROM nginx:1.20.0 WORKDIR /frontend COPY ./src/frontend/dist . WORKDIR /cert COPY ./cert/device.key . COPY ./cert/device.crt . Nginx default.conf upstream hello_django … -
Django CSRF Token error or missing with Ajax POST request
I am trying to integrate ajax into a web application with the Django framework. I am however having a hard time trying to make a simple ajax call to work. I want to make a DB connection using a form (where users input the DB credentials), call the API, then return the output (whether successful or not). Here's my views.py that is used to handle the API: # -- START from HERE ! class TestConnectionAPI(views.APIView): ''' Test DB Connection from TARGET DB ''' def post(self, request): dbs = (request.data['host'], request.data['port'], request.data['dbname'], request.data['user'], request.data['password'], request.data['schema_name']) try: x = dc.DbConnection(*dbs) x.create_conn() data = x.check_conn() result = { 'message' : 'Success', 'server' : f'Connection established from {data}', 'results':{ 'host':dbs[0], 'port':dbs[1], 'dbname':dbs[2] }, } return Response(result, status=status.HTTP_200_OK) except Exception as e: return Response({'Message':str(e)}, status=status.HTTP_400_BAD_REQUEST) This is my connection.html to display the form (complete code: here) : ... <form method="post"> <div class="modal-body"> <div class="form-group"> <label for="hostname">Hostname</label> <input type="text" class="form-control" id="hostname" name="hostname" aria-describedby="hostname"> </div> <div class="form-group"> <label for="port">Port</label> <input type="number" class="form-control" id="port" name="port" placeholder="e.g., 5432"> </div> <div class="form-group"> <label for="database">Database name</label> <input type="text" class="form-control" id="dbname" name="dbname" placeholder="Enter database name"> </div> <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Enter username"> </div> <div class="form-group"> <label for="password">Password</label> … -
I want to use email field as a main field for users, vendors. But for django-admin I want to use username field usual. Need suggest
models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.fields import EmailField class CustomUser(AbstractUser): email = models.EmailField(('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) is_customer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class VendorDetails(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE) aadhar_number = models.CharField(max_length=200) pan_number = models.CharField(max_length=200) store_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) admin.py from django.contrib import admin from customer.models import CustomUser, VendorDetails # Register your models here. admin.site.register(CustomUser) admin.site.register(VendorDetails) when attempting ----- python manage.py createsuperuser----(File "D:\Yabesh\Django\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username') need help. can I write usermanager for this? Thanks in advance. -
Django ORM fill 0 for missing date
I'm using Django 2.2. I want to generate the analytics of the number of records by each day between the stand and end date. The query used is start_date = '2021-9-1' end_date = '2021-9-30' query = Tracking.objects.filter( scan_time__date__gte=start_date, scan_time__date__lte=end_date ) query.annotate( scanned_date=TruncDate('scan_time') ).order_by( 'scanned_date' ).values('scanned_date').annotate( **{'total': Count('created')} ) Which produces output as [{'scanned_date': datetime.date(2021, 9, 24), 'total': 5}, {'scanned_date': datetime.date(2021, 9, 26), 'total': 3}] I want to fill the missing dates with 0, so that the output should be 2021-9-1: 0 2021-9-2: 0 ... 2021-9-24: 5 2021-9-25: 0 2021-9-26: 3 ... 2021-9-30: 0 How I can achieve this using either ORM or python (ie., pandas, etc.)? -
How can i list all the functions in the class models using terminal?
from django.db import models How can i list all the functions in the class models using terminal? -
Vimeo video to domain-level privacy not working in Django
I have an app built on django framework where I want to embed my own vimeo videos and I want the video to play in my website only. For that I restricted the video to domain-level privacy. But still it's showing error in my website as Sorry Because of its privacy settings, this video cannot be played here. -
When running pipenv install for Django project gets the error "No matching distribution found for django-supervisor==0.4.0"
I get this error when trying to install the dependencies of a Django project creating a virtual environment with pipenv When running pipenv install inside the pipenv shell I get this error. Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: No matching distribution found for django-supervisor==0.4.0 Any solutions to try? -
Deploy django with kubernetes ingress
I am unable to setup path for django application form kubernetes nginx. The application is running fine on local development but not with kubernetes. It says Failed to connect Minimal reproduceable example <values.yaml> imageName: ingestion-dashboard replicas: 1 ingressAnnotations: nginx.ingress.kubernetes.io/use-regex: "true" ingressRules: - path: /dashboard portName: http <deployment.yaml> {{ include "ingestion-dashboard.deployment-header" . }} spec: {{ include "ingestion-dashboard.workerNodeSelector" . | indent 6 }} containers: - name: ingestion-dashboard {{ include "image" . | nindent 10 }} env: - name: SOME_ENV value: SOME_VAL ports: - containerPort: 4781 hostIP: 0.0.0.0 <service.yaml> apiVersion: v1 kind: Service metadata: name: ingestion-dashboard labels: {{ include "ingestion-dashboard.labels" . | indent 4 }} spec: ports: - name: http port: 4781 protocol: TCP targetPort: 4781 selector: app.kubernetes.io/name: {{ include "ingestion-dashboard.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} <urls.py> {in django} urlpatterns = [ path('/dashboard/', include(running_urls.urlpatterns)) ] Port `4781` is configured everywhere (docker file as well) below is the output of k get service ingestion-dashboard -o wide NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE ingestion-dashboard ClusterIP 10.69.37.77 <none> 4781/TCP 13h This is not working. The same setup runs fine when used for flask app. But this is not running for django. Nginx and django apps have no errors as Nginx is running fine for others(including … -
I am trying to view and download a file that I have uploaded using django web application. The web does not open when clicking on view or download
Here is my HTML home.html template. <a href="{{MEDIA_URL}}/{{post.file_field.url}}" class="btn btn-warning" target="_blank">View</a> <a href="{{MEDIA_URL}}/{{post.file_field.url}}" class="btn btn-info mx-4" download>Download</a> settings.py MEDIA_ROOT = BASE_DIR / 'media/' MEDIA_URL = 'media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('photoapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get an object's id and use it for child's query?
def customer(request, customer_id): """Displays customer profile""" customer = Customer.objects.get(id=customer_id) entries = customer.entry_set.order_by('-date_added') subentry = SubEntry.objects.get() context = {'customer': customer, 'entries': entries, 'subentry': subentry} return render(request, 'crm/customer.html', context) I have three classes, Customer, Entry and SubEntry. Customer is a ForeignKey to Entry and Entry is a ForeignKey to SubEntry. Each class has a textfield whose id I can access through the python shell. Currently, I have customer.html displaying a loop that iterates through the entries for a customer. Is there are better way to show this information and print out the subentry for each entry? -
How to redirect to same page after posting in django?
In my django application, I have a form that redirects to a new page if the form is valid. On that new page, I want to include a new form where I can add time slots. How can I set my function in views.py so I can redirect to the same page after inputing the start_time and end_time for the timeslot? This is what I have so far: In models.py class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) food_avail_id = models.ForeignKey(FoodAvail, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.start_time) + "-" + str(self.end_time) In forms.py: class TimeSlotForm(ModelForm): class Meta: model = TimeSlot fields = ["start_time", "end_time"] In views.py: def create_timeslots(request): if not check_existing_timeslot(request): instance = TimeSlot() data = request.POST.copy() data["time_slot_owner"] = request.user data["food_avail_id"] = FoodAvail.objects.get(author=request.user) form = TimeSlotForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: instance = get_object_or_404(TimeSlot, time_slot_owner=request.user) form = TimeSlotForm(request.POST, request.FILES, instance=instance) if request.method == "POST": form = TimeSlotForm(request.POST or None, instance=instance) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) else: form = TimeSlotForm(instance=instance) return render(request, "food_avail/view_food_avail.html", {"timeslot": form}) My HTML template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> {{ field.label }} <strong>{{ error|escape … -
How to have a two parallel ListViews for near identical CreateView views in Django
I have the following Django code. models.py class Article(models.Model): title = models.CharField(max_length=255) #Body is the "body" of our entry - self explanatory. comment = models.TextField() views.py class ArticleListView(ListView): model = Article paginate_by = 50 fields = ('title', 'comment') template_name = 'article_list.html' class ArticleCreateView(CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'comment') I simplified (removed unecessary details from the code) the code, as there are DetailViews and UpdateViews which are pretty standard. What I would like to do is add something like the following to my views.py class ArticleListView2(ListView): model = Article paginate_by = 50 fields = ('title', 'comment') template_name = 'article_list.html' class ArticleCreateView2(CreateView): model = Article template_name = 'article_new.html' fields = ('title', 'comment') Whereby the ArticleCreateView2 looks identical to the ArticleCreateView except instead of the article getting added to ArticleListView it would get added to ArticleListView2 and when I get to ArticleListView2 I could use an UpdateView feature which after updating would "move" the article to the "original" ArticleListView. Is there any way I can do this simply? Thank you. -
Django: filter by user and Primary Key
in my app the Week model is linked thanks to a OneToOneField to the File model and I'd like to get only the file uploaded by the user themselves and to use all the values in the same model to create a chart. So if User_A post file_id_one (monday=3, tuesday=7 [...]) and file_id_two (monday=4, tuesday=9 [...])I'd like to filter and get only the file posted by the logged in User_A and when the user reach The data.html using a pk "{% url 'data' data.id %}" a chart with the value of file_id_one (monday=3, tuesday=7 [...]) will appear if the pk is 1. if the pk is two then a chart with file_id_two (monday=4, tuesday=9 [...]). So I think I need to filter by user and also by pk? Right now with my code this is the error I'm getting 'WSGIRequest' object has no attribute 'file' . However colors = File.objects.filter(pk=pk) it's actualy working but if I use data = list(Week.objects.filter(pk=pk)[2:] the data variable is blank. MODEL class File(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) docfile = models.FileField(upload_to=path) color = models.CharField(max_length=250) class Week(models.Model): file_doc = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday … -
Django restframework viewset serializer KeyError
I try to POST request but I got KeyError. Exception Location: C:\github\dj-postgres-heroku\get_staff\serializers.py, line 32, in create Here is error location and that line is this. def create(self, validated_data): **profile_data = validated_data.pop('profile')** I try to POST data like this. enter image description here enter image description here { "profile":1, "title": "일단 10만원, 업무 마친 후 바로 입금", "hourly_pay": 12500, "start_date": "2020-05-06", "end_date": "2020-05-09", "start_time": "09:00:00", "end_time": "18:00:00", "content": "간단업무입니다.", "jobs":[1, 2] } Here are my code all. models.py class GetStaffPost(models.Model): profile = models.ForeignKey(Profile, null=True, on_delete=models.CASCADE) # default=1 -> pk=1 title = models.CharField(max_length=30) jobs = models.ManyToManyField(Job, blank=True) # tag랑 비슷 hourly_pay = models.IntegerField(null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) created_at = models.DateTimeField(null=True, auto_now_add=True) content = models.TextField(default='content') class Meta: ordering = ['-created_at'] def __str__(self): return f'{self.pk}: {self.title} - {self.profile.nickname}' serializers.py class GetStaffPostSerializer(serializers.ModelSerializer): profile = serializers.PrimaryKeyRelatedField(read_only=True) jobs = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = GetStaffPost # fields = ['id', 'profile', 'title', 'jobs', 'hourly_pay', 'start_date', 'end_date', # 'start_time', 'end_time', 'created_at', 'content'] fields = "__all__" def create(self, validated_data): # profile, jobs profile_data = validated_data.pop('profile') profile_id = profile_data profile = Profile.objects.get(pk=profile_id) jobs_data = validated_data.pop('jobs') # list? post = GetStaffPost.objects.create(**validated_data, profile=profile) # Direct assignment to the forward side of a many-to-many set … -
How do i run django application without port number
How do i run django application without port number: i had tried Django: Run django app on server without port? but didn't work. -
Django Heroku Migrate Error(?): "You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s)"
So I'm working on hosting a project and on my Heroku dashboard it says it's live, but every time I try to access it I get a 500 Server Error, even when trying to access it locally via Heroku CLI. I tried running migrations because I get the following warning: You have 21 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, recipe, sessions, users. Run 'python manage.py migrate' to apply them. Even after running makemigrations and migrate, as can be seen in screenshot below, any suggestions to what I might be missing?