Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get Django stdout forwarded to Elastic Beanstalk logs?
My Django application runs on Elastic Beanstalk, using Amazon Linux 2 platform. My problem is that output to stdout (e.g. print ("hello world") ) is not stored in any log file found in the log bundle. I just migrated to AL2 from the older Amazon Linux platform. With the legacy platform I did not have issues with logs. -
How to get Django Admin CSS styles to work on Elastic Beanstalk?
I'm running Django on Elastic Beanstalk, Amazon Linux 2 platform. Proxy server is nginx. Django admin does work, but the styles do not. I get the following error message: Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. How can I fix this? -
How to read pdf file from frontend using Django framework?
I am trying to read pdf file content using Django framework. what I have tried till now is def upload(request): try: if request.method == 'POST': if request.FILES['document'].name.split('.')[-1] == "pdf": input = request.FILES['document'].read().decode() print(input) return HttpResponse('upload Products') except Exception: traceback.print_exc() input = request.FILES['document'].read().decode() // This method gives error like 'utf-8' codec can't decode byte 0x9c in position 72: invalid start byte input = request.FILES['document'].read() I am not able to decode the Output b'%PDF-1.4\n%\xc3\xa4\xc3\xbc\xc3\xb6\xc3\x9f\n2 0 obj\n<</Length 3 0 R/Filter/FlateDecode>>\nstream\nx\x9c\xdd\x1b\xcb\x8e\xe3\xb8\xf1\xde_\xe1\xf3\x02\xee\x88ER\x94\x80\x81\x01\xdbm\x07\xd8\xdbf\x1a\xc8!\xc8\xc9\xc9&Xx\x03d/\xfb\xfb xa9'Yz\xd8\xed\xe9\xde\x1c\xa6\xd1\x18O\x95$\x92\xf5\xae\x12Y\xea\x9e\xc3\xe6\xf7\xa7\xffn\xbaM\x87P\x1e\xf33l\x86\x14\x9e\x87\xcdo\xff|\xfa\xeb\x0f\x9b\xff<\x85\r\xfd\xfd\xf6\xaf\xa7\x0eo\xc0\xe6\xd7'{\x086W\x1d@C\xaf:\x05\xfd/\xf7 xfe\xfd\xf4\xf3\x0f\x93A\xd1\r\x8a\xf7\x0619\xf8\x87\x8b\x1e^\x9fr\xc6'\x06\xc0\x9f\xd7\x7fl\xfetFj\x86\xcd\xeb\xcf_\xba\xb0{\xfd\xe5\xe9\xf4\xfa\xf4\xd3\xecy\x08\xf0\x9c\xee\x0f\xe8\x9e\xbb\xae\x0c\t\xd7\x8e\xb9\x1fz\xfc?\r\x103M\x00 cA\xe6\x87\xd8\xe3\x1c\xbf>\x11q\x02_\x99P\x12MQ\x16\xd2\x1c\xd3\xe7\xfc\x0c\xd7'\x91\xc2\x8d\xf5\xfe\xf2g\xa2\xfd\xb9\xc4<l~G\x06~DI\xff Do I have to do anything with content type which is application/pdf -
Accessing "request" object within Jinja2 "environment" function
I am currently working on a project which heavily uses Jinja2 for template rendering. The relevant code looks like this: settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'request/templates'), os.path.join(BASE_DIR, 'core/templates'), os.path.join(BASE_DIR, 'vaux/templates')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'myapp.jinja2.environment', 'extensions': ['jinja2.ext.i18n', 'jinja2.ext.do', 'vcom.jinja2.blockcache', 'jinja2.ext.with_'], 'autoescape': False, 'bytecode_cache': FileSystemBytecodeCache(CACHE_DIR), 'auto_reload': True, 'lstrip_blocks': True, 'trim_blocks': True, }, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] myapp/jinja2.py file looks like this: def environment(**options): env = Environment(**options) env.globals.update({ 'some_global_context_var': 'Some value' }) # how do I access request ? So that I can write something like request.META['HTTP_HOST'] So my goal now is to try to get access to the request object, so that I can write something like request.META['HTTP_HOST']. Is there any way to do that ? Prior to this, I tried to come up with a global context var using Django's vanilla `context processors' concept, but with Jinja2 it is not so easy. -
Query an attribute of many to many object in django
In my Django Model I want to query a many to many related object and get value of another attribute Models.py class FlowKits(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) trip_cost = models.IntegerField(default=0) class Flow(models.Model): flow_name = models.CharField(max_length=500, default=0) kits = models.ManyToManyField(FlowKits) owner = models.ForeignKey(User, on_delete=models.CASCADE) How can I get the trip_cost of a flow whose flow_name = 'Foo' and kit = 'bar'? I got the Flow object but how to proceed? t = Flow.objects.get(flow_name = 'Foo') -
Don't put the current value in the form
Faced such a problem that the current values about the user are not passed to the form. What I want to do is to combine the user model and the profile model, then display the current user data in two forms for editing. It seems to be done correctly, but for some reason it does not work. Please tell me who understands this) file views.py: class ProfilePage(UpdateView): model=Profile template_name="market/profile.html" form_class=ProfileUpdateForm second_model = User second_form_class= UserUpdateForm def get_context_data(self, **kwargs): context = super(ProfilePage,self).get_context_data(**kwargs) context['UserUpdateForm'] = UserUpdateForm( prefix='UserUpdateForm', data = self.request.POST, instance=self.request.user, ) context['ProfileUpdateForm'] = ProfileUpdateForm( prefix='ProfileUpdateForm', data = self.request.POST, files = self.request.FILES, instance=self.request.user.profile, ) return context def post(self, request, *args, **kwargs): super(ProfilePage,self).post(self, request, *args, **kwargs) context = self.get_context_data(**kwargs) if context['UserUpdateForm'].is_valid(): context['UserUpdateForm'].save() elif context['ProfileUpdateForm'].is_valid(): context['ProfileUpdateForm'].save() return self.render_to_response(context) file forms.py: class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ("username",) class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=('valuta','slug','avtor') file models.py: class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) avtor=models.ImageField(default='user_images/default.jpg', upload_to='user_images',blank=True) slug=models.SlugField(max_length=50, unique=True,blank=True) valuta=models.ForeignKey(Valuta,default="5", on_delete=models.CASCADE) -
How to preserve form values after submit?
I'm preparing a simple search/filter form for my django project and I would like to have all options kept after clicking 'submit' button. I'm using select options, inputs and checkboxes. Is there any all-purpose solution for this? The method used is GET Here's the code: <form method = "GET" action = "."> <div class="form-row"> <div class="form-group col-8"> <label for="filter_by_name">Search by name</label> <div class="input-group"> <input class="form-control py2 border-right-0 border" type="search" name="filter_by_name" placeholder="Name contains.."/> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> <div class="form-group col-md-4"> <label for="filter_by_shop">Search by shop</label> <select id="filter_by_shop" class="form-control" name="filter_by_shop"> <option selected>All shops</option> <option>first shop</option> <option>second shop</option> </select> </div> </div> <div class="input-group col-md-8 checkboxes"> <span> <input type="checkbox" name="first" value="first"\> <label >first</label> <input type="checkbox" name="second" value="second"\> <label >second</label> <input type="checkbox" name="third" value="third"\> <label >third</label> </span> </div> <div class="form-group col-md-2"> </div> <button type="submit" class="btn btn-primary">Search</button> </div> </form> def myView(request): qs = v_pricenew.objects.all().order_by('PRICE') filter_by_name = request.GET.get('filter_by_name') filter_by_shop = request.GET.get('filter_by_shop') if is_valid_queryparameter(filter_by_name): qs = qs.filter(NAME__icontains=filter_by_name) if is_valid_queryparameter(filter_by_shop): qs = qs.filter(SHOP__icontains = filter_by_shop) filter_list = [] if first: filter_list.append('firstCat') if second: filter_list.append('secondCat') if third: filter_list.append('thirdCat') if len(filter_list) != 0: qs = qs.filter(CAT__in = filter_list) context = { 'queryset': qs } return render(request, 'compare_app/main.html', context) I managed to achieve this using … -
How do I make a search bar that will get a query from saved entry without a model
Def search(request): Lists = util.lists.entries() Object_list = lists.objects.GET.get('q') Return object_list -
Render variables in DB strings?
I'm building a survey tool. The questions will be derived from templates. But of course, it would be nice if they would contain personalized elements, too. Here is an example: How many products from {{ brand_name }} do you buy per week? This information should not be rendered in a HTML template but rather sent via JSON. Django comes with functions like render_to_string that take a context object and a template path. But I'm not sure if they can be used here. I'm super happy for any help! Thanks! -
How can I do to add the condition AND using exlude?
I have this query : MyTable.objects.filter(date=date).exclude(starthour__range=(start, end), endhour__range=(start, end)) But I want exclude the queries that starthour__range=(start, end) AND endhour__range=(start, end) not OR. I think in this case the OR is used. Could you help me please ? Thank you very much ! -
Enable user to add item to a list dynamically using Django and Ajax
I am trying to build functionality into my webapp the does the following: A user searches for an address Nearby cafes are pulled from a database table and displayed to them The user is able to click an "add-to-list" tag The cafe name/address are added to a list made by the user I have successfully built 1 and 2. I am struggling with 3 and 4. The Current Situation I am trying to pass the cafeName at this stage via an AJAX post call, but it doesn't look like it is firing correctly. Initially I was trying to do this with AJAX and views.py function but was advised to use Django Rest Framework, so I am now creating an api and using Ajax to pass the cafe details async. The Code At this stage my models.py file looks like this class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) class Meta: managed = False db_table = 'a_cafes' class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? class Venues(models.Model): venue_name = models.CharField(max_length=255) venue_address = models.CharField(max_length=100) venue_long = models.FloatField(null=True) venue_lat = models.FloatField(null=True) venue_geolocation = models.PointField(geography=True, blank=True, … -
Request parameter explanation
In messages.success(request, 'Account was created'+user) is the request keyword requesting messages.success or 'Account was created'+user? -
Programming Error at/ relation "project_app_category" does not exist
I am trying to run "docker-compose up" and my django app is not seeing all my Database tables. I have run migrations multiple times and i have also syncdb but it's all to no avail. I am using PostgreSQL as my db and all the database tables exist in the DB. This is my settings.py file DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "Vendor", "USER" : "postgres", "PASSWORD" : "sangobiyi", "HOST" : "db", "POST" : "5432", } } docker-compose.yml version: '3.4' services: db: image: postgres:latest restart: always environment: POSTGRES_DB: 'Vendor' POSTGRES_USER: 'postgres' POSTGRES_PASSWORD: 'sangobiyi' web: build: . image: temiloluwaelizabeth/vendor-business:v1.0.0 command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/vendor_business ports: - "8000:8000" depends_on: - db Dockerfile FOM tiangolo/uwsgi-nginx:python3.8 LABEL Name-code6 Version=0.0.1 EXPOSE 8000 ENV LISTEN_PORT=8000 ENV USWGI_INI uswgi.information WORKDIR /app ADD . /app RUN chmod g+w /app ADD requirements.txt . RUN python -m pip install -r requirements.txt Whenever i change the host to "localhost" in my settings.py file and run python manage.py runserver it works fine but when i change the host in my settings.py to "db" and run docker-compose up it throws the programming error. i have tried multiple times to run migrations and everything has migrated -
If and else statements in Django template
I am doing an encyclopedia project and on the homepage there is a search field where the user can enter in the title of an entry to perform a search. If there is a complete match, then the entry page will load. If there is a partial match then it will lead to a search page that will list some entry suggestions with similar titles. If there is no match or the search was performed without a query, I want the search page to display a message telling the user no entries have been found. I have the first 2 conditions down and they are working fine but I am struggling with getting the page to display the error for no entries found. views.py def search(request): value = request.GET.get('q','') if(util.get_entry(value) is not None): return HttpResponseRedirect(reverse("entry", kwargs={'entry': value })) else: subStringEntries = [] for entry in util.list_entries(): if value.upper() in entry.upper(): subStringEntries.append(entry) return render(request, "encyclopedia/search.html", { "entries": subStringEntries, "search": True, "value": value }) search.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} {% if search %} <h1>Searching for "{{ value }}"</h1> <h2>Did you mean...</h2> <ul> {% for entry in entries %} <li><a href="{% … -
Django - How to get multiple model data with single POST request?
I have 2 such models. I need to POST the data of 2 models in single POST API Call. Is it possible using viewsets ? class Customer(models.Model): id = models.AutoField(primary=True) customer_name = models.CharField(max_length=255) customer_number = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CustomerReferences(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) reference_name = models.CharField(max_length=255) reference_address = models.CharField(max_length=255) reference_number = models.IntegerField() -
Django Integrity Error NOT NULL constraint failed
I have searched this error over and over now and can't find a response that relates to my issue. I have a modal in my home page which I would like to allow users to update their posts from. I am using an inclusion tag and fbv for this. Here is my view: def update_view(request): profile = Profile.objects.get(user=request.user) if 'submit_u_form' in request.POST: u_form = PostUpdateForm(request.POST) if u_form.is_valid(): instance = u_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() return redirect('posts:index') And here is my custom tag: @register.inclusion_tag('posts/update.html') def update_tag(): u_form = PostUpdateForm() return {'u_form': u_form} Forms.py is here: class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = ['content', 'image', 'category',] Urls.py: urlpatterns = [ path('update/', update_view, name='update'), ] My modal in index.html includes this form: <form action="{% url 'posts:update' %}" method="post" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} <input type="hidden" name="post_id" value={{ post.id }}> {% update_tag %} </div> <div class="modal-footer"> <button type="submit" value="submit" name="submit_u_form">Update Post</button> </div> </form> And update html simply contains {{ u_form }} My form shows up in the modal how I would like it to however upon submit I receive this error: NOT NULL constraint failed: posts_post.author_id Please can someone explain to me why this is happening and how … -
Updating models with unique fields in Django Rest Framework
I get a "value already exists" error when I try to update the existing record. example: I have 10 Companies in a database. Now I want to edit the 4th record. Am looking to update the company "short_name" and leaving the "full_name" unchanged. When I hit submit, an error message is displayed in postman for full_name field "Already Exist" How can I avoid this? Model.py class CompanyProfile(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='ID',) short_name = models.CharField(max_length=30, null=True, blank=True,) full_name = models.CharField(max_length=255, unique = True,) def __str__(self): return str(self.full_name) Serializers.py class RegisterationCompanySerializer(serializers.ModelSerializer): short_name = serializers.CharField( max_length=30, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Short Name already exists or already in use")], ) full_name = serializers.CharField( max_length=255, validators=[UniqueValidator(queryset=CompanyProfile.objects.all(), message="Full Name already exists or already in use")], ) class Meta: model = CompanyProfile fields = '__all__' extra_kwargs = { 'short_name': {'required': True}, 'full_name': {'required': True}, } views.py class MainCompanyProfileView(viewsets.ModelViewSet): queryset = CompanyProfile.objects.all() serializer_class = RegisterationCompanySerializer permission_classes = (permissions.AllowAny,) def update(self, request, pk=id ,*args, **kwargs): partial = kwargs.pop('partial', False) instance = get_object_or_404(CompanyProfile, id = pk) serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) return super().update(request, *args, **kwargs) urls.py router = DefaultRouter() router.register('', MainCompanyProfileView) urlpatterns = [ path('v1/', include(router.urls)), ] Stacktrace Note: There are a lot of fields in each company have … -
VSCode Formatter causing error on my django project
Currently i am working on my django project with VSCode, and in my .html files i select the Django-Html as my language mode. And i have multiple blocks {%__%} in my html files. for example: {% block navbar %} {% endblock navbar %} {% block footer %} {% endblock footer %} enter image description here The problem is when i save the file, VSCode will auto format my html and move my _%} to next line which will make the endblock cannot recognize it properly after saving: {% block navbar %} {% endblock navbar %} {% block footer %} {% endblock footer %} enter image description here So is there anyone who has experienced this and knows how to fix it? -
How does the view in the app get the parameters in the urls.py under the project?
My directory structure(omit other unnecessary files): root urls.py app urls.py views.py root/urls.py: urlpatterns = [ path('<slug:_key>', include('app.urls')) ] app/urls.py: urlpatterns = [ path('', views.my_view, name="my_view"), ] app/views.py def my_view(request, key): res = my_func(key) return HttpResponse(res) Then my_view cannot get the parameter key -
I Can't able to Upload multiple Images using Django Forms, I tried to upload multiple images using Filepond in Django
I tried to upload Multiple images using Filepond, and it is working from frontend but not from the backend. And also not getting data from backend to edit the form. A form showing Blank only. I added my code below as models.py, forms.py, views.py, and HTML code also. I tried a lot of ways to upload multiple images but every time got errors only. Please, help me to resolve it ASAP. Thanks, in advance :). models.py class UserDetail(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) image = models.ImageField(null=True) firm_name = models.CharField(max_length=75, null=True) slug = models.SlugField(max_length=75, null=True, blank=True) person_name = models.CharField(max_length=40, null=True) designation = models.CharField(max_length=20, null=True) def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(slug_generator, sender=UserDetail) class UploadImages(models.Model): userdetail = models.ForeignKey(UserDetail, default=None, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True) def __str__(self): return self.userdetail.firm_name class Meta: verbose_name_plural = "Upload Extra Images" forms.py from django import forms from customer.models import UserDetail from django.contrib.auth.forms import UserChangeForm class EditForm(UserChangeForm): person_name = forms.CharField(label='Full Name') image = forms.ImageField(label='Logo Image') def __init__(self, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'input' class Meta: model = UserDetail fields = ('image', 'firm_name', 'person_name', 'designation') admin.py class UploadImagesAdmin(admin.StackedInline): model=UploadImages @admin.register(UserCardDetail) class UserCardDetailAdmin(admin.ModelAdmin): inlines = [UploadImagesAdmin] class Meta: model = … -
How can I move my media files stored in local machine to S3?
I have a Django application running on EC2. Currently, all my media files are stored in the instance. All the documents I uploaded to the models are in the instance too. Now I want to add S3 as my default storage. What I am worried about is that, how am I gonna move my current media files and to the S3 after the integration. I appreciate the help. I am thinking of running a python script one time. But I am looking for any builtin solution or maybe just looking for opinions. Thanks! -
Print Syntax error when testing out django script
When running this from django.urls import path from . import views from . import util encyclopedia_list = util.list_entries() urlpatterns = [ path("", views.index, name="index") ] for encyclopedia in encyclopedia_list: urlpatterns.append(path(f"{encyclopedia}", views.encyclopedia, name='encyclopedia_page') print(urlpatterns) script in a django app in order to test if the urlpatterns list is being updated acordingly I get a syntax error with the print function on the last line, any idea on what could be happening? -
How to store objects of custom class as session variables in django?
In my case i wants to store object of my USER class to be stored as session variable To be more precise my class contains several methods for USER structure of my USER class class USER: def __init__(self , phone_number_of_user = None , user_name = None): self.phone_number = phone_number_of_user self.user_name = user_name def login(self): login_code_will_be_here def get_user_name(self): return self.user_name def set_data_of_user_in_firebase(self , data = None): code to set data of user will be here firstly i create a USER object user = USER(phone_number = 9******** , user_name = John) But when i tries to store my objects in session of django like this request.session['user'] = user django shows me following error Object of type USER is not JSON serializable -
Django server not running? [closed]
I'm trying to run an existing Django server, but when I try to run it, CMD doesn't output anything? The server has already been created by someone else and I've already installed Python, Pip and Django. Screenshot -
objects.filter to get if string is contained in one or other field
I'm trying to filter my clients with a query. The user can look for the cif code and the client name writing in the same field so I can't know if he's looking for one thing or another. I'm trying to figure it out how to filter in both fields without excluding the other. I'll try give an example: I have this on my client table: [ { "company_name":"Best Bar EUW", "cif":"ABCD1234" }, { "company_name":"Word Bar EEUU", "cif":"POIU4321" }, { "company_name":"Not a bad bar", "cif":"MNVB1321" } ] Now I want to look for the "EE" string: the result that I want is the second object but the string "EE" is not included in the "cif" so it won't give me the result I want because it is included in one field but not in the other. This is my Client model: class Client(LogsMixin, models.Model): """Model definition for Client.""" company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField('consumptions.Platform', verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) What can I do with this? Thanks in advance !