Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integer field is not increasing on like
I am building a Blog App and I build a feature of increasing points when someone likes the posts. AND I made an IntegerField to count points when post like. BUT Integer field is not increasing when someone likes the post. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) full_name = models.CharField(max_length=100,default='') points = models.IntegerField(default=1) class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) views.py def blogpost_like_dislike(request, post_id): post = get_object_or_404(BlogPost, pk=blogpost_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): request.user.profile.points += 10 # Increasing Here request.user.profile.save() post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) else: messages.error(request, 'Something went wrong') return redirect('blogposts') I have tried many times but it is still not increasing. Any help would be much Appreciated. Thank You in Advance. -
Bootstrap Modal Not Showing in Django Template
I have spent way too much time troubleshooting this. Does anyone have any idea why this modal won't pop up? It seems that if I remove the table (that takes up most of the code), the modal then works fine. If I remove the CSS, the modal still doesnt work. Don't judge if it's horrible, only started learning Django, HTML, etc. 2 weeks ago 😛 {% extends 'base.html' %} {% load crispy_forms_tags %} {% block head %} <style> .teacher-list { margin-left: 200px; height: 100%; width: 350px; position: fixed; overflow:hidden; overflow-y:scroll; border-right: 1px solid; border-color: #d3d3d3; } .teacher-list-title { line-height: 1.3; height: 4px; } .teacher-list-text { line-height: 1.3; padding-bottom: 0px; font-weight: normal; height: 4px; } .teacher-body { padding-left: 570px; padding-top: 10px; text-align: center; } .icon-only-button { background: transparent; border: none !important; padding: 0 0 0 0; } .search input { padding-left: 10px; height: 30px; width: 220px; border: none; } .line { margin-left: 550px; width: 100%; border-bottom: 1px solid black; position: absolute; } </style> {% endblock %} {% block content %} <div class="teacher-list"> <table class="table"> <tbody> <tr class="search"> <form method="GET" name="search"> <th scope="row"> <input name="search" type="search" placeholder="Search.." value="{{ search_text }}"> </th> </form> <td> <button type="button" class="icon-only-button" data-bs-toggle="modal" data-bs-target="#exampleModal"> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" … -
Unit test cases in Django not executed
I've my Django project's unit test set up. Strangely, regardless of how many I run the command still the test cases didn't get executed. The resulting test always shows ZERO. I suspect is the files/directories permissions issue. Your help and advice are much appreciated. Please see the screenshots below. -
Django smart_str 'NoneType' object has no attribute
In django, I want to download the data to excel using the smart_str, but some record of user dont have data or blank some field like in the error below, how can i do with smart_str which should be unnecessary or error free if no data can be detected? def downloadcv(request): response = HttpResponse(content_type='text/csv') # decide the file name response['Content-Disposition'] = 'attachment; filename="StudentEnrollmentRecord.csv"' writer = csv.writer(response, csv.excel) response.write(u'\ufeff'.encode('utf8')) writer.writerow([ smart_str(u"Guardians_Fullname"), smart_str(u"Guardians_Address"), smart_str(u"Contact_Number"), ]) reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time') for report in reports: last_name = report.Student_Users.Parent_Users.Guardian_LastName or "" first_name = report.Student_Users.Parent_Users.Guardian_FirstName or "" initial = report.Student_Users.Parent_Users.Guardian_Middle_Initial or "" writer.writerow([ smart_str(last_name, first_name, initial), return response if response is not None else 'None' this is the error i get -
Django Queryset objects and accessing model field attributes
Technology Django 3.2 Model I have a model with fields with properties like max_length and decimal_places. View Furthermore I have a view returning a Queryset with model objects. I would like to access the field attribute like so: Template {{ model_name.field_name.max_length }} {{ model_name.field_name.decimal_places }} also the following does not work: {{ model_name.field_name.field.max_length }} {{ model_name.field_name.field.decimal_places }} Any ideas? It seems to work with a model form, in which the latter examples work. Thanks in advance. -
getting current user in django-import-export
I want to automatically add current user in a field before importing in django-import-export. class MyModel(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100) img = models.ImageField(upload_to='model', null=True, blank=True) slug = models.SlugField(max_length=100) -
In Django Rest Framework, how to parse an object as a field in a serializer?
Suppose I have the following serializer for a Product instance. from rest_framework import serializers class Product: def __init__(self, code): self.code = code class ProductSerializer(serializers.Serializer): code = serializers.CharField() def create(self, validated_data: dict): return Product(validated_data['code']) Now, I can use it like thus to obtain a Product instance from the request data: serializer = ProductSerializer(data=request.data) serializer.is_valid() product = serializer.save() # product is a `Product` instance Now, I have another serializer that have a product as a field: class CompareProductRequestSerializer(serializers.Serializer): product1 = ProductSerializer() product2 = ProductSerializer() Now if I do this: serializer = CompareProductRequestSerializer(data=request.data) serializer.is_valid() p1 = serializer.validated_data['product1'] p2 = serializer.validated_data['product2'] Then p1 and p2 would be dictionaries, and not Product instances (e.g., p1 == {code: '12345'}). How can I get p1 and p2 to be Product instances instead? -
Alert box is unable to show a variable Order Id of the order placed
I am using a checkout page to allow users to place order in my shopping website using django. But once the checkout form is filled and submit button is clicked, an alert box pops up: $('#done').click(function(){ console.log({{ord_id}}) alert('Thanks for ordering with us. Your order Id is {{ord_id}} . Use it to track your order.'); localStorage.clear(); }) Look at the variable inside the alert box string. I am unable to get its value enter image description here The function in views.py which points to the HTML page containing this javascript part, looks like this: def checkout(request): if request.method=="POST": itemsJson=request.POST.get("itemsJson","") name=request.POST.get("name","") email=request.POST.get("email","") phone=request.POST.get("phone","") address=request.POST.get("address1","")+" "+request.POST.get("address2","") city=request.POST.get("city","") state=request.POST.get("state","") zip=request.POST.get("zip","") place_order=Order(itemsJson=itemsJson,name=name,email=email,phone=phone,address=address,city=city,state=state,zip=zip) place_order.save() orderid=place_order.check_id update=UpdateOrder(order_id=orderid,update_email=email,update_desc="Your Order has been Placed") update.save() params={'ord_id':orderid} return render(request,'shop/checkout.html',params) return render(request,'shop/checkout.html') What should I do?? -
Django model query selecting related items and excluding current object
I am using Django 3.2 I have an Article model: from taggit.managers import TaggitManager class Article(models.Model): # fields tags = TaggitManager() In my views, I try to select related articles (using tag similarity as the "distance metric"). This is the statement that returns related articles in my view handling logic: # Note: self.model resolves to `Article` related_posts = self.model.objects.filter(is_published=True, tags__name__in=article_tags_array).exclude(id=article_object.id).prefetch_related().distinct() This statement however, FAILS to EXCLUDE the current object, in the returned QuerySet - despite my *EXPLICITLY invoking exclude() on the returned QuerySet. Why is this happening? How do I fix this, so that the current object is not included in the returned set? -
How to set variable maxValue in django forms
I'm writing a code in django framework for a sales website and the number of available pieces of a certain merchandise is limited. to obtain the number of remaining products I have to call a certain function. Now I wanted to ask if there's any way to call this function in the models.py or forms.py modules or any other way to set this limit. This is my view module: from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import orderForm from regpage.models import User from django.views import View class orderView(View): def get(self, request): form = orderForm() return render(request, "dashboard/order.html", {'form': form,}) This is my forms module: from django import forms from .models import Order class orderForm(forms.ModelForm): class Meta: model = Order fields = ['productCount'] This is my models module: from django.db import models from django.db.models.enums import Choices from regpage.models import User from django.core import validators from django.core.validators import EmailValidator, MaxValueValidator, MinValueValidator class Order(models.Model): userID = models.ForeignKey(User, on_delete=models.CASCADE) productCount = models.PositiveSmallIntegerField() #THE LIMITED FIELD This is my html file: {% extends 'dashboard.html' %} {% block dashTitle %} Order {% endblock dashTitle %} {% block dashContent %} <p style="text-align:center;font-size:30px;"><b> Order Page </b> </p> <form style="text-align:center;font-size:25px" method="POST"> {% csrf_token %} {% … -
MultiValueDictKeyError at /upload_notes
I am unable to solve this error since 10 days. I refer all over google but did not get solution of it. Please someone help me to solve this error. upload_notes.htmlfile <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Notes File</label> <input type="file" class="form-control" name="notesfile" > <input type="submit" class="btn btn-danger mt-2" value="Submit"> </form> views.py def upload_notes(request): if not request.user.is_authenticated: return redirect('login') error="" if request.method=='POST': b=request.POST['branch'] s=request.POST['subject'] n=request.POST['notesfile'] f=request.POST['filetype'] d=request.POST['description'] u=User.objects.filter(username=request.user.username).first() try: Notes.objects.create(user=u,uploadingdate=date.today(),branch=b,subject=s, notesfile=n,filetype=f,description=d,status='pending') error="no" except: error="yes" d={'error':error} return render(request,'upload_notes.html',d) enter image description here This is the error image -
I cannot connect my form to my models for posting of grades
Models.py class YearLevel(models.Model): ... class Section(models.Model): ... class Subject(models.Model): ... class Student(models.Model): first_name = models.CharField(max_length = 100, default = '') last_name = models.CharField(max_length = 100, default = '') year_level = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null = True) section = models.OneToOneField(Section, on_delete=models.SET_NULL, null = True) enrolled_subject = models.ManyToManyField(Subject) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null = True) #parent is from user models class StudentGrade(models.Model): PERIOD_CHOICES = [ ... ] student = models.ForeignKey(Student, on_delete=models.CASCADE,) period = models.CharField(choices=PERIOD_CHOICES, max_length = 30) subjects = models.ForeignKey(Subject, on_delete=models.CASCADE) grade = models.DecimalField(default = 75.00, max_digits=4, decimal_places=2) Views.py def postgrade(request): students = Student.objects.all().prefetch_related('enrolled_subject') context = { 'students': students, } if request.method == "POST": data = request.POST grade_list = data.getlist('grade') subject_list = data.getlist('subject') student = Student.objects.get(pk= data.get('studentid')) #this is where they point my error i=0 while i < len(grade_list): enrolled_subject = Subject.objects.get(pk= subject_list[i]) new_grade = StudentGrade(student = student, period= data.get('period'), subjects = enrolled_subject, grade=grade_list[i]) new_grade.save() i+= 1 Postgrade.html(template) My queries are displaying properly, the problem is I get an error when i try to save the form {% for students in students %} <p> <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}"> {{students.first_name}} {{students.last_name}} </a> </p> <div class="collapse" id="collapse{{forloop.counter}}"> <div class="card card-body"> <form method="POST" > {% csrf_token %} <input type="hidden" name="studentid" value="{{students.student.id}}"> <label … -
Display all days in specific month for data
I want to create a table that displays all days of a given month, and then check if this day is in the database, if it displays the necessary data for a given record at the moment i have loop for display all days for month: def example_table(request,pk,month): something = database.filter(pk=pk).all() num_days = monthrange(2021, month)[1] num_days = range(1,num_days+1) context = locals() in template i was add something like that: {%for time in num_days%} {%for x in something%} {%if x.day == time%} table {%endif%} {%endfor%} {%endfor%} but this record is repeated x times. Someone can give me some advice how to do that ? should looks like 1 data data data 2 3 4 data data data ...etc -
UnboundLocalError while using Django Querysets
I am trying to implement the following Django Queryset in my webapp: from django.db.models import When, Case, Value, Sum, IntegerField, F from django.shortcuts import render,redirect from hr.models import * def mobile_recharge(request): S=['0'] T=['1'] B=['A','B','C'] db_obj1=BillsPayment.objects.using('MBDB').all() db_obj2=BillsService.objects.using('MBDB').all() while db_obj1.values('BILLER_ID')==db_obj2.values('BILLS_SERVICE_CODE') and db_obj2.values('BILLS_TYPE')=='3': data = db_obj1.annotate( Transaction_type=F('BILLER_ID'), Success=Sum(Case( When(ERROR_CODE__in=S, then=Value(1)), default=Value(0), output_field=IntegerField() )), Technical_declines=Sum(Case( When(ERROR_CODE__in=T, then=Value(1)), default=Value(0), output_field=IntegerField() )), Business_declines=Sum(Case( When(ERROR_CODE__like='B',then=Value(1)), When(ERROR_CODE__in=B, then=Value(1)), When(ERROR_CODE__isnull=True, then=Value(1)), default=Value(0), output_field=IntegerField() )) ).order_by(Transaction_type) return render(request,'hr/test.html',{'model':data}) Which is supposed to execute the following SQL Query: SELECT 'MOB' AS TYPE, SUM(case when BP.ERROR_CODE in ('0') then 1 else 0 end) SUCCESS, SUM(case when BP.ERROR_CODE in ('1') then 1 else 0 end) TECHNICAL_DECLINES, SUM(case when (BP.ERROR_CODE LIKE '%ERR%' OR BP.ERROR_CODE in ('A','B','C') or BP.ERROR_CODE is null ) then 1 else 0 end) BUSINESS_DECLINES FROM BP,BS WHERE BP.BILLER_ID=BS.BILLS_CODE AND BS.BILLS_TYPE='3'; When I run the server using the python manage.py runserver command however the browser is giving the UnboundLocalError: Please help me with this. Thank you. -
Identify the Timer for uploading the data sheet ( excel ) in python
I have the excel sheet of 10 k records. If I upload the excel data it will take around 58 secs to complete the method. In my web application is it possible to say the this file upload will be completed in 58 secs in user notification ? whether we are able to identify the seconds/minutes based on records(excel file) in python / Django / celery / RabbitMQ process > -
Django3 Background Tasks not working with Apache2 + mod_wsgi
use django-background-tasks to run some heavy tasks in the background in my Django application. On my local machine everything works fine. However, if I deploy my application in production with Apache and mod_wsgi, the scheduled tasks are not executed. Instead, if I run the command python manage.py process_tasks Executing the above command will cause the Apache server to stop working and must be restarted. In the apache error file I found: [Sat Aug 14 04:53:43.420851 2021] [wsgi:warn] [pid 5573] self.sig_manager = SignalMana ger() [Sat Aug 14 04:53:43.420855 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/background_task/utils.py", line 20, in init [Sat Aug 14 04:53:43.420859 2021] [wsgi:warn] [pid 5573] signal.signal(signal.SIGTSTP, self.exit_gracefully) [Sat Aug 14 04:53:43.420874 2021] [wsgi:warn] [pid 5573] mod_wsgi (pid=5573): Callback reg istration for signal 10 ignored. [Sat Aug 14 04:53:43.420963 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/web_myboot/d jango_boot/core/wsgi.py", line 18, in [Sat Aug 14 04:53:43.420971 2021] [wsgi:warn] [pid 5573] management.call_command('proc ess_tasks') [Sat Aug 14 04:53:43.420977 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/django/core/management/init.py", line 181, in call_com mand [Sat Aug 14 04:53:43.420981 2021] [wsgi:warn] [pid 5573] return command.execute(*args, **defaults) [Sat Aug 14 04:53:43.420985 2021] [wsgi:warn] [pid 5573] File "/home/ubuntu/.virtualenvs /dj/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute [Sat Aug 14 04:53:43.420989 2021] [wsgi:warn] [pid 5573] output … -
problem with updating date in django-rest
I've tried to make a form that contains date-to-published. by default, when we register a new form, automatically adds a date of now! when I try to update it using postman, it seems nothing to be changed at all ! models.py class Student(models.Model): first_name = models.CharField(max_length=100, default=None,blank=True) last_name = models.CharField(max_length=100,default=None,blank=True) edu_code = models.CharField(max_length=100,default=None) national_code= models.CharField(max_length=100,default=None) date_to_published = jmodels.jDateField(blank=True,auto_now_add=True) phone_number = models.CharField(max_length=30,blank=True) student_sign = models.ImageField(upload_to = image_saving,blank=True) admin_fname = models.CharField(max_length=100) admin_lname = models.CharField(max_length=100) item = models.CharField(max_length=100,blank=True) img1 = models.ImageField(upload_to= image_saving, blank=True) img2 = models.ImageField(upload_to= image_saving, blank=True) img3 = models.ImageField(upload_to= image_saving, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' def __unicode__(self): return f'{self.first_name} {self.last_name}' serlializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','first_name','last_name','edu_code','national_code','student_sign','date_to_published','phone_number','admin_fname', 'admin_lname','item','img1','img2','img3'] read_only_fields = ['admin_fname','admin_lname'] def create(self, validated_data): request = self.context.get("request") return Student.objects.create(**validated_data,admin_fname=request.user.first_name,admin_lname=request.user.last_name) def update(self, instance, validated_data): instance.date_to_published = validated_data.get('date_to_published', instance.date_to_published) instance.save() return instance views.py class StudentViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] #permission_classes = [IsAdminUser] queryset = Student.objects.all().order_by('-id') serializer_class = StudentSerializer filter_backends = [filters.SearchFilter] search_fields = ['edu_code','national_code',] enter image description here this is my new date to change an old date but I get the old date as Response. me request method is PUT -
Original exception text was: 'RelatedManager' object has no attribute 'type'. - Django Rest
models.py class Sequence(models.Model): category_id = models.ForeignKey(SequenceCategory, on_delete=models.CASCADE) description = models.TextField() code = models.CharField(max_length=50) total_divisions = models.IntegerField() status = models.BooleanField(default=True) def __str__(self): return self.code class SequenceValue(models.Model): TYPE_CHOICES =( ('N', 'Numeric'), ('A', 'Alphabet') ) sequence_id = models.ForeignKey(Sequence, on_delete=models.CASCADE, blank=True, null=True, related_name='Sequence_details') type = models.CharField(max_length=100, choices=TYPE_CHOICES) value = models.CharField(max_length=50) starting_value = models.CharField(max_length=50, null=True, blank=True) increment_value = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.value serializers.py class SequenceValueSerializer(serializers.ModelSerializer): class Meta: model = SequenceValue # fields = '__all__' exclude = ['sequence_id'] class SequenceSerializer(serializers.ModelSerializer): Sequence_details = SequenceValueSerializer() class Meta: model = Sequence fields = '__all__' def create(self, validate_data): Sequence_details_data = validate_data.pop('Sequence_details') sequence_id = Sequence.objects.create(**validate_data) SequenceValue.objects.create(sequence_id=sequence_id, **Sequence_details_data) return sequence_id views.py class SequenceCreate(ListCreateAPIView): queryset = Sequence.objects.all() serializer_class = SequenceSerializer Why do I get the error? When I refer n number of articles I got a solution that put many=True something like this. Sequence_details = SequenceValueSerializer(many=True) But when I make changes on that then I can't get the Sequence details fields. How can I fix this issue. Can you give a solution please? Actual error- Got AttributeError when attempting to get a value for field type on serializer SequenceValueSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text … -
Certain pages on Heroku return server error 500
good day, I was hoping my first post would be something helpful to other but here we go with a question instead. I'm fairly new to python/django and i'm working on an ecommerce project. My deployed site worked flawlessly, but all of a sudden I started getting server error 500 when trying to access login/register/admin pages. To my untrained eye it seems it's only affecting pages connected with allauth. When I turned on debug on my heroku app it returns "DoesNotExist" / "Site matching query does not exist". Only thing I fiddled with before it stopped working is "sites" in admin panel where I deleted "example.com" and put my site name as it was needed for email sending templates". Could it be that changing site name in admin panel made it this way, and if so, how can I revert the changes now that I can't access my admin panel? any help is greatly appreciated nsum -
FreeBSD: How to run UWSGI with python37 instead of python38
I am running a website on a FreeBSD 13.0 machine. The website is running in a python37 virtual environment with Django. I installed uwsgi on the operating system (not in the virtual environment) so that I can make the website auto-start when the system starts and run it in emperor mode. I have previously set this up successfully before but I ran into some issues when python38 was released. When I install uWSGI 2.0.19.1, it pulls python38 along with it, and when I run uwsgi, it runs with python version 3.8. I confirmed that both versions of python are installed, but uwsgi prefers to use python38. My question is, how can I specify to uwsgi which python version to use? I want to make uwsgi run with python37 instead of py38. I know that an alternative could be to install a different version of uwsgi but how would I go about installing a different version? Only the latest version appears with 'pkg.' -
is there any way to solve this error need some good insights
my error is :- groups.Groups.members: (fields.E303) Reverse query name for 'groups.Groups.members' clashes with field name 'auth.User.groups'. HINT: Rename field 'auth.User.groups', or add/change a related_name argument to the definition for field 'groups.Groups.members'. from django.db import models from django.utils.text import slugify import misaka from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class Groups(models.Model): name = models.CharField(max_length=264) slug = models.SlugField(allow_unicode=True,unique = True) description = models.TextField(blank = True,default = '') description_html = models.TextField() members = models.ManyToManyField(User,through = 'GroupMember') def __str__(self): return self.name def save(self,*args,**Kwargs): self.slug = self.slugify(self.name) self.description_html = self.misaka(self.description) super().save(*args,**Kwargs) def get_absolute_url(self): return reverse('groups:single',Kwargs={'slug':self.slug}) class Meta(): ordering = ['name'] class GroupMember(models.Model): group = models.ForeignKey(Groups,related_name='membership',on_delete = models.CASCADE) user = models.ForeignKey(User,related_name = 'user_group',on_delete = models.CASCADE) def __str__(self): return self.user.username class Meta(): unique_together=['group','user'] -
How to copy files from host to docker named volume
I started a Django app with docker with bind host to handle user uploads but now I want to migrate to named volumes but I already have files in my host, so I was wonderings how can I copy the files from the host to the volume, this is my docker-compose for my web container: version: '3' services: db: restart: always image: "postgres:13.2-alpine" container_name: db ports: - "5432:5432" env_file: - ./.env.dev volumes: - ./pgdata:/var/lib/postgresql/data web: container_name: web restart: always build: context: . dockerfile: ./docker/development/Dockerfile environment: DEBUG: 'true' DJANGO_SETTINGS_MODULE: myapp.app_settings.development command: sh ./docker/development/runserver.sh ports: - "8000:8000" env_file: - ./.env.dev volumes: - .:/app # Enable code reload - django-static:/app/run/static - django-media:/app/run/media depends_on: - db volumes: django-static: django-media: And this is my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY ./requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # COPY . /app ADD . /app RUN apt-get clean && apt-get update && apt install -y netcat COPY ./docker/development/entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] There is a way to copy my uploads from host: /home/art/myapp/run/media and /home/art/myapp/run/static to volumes django-static and django-media ? Also, How I can backup the files from the volume? -
Using Django StreamingHttpResponse in template
How can one use the streamed data using Django's StreamingHttpResponse in a template? This is so trivial, yet I found 0 info about this online. views.py : import VideoCamera def Gen(feed): while True: something = feed.do_something() yield (something) def Use(request): return StreamingHttpResponse(Gen(VideoCamera()), content_type='text') urls.py : urlpatterns = [ path('use_feed_data/', views.Use, name='use_feed_data'), ] in template : {% url 'use_feed_data' %} The result in the template is the path "/use_feed_data/" instead of the streamed data, yet in localhost:8000/use_feed_data/ I'm able to see all the streamed data. How can I access that streamed data in the main template? -
Django profile picture: The 'ImageField' attribute has no file associated with it
thank you for taking your time! This is my problem, I'm working on a little project about a blog with Django. When I upload a profile picture, everything works fine, but when I don't, the "The 'ImageField' attribute has no file associated with it." error prompts. The thing is that I uploaded a default pic in the static dir and created and if to manage that. If the user doesn't have a photo, just show the image from the static dir. Here are the HTML and model files. <div class="ui items"> <div class="item"> {% if post.author.profile.image.url %} <div class="ui small image"> <img src="{{ post.author.profile.image.url }}"> </div> {% else %} <div class="ui small image"> <img src="{% static 'static/ProyectoBlog/images/default-profile-pic.png' %}"> </div> {% endif %} <div class="content"> <a class="header">{{ post.author.first_name }} {{ post.author.last_name }}</a> <div class="meta"> <span>About</span> </div> <div class="description"> <p>{{ post.author.profile.bio }}</p> </div> <div class="extra"> <a href="{{ post.author.profile.fb_url }}"> <i class="big facebook icon"></i> </a> <a href="{{ post.author.profile.tw_url }}"> <i class="big twitter icon"></i> </a> <a href="{{ post.author.profile.ig_url }}"> <i class="big instagram icon"></i> </a> </div> </div> </div> </div> class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(max_length=500) image = models.ImageField(upload_to="bios", blank=True, null=True, default='static/ProyectoBlog/images/default-profile-pic.png') fb_url = models.CharField(max_length=255, null=True, blank=True) tw_url = models.CharField(max_length=255, null=True, blank=True) … -
New Graphene-Django installation gives ImportError for schema.schema path in settings.py when accessing /graphql/
Important part of the traceback Exception Type: ImportError at /graphql Exception Value: Could not import 'website.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'motophoto.website'. This is a brand new Graphene-Django install with barely any work. I followed the tutorial on the website and have done everything correct, checked and double checked. Have been looking at other SO answers with no luck. Made sure the recommended versions are installed. Checked for misspellings and tried different paths Restarted the Django server many times Project Structure Relevant Source Code I don't really want to upload the entire project, but comment if you need a look at a specific file other than what's provided.