Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3 Form Data not posting to DB and I would like it to, what am I missing?
This in in the early stages of testing and my expectation is that I should have enough here to write to the DB and I see no signed of a failure anywhere aside from the empty table after several POST attempts. #WEB FORM <form action="/" method="POST" id="ticketsubmitform"> {% csrf_token %} <div class="form-control" {% if form.date_submitted.errors %}errors{% endif %}> {{ form.date_submitted.label_tag }} {{ form.date_submitted }} {{ form.date_submitted.errors }} </div> <div class="form-control" {% if form.contact_name.errors %}errors{% endif %}> {{ form.contact_name.label_tag }} {{ form.contact_name }} {{ form.contact_name.errors }} </div> <div style="padding-bottom: 12pt"> <button type="submit"> >>> Submit Ticket >>> </button> </div> </form> #views.py def ticketing_app(request): if request.method == 'POST': form = TicketForm(request.POST) if form.is_valid(): ticket = Ticket( date_submitted=form.cleaned_data['date_submitted'], contact_name=form.cleaned_data['contact_name'], ) ticket.save() else: form = TicketForm() return render(request,'authentication/ticketing-app.html',{ "form": form }) #forms.py class TicketForm(forms.Form): date_submitted = forms.DateField(label="Date Submitted:", required=True, error_messages={ "required": "Date must not be empty." }) contact_name = forms.CharField(label="Contact Name:", max_length=45, required=True, error_messages={ "required": "Contact Name must not be empty.", "max_length": "Please enter a shorter name." }) #models.py class Ticket(models.Model): #---Base Meta----------------------------------------- date_submitted = models.DateField(max_length=15) contact_name = models.CharField(max_length=45) No errors on post - [29/Sep/2021 21:18:55] "POST / HTTP/1.1" 200 I do not see anything missing that would prevent a DB write -
django coverage not covering the urls despite writing specific tests for the urls
in my app named backoffice_engine, my urls.py file is as follows from django.urls import path, include from . import views urlpatterns = [ path('test/', views.test, name='test'), path('', views.dashboard, name='dashboard'), path('dashboard/', views.dashboard, name='dashboard'), path('add_new_client/', views.add_new_client, name='add_new_client'), path('edit_client/<int:client_id>', views.edit_client, name='edit_client'), .....some more paths.... ] my test_urls.py file for this urls.py file is as follows from django.test import SimpleTestCase from django.urls import reverse, resolve from backoffice_engine.views import * class TestBackofficeEngineUrls(SimpleTestCase): def test_test_url(self): url = reverse('test') self.assertEquals(resolve(url).func, test) def test_blank_url_uses_dashboard_function(self): url = reverse('dashboard') self.assertEquals(resolve(url).func, dashboard) def test_add_new_client(self): url = reverse('add_new_client') self.assertEquals(resolve(url).func, add_new_client) def test_client_detail(self): url = reverse('client_detail', args=['1']) self.assertEquals(resolve(url).func, client_detail) my understanding is runnning coverage on this file should result in coverage report showing that the following urls have been covered by unit tests. however coverage report for backoffice_engine.urls.py is zero missing by default. the report only is checking only the first 3 lines of the urls.py file -
how to take multiple images from webcam and save into database javascript - django
i'm trying to use modelformset_factory with capturing image from webcam , in order to take several images and save into database ? i'm only able to take one image , is there any way to achieve that please ? or how to use dynamic number of canvas ? class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) def __str__(self): return str(self.booking.id) forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] UploadDocumentFormSet = modelformset_factory(Document,form=UploadDocumentsForm,extra=1,can_delete=True) views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return redirect(reverse_lazy("booking:add_booking",kwargs={"room_no":obj.room_no.room_no})) else: messages.error(request,_('take a picture or choose an image')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) **NOTE ** my javascript solution doesnt work with formset const player = document.getElementById('player'); const docs = document.getElementById('document') const captureButton = document.getElementById('capture'); const constraints = { video: true, }; captureButton.addEventListener('click', (e) => { const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); context.drawImage(player, 0, 0, canvas.width, canvas.height); const imgFormat = canvas.toDataURL(); docs.value = imgFormat e.preventDefault(); }); navigator.mediaDevices.getUserMedia(constraints) .then((stream) => { player.srcObject = stream; }); $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none … -
Django custom user 'Account' object has no attribute 'has_module_perms'
I create a custom user model to login via email, but i got some issue when im tried to login on admin channel from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManajer(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email = self.normalize_email(email), username = username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name, last_name, username, email, password): user = self.create_user( email = self.normalize_email(email), password= password, username = username, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self.db) return user I'm able to create a superuser. However, when I try to login with email. I got this Error Exception Type: AttributeError Exception Value: 'Account' object has no attribute 'has_module_perms' Exception Location: ....\env\lib\site-packages\django\utils\functional.py, line 241, in inner Can someone fix that ? -
Django join between 3 tables
Hi i dont know really how i can perfom a join between this 3 tables. class Table1(models.Model): '''Productos a ser utilizados''' name = models.CharField() class Table2(models.Model): '''Productos a ser utilizados''' table1 = models.ForeignKey(Table1, related_name='TableTwo', on_delete=models.CASCADE, null=True, blank=True) class Table3(models.Model): '''Productos a ser utilizados''' codigo = models.IntegerField() table1 = models.ForeignKey(Table1, related_name='TableThree', on_delete=models.CASCADE, null=True, blank=True) im really confused about subquerys and join on django i dont know how i can do this. -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I am trying docker-compose an app with django and postgres using docker-compose but I get an error with the "NAME" Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'POSTGRES_NAME': 'postgres', 'POSTGRES_USER': 'postgres', 'POSTGRES_PASSWORD': env('POSTGRES_PASSWORD'), 'POSTGRES_HOST': 'localhost', 'POSTGRES_PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_NAME: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=sec DATABASE_URL=postgres://postgres:pass@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=pass POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Where does this "NAME" come from? Thanks for your help -
Django, Postgres and Docker compose: django.db.utils.OperationalError: could not connect to server: Connection refused
Here is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': env('POSTGRES_PASSWORD'), 'HOST': 'localhost', 'PORT': '5432', } } Here is my docker-compose version: "3.8" services: web: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db environment: DATABASE_URL: postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_NAME env_file: - .env db: image: postgres container_name: pgdb ports: - "5432" env_file: - .env environment: POSTGRES_USER: $POSTGRES_USER POSTGRES_PASSWORD: $POSTGRES_PASSWORD POSTGRES_DB: $POSTGRES_NAME Here is my .env DEBUG=on SECRET_KEY=thekey DATABASE_URL=postgres://postgres:thepassword@localhost:5432/postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=thepassword POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_NAME=postgres Inside my postgres database it says 2021-09-29 20:29:02.375 UTC [1] LOG: starting PostgreSQL 13.4 (Debian 13.4-1.pgdg110+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2021-09-29 20:29:02.375 UTC [1] LOG: listening on IPv6 address "::", port 5432 2021-09-29 20:29:02.379 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2021-09-29 20:29:02.384 UTC [26] LOG: database system was shut down at 2021-09-29 20:29:00 UTC 2021-09-29 20:29:02.390 UTC [1] LOG: database system is ready to accept connections PostgreSQL Database directory appears to contain a database; Skipping initialization I am not able to connect the django app with the postgres, can someone please help? I have started … -
Django - PermissionRequiredMixin - Return a 'permission_denied_message' in current View, instead of a 403 Page?
Django version 3.0.5 I want to use the PermissionRequiredMixin in my View to display a banner message the same way I would with the SuccessMessageMixin. For example, if a user attempts to delete an object and they do not have permissions, the permission_denied_message would essentially be treated as an error message an displayed in the current view as a banner message. Is that even possible? the code that I currently have does not work - it always redirects to the 403 page. see below: class DocDeleteView(PermissionRequiredMixin, SuccessMessageMixin, DeleteView): model = SlateDoc success_url = reverse_lazy('slatedoc-list') success_message = "SlateDoc was deleted!" permission_required = ('slatedoc.delete_slatedoc') raise_exception = True permission_denied_message = "Permission Denied" def delete(self, request, *args, **kwargs): if self.has_permission() is False: messages.error(self.request, self.permission_denied_message) else: self.object = self.get_object() self.object.soft_delete() messages.success(self.request, self.success_message) return HttpResponseRedirect(self.get_success_url()) -
django register_simple_tag send two parameter and how can ı use this in if condition?
In my project I want user make just one comment to Doctor profile.So ı choosed to use register_simple_tag and find if user made comment before bu if condition doesn't work.Can anyone know which part is wrong or has the another better way to solve this issue? commentExist.py register=template.Library() @register.simple_tag def isCommentExist(request,doctor): commmentExist=CommentModel.objects.filter(parent=None,is_published=True,doctor=doctor,comment_user=request.user).count() if commmentExist: return True else : return False profile.html {% if request.user.is_authenticated %} {% load commentExist %} {% isCommentExist request doctor as existComment %} {% endif %} {% if existComment %} # make some operation {% else %} # make some operation {% endif %} -
'AnonymousUser' object has no attribute '_meta' | Django
Errors occurs while authenticating user, CODE settings.py AUTH_USER_MODEL = 'Authentication.User' AUTHENTICATION_BACKENDS = ( ('django.contrib.auth.backends.ModelBackend'), ('Authentication.auth.CustomAuthEmailBackend.EmailAuthBackend'), ) Custom Backend from django.contrib.auth.models import User from django.contrib.auth.backends import BaseBackend class EmailAuthBackend(BaseBackend): def Authenticate(self, request, email, password): try: user = User.objects.get(email=email) success = user.check_password(password) if success: return user except User.DoesNotExist: pass return None def get_user(self, uid): try: return User.objects.get(pk=uid) except: return None views.py user_id = 1 password = ******* user = User.objects.get(pk=user_id) user.unique_username = unique_username userid = int(user_id) user.custom_user_id = createUserUnqiueId(userid) user.is_active = True useremail = user.email user.save() user = auth.authenticate(request, email=useremail, password=password, backend='Authentication.auth.CustomAuthEmailBackend.EmailAuthBackends') auth.login(request, user, backend='Authentication.auth.CustomAuthEmailBackend.EmailAuthBackend') return redirect('index') CODE EXPLANATION Working with email login by overriding username login. Then in authentication I have coded a custom for authentication but sometimes it works fine and default gives error and sometimes custom authentication back-end displays error and default authentication back-end works fine. Why? Also, if an authentication back-end is working fine on localhost, it displays errors after uploading on C panel. ERROR AttributeError at /auth/activate/Mjc/atr5z0-1d1d9f0050ff97fec5e766fd2418b520/s%2523f%253FO%253E%2560!c%257CK-0B92 'AnonymousUser' object has no attribute '_meta' Request Method: POST Request URL: http://app.barter.monster/auth/activate/Mjc/atr5z0-1d1d9f0050ff97fec5e766fd2418b520/s%252523f%25253FO%25253E%252560!c%25257CK-0B92 Django Version: 3.2.7 Exception Type: AttributeError Exception Value: 'AnonymousUser' object has no attribute '_meta' Exception Location: /home4/barter/virtualenv/Barter/3.8/lib/python3.8/site-packages/django/utils/functional.py, line 247, in inner Python Executable: /home4/barter/virtualenv/Barter/3.8/bin/python3.8 Python Version: 3.8.6 Python … -
redirect doesn't convert special characters correctly on redirect in django
I have a page in my django app that requires authentication. If the user hits mydomian/my_page the view will evaluate if the request is authenticated. If authenticated the request will get routed to the right html page (my_page.html). If the request is unauthenticated the request will be routed to the login page with a redirect: class MyView(View): def get(self, request): user = request.user context = { 'username': user.username } if user.is_authenticated and user.is_staff: return render(request, 'path/to/my_page.html', context) logout(request) return redirect('/admin/login?next=/my_page') This worked pretty well, when an unauthenticated user hit mydomain/my_page it will get routed to mydomain/admin/login/?next=/my_page and once authenticated it will get routed to mydomain/my_page with will serve path/to/my_page.html. Now I updated to the latest django version and the rerouting changed: When an unauthenticated request hits my page it gets rerouted to this url mydomain/admin/login/?next=/admin/login%3Fnext%3D/my_path. Once the login happens on that page, the page gets rerouted to mydomain/admin instead of mydomain/my_page. Then when I call mydomain/my_page it gets routed to the right page (since the request is authenticated). I tried replacing the redirect with return HttpResponseRedirect((('/admin/login?next=/my_page').encode('utf-8'))) but didn't work. I also couldn't find anything in the django docs on if and how the changed the redirect method. Any ideas? -
how to iterate multiple lists in django template
I'm trying to iterate a zip list to templates.So basically I have three lists of zip list I want to iterate it to template with this format(example picture). that's why I used three for loop in here all data are dynamic like (content,cards,posts).I think i may be some error with for loop on templates. If you need more info I can give you.And also if you have another better way than this please let me know. So here is my zip list zipped_lists = zip(card_postings, arrays, post_content) And also this is template {% for card,posts,contents in zipped_lists %} <div class="card"> <div class="card-body"> <h4 class="text-center">{{ card }}</h4> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for post in posts %} <div class="col"> <div class="card"> <div class="card-header text-center text-primary"> <h5>{{ post }}</h5> </div> <ul class="list-group list-group-flush"> <li class="list-group-item border-0"> {% for subj in contents %} <i>{{subj}} <br> </i> {% endfor %} </li> </ul> </div> </div> {% endfor %} </div> </div> </div> {% endfor %} </div> -
Django upload and read vcard object - loosing my mind
I am trying to let users of my Django app upload vcards through a form, parse those vcards on the fly and then serve some of the content back to the front-end without storing the vcards on server. I have successfully found a way to read and extract content from vcards that are stored on my machine using the vobject library and a few lines of code like the one below with open(vcard_path) as source_file: for vcard in vobject.readComponents(source_file): full_name = vcard.contents['fn'] .... However, I am failing to replicate this approach when accessing a vcard file that has been uploaded through a django form. I have this form <form action="{% url "action:upload_vcard" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="vcard" id="vcard_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> and this is the view def upload_vcard(request): data = {} if "GET" == request.method: return render(request, "action/upload_test.html", data) # if not GET, then proceed file = request.FILES["vcard"] with open(file) as source_file: for vcard in vobject.readComponents(source_file): full_name = vcard.contents['fn'] return HttpResponseRedirect(reverse("action:upload_vcard")) In this case … -
NoReverseMatch Django Project
I want to create the products through the customer's profile, so that the customer's name is attached to the form when creating the product that is related to it. But i cant find the error, please help me urls.py urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name="products"), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>', views.createOrder, name='create_order'), path('update_order/<str:pk>', views.updateOrder, name='update_order'), path('delete_order/<str:pk>', views.deleteOrder, name='delete_order'), path('create_customer/', views.createCustomer, name='create_customer'), ] views.py Here I focus on the "create Order" function passing the customer's primary key and using "initial" to append the customer's name to the form def home(request): orders_value = Order.objects.all() customer_value = Customer.objects.all() total_orders_value = orders_value.count() total_customers_value = customer_value.count() pending_value = orders_value.filter(status='Pending').count() delivered_value = orders_value.filter(status='Delivered').count() context = {'orders_key': orders_value, 'customer_key': customer_value, 'total_orders_key':total_orders_value, 'pending_key': pending_value, 'delivered_key': delivered_value} return render (request, 'accounts/dashboard.html', context) def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form_value = OrderForm(initial={'customer':customer}) if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): order = Order.objects.get(id=pk) form_value = OrderForm(instance=order) if request.method == … -
How to repair flex in one part of page?
I created website, with this template. But somehow I get not to work flex on this part where is copyright. I'm working in django and even if I copy same code, this part is not working. Any idea how to solve this? <!-- Fotter Bottom Area --> <div class="footer-bottom-area"> <div class="container h-100"> <div class="row h-100"> <div class="col-12 h-100"> <div class="footer-bottom-content h-100 justify-content-between d-flex align-items-center"> <div class="copyright-text d-flex"> <p>Copyright &copy;<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made with <i class="fa fa-heart-o" aria-hidden="true"></i> by <a href="https://colorlib.com" target="_blank">Colorlib</a></p> </div> </div> </div> </div> </div> </div> -
Is there a way I can download the headers only as a file in Django ImportExportModelAdmin
Is there a way to just download a file that contains only the field titles? For example, the download template button will download a file that has all the necessary fields as shown in the help text. The downloaded file would look like this: Any help is appreciated. -
Download mp3 files in client system from api using django framework
I have built a website where I need to let users download mp3 files by calling API. But, the files are downloading in the server, not in the client system. def download(url: str, dest_folder: str): if not os.path.exists(dest_folder): # create folder if it does not exist os.makedirs(dest_folder) filename = "1.mp3" file_path = os.path.join(dest_folder, filename) r = requests.get(url, stream=True) if r.ok: print("saving to", os.path.abspath(file_path)) with open(file_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024 * 8): if chunk: f.write(chunk) f.flush() os.fsync(f.fileno()) download(i="API URL mylink", dest_folder="C:/Users/"+username+"/Desktop/call_logs") Please help me how to change this code in such a way that the file has to download into the client system! -
docker-compose and django secret key
I have build my postgres and django appplication using the following version: "3.8" services: django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - db db: image: postgres container_name: pgdb environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres When I check the docker-desktop, I got 2 docker containers, "django" and "pgdb". When I check the django, it says django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Originally, on my windows 10 machine, I saved the secret key in the windows variable. What is the way to build the docker-compose so it has the secret get? SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') -
Django Postgres not adding / dropping constraints not working for partitions
I am creating a unique together constraint on set of four columns. I am seeing after creating those constrains, the table is still accepting the duplicates. Later I found that the partitions of that table also needs the constraints to be applied. Before doing that, I deleted all duplicate records. Now when I tried the same again, it is not working. Only the root table is getting the unique constraints and not the partitions. I am trying all these through Django migrations. If I run the SQL query to alter table directly in postgres on individual partitions, in that case it is working. Please advise what I am missing here. -
Modifying foreign key queryset in Django create CBV
I have 2 groups of 5 employees. In each group, one of the employees is that group's supervisor. In the create view, once the supervisor field is populated, I would like the employee foreign key field to show only those employees belonging to that supervisor. It would be nice to have the appropriate employees displayed based on the user (supervisor) without the supervisor field having to be populated first. I have tried model forms to try to appropriately modify the employee foreign key field query set, obviously to no avail. Please help! The code is as follows: class Instruction(models.Model): supervisor = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="supervisorinstructions" ) employee = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="employeeinstructions" ) instruction = models.CharField(max_length=300) def __str__(self): return f"{self.instruction}" def get_absolute_url(self): return reverse("myapp:instructiondetail", kwargs={"pk": self.pk}) class InstructionCreate(CreateView): model = models.Instruction fields = [ "supervisor", "employee", "instruction", ] template_name = "myapp/instruction_create_form.html" -
How can I copy a FieldFile to a different model?
I have referenced this SO.. Django - how to create a file and save it to a model's FileField? But I can't quite make out what I'm supposed to do. I am trying to populate a model with initial data and I am getting a FIELDFILE...I strip all of the other attributes and I am just getting the FIELDFILE name. I am trying to save it to a model using inlineformsets...but it won't save. I tried to override my SAVE method in my form...as shown below just as an experiment... def save(self, update_author, *args, commit=True, **kwargs): f = open('/path/to/file') self.attachments.save(book, File(f)) But it does nothing. Thanks in advance for any pointers. -
Django Fetching Submit Orders
I am dealing with Django this project where I need to create an ordering system, where there would be possible to create an order as a company (so there would be billing information of the company) and based on how many employees the company would select to take part in the course, they would fill up forms about the employees. So f.e. i need to fetch the data like this - One order: Company Ltd. (information about the company) - Will Smith (information about the employee) Company Ltd. (information about the company) - Jennifer Proudence (information about the employee) Company Ltd. (information about the company) - Stein Code (information about the employee) Company Ltd. (information about the company) - Michael Louve (information about the employee) and also: Company Ltd. (information about the company) - Will Smith (information about the employee), Jennifer Proudence (information about the employee), Stein Code (information about the employee), Michael Louve (information about the employee) -
Django and Tensorflow serving in Docker Compose
I can successfully run my django using the following # pull the official base image FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN apt-get update RUN apt-get install ffmpeg libsm6 libxext6 -y RUN pip install --upgrade pip COPY requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY .. /usr/src/app EXPOSE 8000 WORKDIR /usr/src/app/flyingChicken CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] And I can successfully the TensorFlow serving using docker run -p 8501:8501 --name tfserving_classifier --mount type=bind,source=algorithms\SSIM\,target=/models/flyingChicken-e MODEL_NAME=flyingChicken-t tensorflow/serving I would like to deploy both remotely on an Azure server. How can I trigger the tensorflow serving docker from the django docker? -
Django local memory cache is re-fetching each time
I am using Django's local memory cache in development and I can't get it to work. I have set the following in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' } } I see the views are being called everytime a page is loaded. I only have one Django server process running in dev -
Django test fails with "No User matches the given query."
I wrote Django app and now I'm trying to cover it with automated tests. For testing get_queryset function within my ListView I created a test user and his post, but my test fails with "No User matches the given query". When I execute py manage.py runserver everything is fine, no exceptions are raised and the page's displayed properly. I'm new to Django testing so I absolutely have no idea what's going on. Could you help me please? This is my view from view.py class UserPostListView(ListView): """Displaying a page with a certain user's posts""" model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): """Dynamic filtering to get posts by a chosen user""" queryset = super().get_queryset() user = get_object_or_404(User, username=self.kwargs.get('username')) return queryset.filter(author=user).order_by('-date_posted') Test for that view: class TestUserPostListView(TestCase): """Test UserPostListView""" def setUp(self): """Creating a test user and his post to see if the certain user's page with posts is displayed properly""" self.factory = RequestFactory() self.user = User.objects.create_user( username='test_user', email='testuser@example.com', password='fhhewo87539275' ) self.post = Post.objects.create( title='test_post', content='blabla', author=self.user ) def test_get_queryset(self): """Testing get_queryset function""" url = reverse('user-posts', kwargs={'username': self.user.username}) request = self.factory.get(url) view = UserPostListView() view.setup(request) queryset = view.get_queryset() self.assertIn(self.post, queryset) Traceback: Traceback (most recent call last): File …