Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am creating a django app that will provide people to post the zip files on the app and others can download that zip file
The app is like home page has images and if you click on the image , image details open up and i want to place the zip file in the details for others to download it. How to do that? -
Django ListView is missing a QuerySet - Error Message - 2 Models In 1 View
I'm trying to view data from 2 models in a single list view. I'm getting the below error message and I can't seem to figure out why. I have included the browser error, views.py, urls.py and html page. Any assistance would be appreciated and as a side note I'm new to programming, Python and Django. Error: ImproperlyConfigured at /scripts/patientsdetails/ PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset(). Request Method: GET Request URL: http://127.0.0.1:8000/scripts/patientsdetails/ Django Version: 3.2.2 Exception Type: ImproperlyConfigured Exception Value: PatientListView is missing a QuerySet. Define PatientListView.model, PatientListView.queryset, or override PatientListView.get_queryset(). urls.py from django.urls import path from .views import ( ScriptListView, ScriptUpdateView, ScriptDetailView, ScriptDeleteView, ScriptCreateView, PatientListView, PatientUpdateView, PatientDetailView, PatientDeleteView, PatientCreateView, ) urlpatterns = [ path('patientsdetails/', PatientListView.as_view(), name='patient_list'), ] views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput from django.contrib.auth import get_user_model from django.shortcuts import render from scripts.models import Patient, Script from .models import Script, Patient class PatientListView(LoginRequiredMixin, ListView): template_name = 'patient_summary.html' def get_context_data(self, **kwargs): context = super(PatientListView, self).get_context_data(**kwargs).filter(author=self.request.user) context['patient'] = Patient.objects.filter(author=self.request.user) context['script'] = Script.objects.filter(author=self.request.user) return context html {% for patient in object_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ patient.patient_name … -
ValueError Cannot assign "<QuerySet [<Product:name>]
I am a student learning Django. I want to implement so that I receive the product code in the order(join model) DB when ordering a product, but it is difficult because I keep getting an error like the title. I think I will die because it hasn't been solved for too long. When I use product.object.all(), all the query sets are loaded, and even when I use a filter, an error occurs. How can I solve this problem? It would be such an honor if you could reply. models.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.join_code) class Meta: ordering = ['join_code'] My guess is that there is something wrong with this part.(join/views.py) I think something went wrong in the process of … -
How to create multiple instance of same the same model but different user
I had a blog post with comments, and I want people to be able to edit their comment at the same page with modal or whatever. I have tried using the FooForm(instance=model) , but it only allows a model with one user in it -
Django: no such table: users_profile - Cannot apply migrations
Django noob here. Whenever I extend the base User Model, and try to access or edit the new fields, I receive the following error [... table not found]. 1 Im not sure why this is happening as I have ran makemigrations and migrate multiple times. For reference here are my migrations 2 Also here is my models.py for further reference 3 I believe some issue is occurring with the command line [python3 manage.py migrate], as makemigrations indicates that changes have occurred, yet migrate constantly states no changes detected. Also worth noting that this issue occurs when attempting to change the profile table in the admin site Please let me know if you need to know anything else. Thanks for any help :) site wont let me directly upload photos so have used the links instead. -
when I tried to execute pip install pillow in django 2.2..its showing following error>Can anyone review this error
Running setup.py install for pillow ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sushant\pycharmprojects\inventorymanagement\venv\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\U sers\Sushant\AppData\Local\Temp\pip-install-fneb7b0f\pillow_c936c1eaa32247fa836a1ef8974590fc\setup.py'"'"'; file='"'"'C:\Users\Sushant\AppData\Local\T emp\pip-install-fneb7b0f\pillow_c936c1eaa32247fa836a1ef8974590fc\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) el se io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec '"'"'))' install --record 'C:\Users\Sushant\AppData\Local\Temp\pip-record-lwn4j6lp\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\sushant\pycharmprojects\inventorymanagement\venv\include\site\python3.10\pillow' cwd: C:\Users\Sushant\AppData\Local\Temp\pip-install-fneb7b0f\pillow_c936c1eaa32247fa836a1ef8974590fc Complete output (178 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\PIL copying src\PIL\BdfFontFile.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ContainerIO.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ExifTags.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\features.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\FitsStubImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\FontFile.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GdImageFile.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GifImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GimpGradientFile.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\Image.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ImageChops.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ImageCms.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ImageColor.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ImageDraw.py -> build\lib.win-amd64-3.10\PIL copying src\PIL\ImageDraw2.py -> build\lib.win-amd64-3.10\PIL copying … -
Problem of Q() for and two condition in Django models
Suppose that I have these models: class X(models.Model): interface = models.OneToOneField('Interface', related_name='x') class Y(models.Model): interface = models.OneToOneField('Interface', related_name='y') class Interface(models.Model): CHOICE = ( (0, 'this is x'), (1, 'this is y'), ) owner_type = models.IntegerField(choices=CHOICE,) Now, I want to get count Interface Objects that dosen't have x relation and y relation. I used these two way: z = Interface.objects.filter(x__isnull=True).filter(y__isnull=True).count() # Get correct number of objects x = Interface.objects.filter(Q(x__isnull=True)and Q(y__isnull=True)).count() # Get wrong number of objects The z return correct result but x return wrong number. Why this happend? -
Radio Button is not selected with GET Request Django FormModel
Radio button Django is getting rendered in the form but the problem is when I try to get the selected Radio Button. It isn't selecting as per the value in the database. It just shows to select from the Radio Button I am able to POST but not GET. Model.py class myModel(models.Model): STATUS_CHOICES = [(1, 'Ok'), (2, 'Not Ok')] left_leg = models.BooleanField(choices=STATUS_CHOICES, default=1, null=True) forms.py class myModelForm(forms.ModelForm): model = myModel fields = ('left_leg') widgets = {'left_leg': forms.RadioSelect} views.py def myview(request, pk): aa = myModel.objects.get(pk=pk) if request.method == 'POST': form = myModelForm(request.POST, instance=aa) if form.is_valid(): form.save() return redirect("/") else: context = {'form': form} return render(request, "aa.html", context) aa.html <div class="col-lg-2"> <div class="form-group"> {{ form.left_leg.errors }} {% for choice in form.left_leg%} {{ choice }} {% endfor %} </div> </div> url.py path('path/update/<int:pk>/', myView, name='xx'), Please help -
I am Unable to extend the User model in Django
Here I have changed the model and view name but I am unable to extend my user model why it gives the error like Registration() got an unexpected keyword argument 'myuser' please try to solve this error. And this problem arises many time please give me the solution. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Registration(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.fname class Candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return "{} -- {}".format(self.full_name,self.position) views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname reg = Registration(dob=dob,myuser=myuser) reg.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") error: … -
Some sent datas are not written, while some of them are written Django & Postman
Hello guys I am trying to authenticate in API written in Django Rest Framework with React.js, but before React I am testing my API with Postman, however, while trying to sign up, I am facing a problem. I am giving all required fields but it is not writing to db, when I look at Django Admin, These fields are still empty, while others are filled with the data I have given first_name second_name dob (date of birth) longitude lattitude interests Here is my models.py file in users app from django.db import models from django.contrib.auth.models import AbstractUser from courses.models import Field class CustomUser(AbstractUser): username = models.CharField(max_length=32 , verbose_name="Login", unique=True, ) first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False) second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False) # & dob = date of birth dob = models.DateField(auto_now_add=False, verbose_name="Yoshingiz", blank=False, null=True) gender_choices = [("e", "Erkak"), ("a", "Ayol")] gender = models.CharField(choices=gender_choices, verbose_name="Jinsingiz", default="e", max_length=1) interests = models.ManyToManyField(Field, verbose_name="Qiziqishlaringiz") longitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (uzunlik)", null=True, blank=True) latitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (kenglik)", null=True, blank=True) Here is my forms.py file in users app from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = … -
django orm inner join group by data
class Dishes(models.Model): """ 菜品""" cuisine_list = ((0, '川菜'), (1, '粤菜'), (2, '徽菜'), (3, '湘菜')) name = models.CharField('菜名', max_length=100) material = models.TextField('材料') cuisine = models.IntegerField('菜系', choices=cuisine_list) price = models.IntegerField('价格') def __str__(self): return self.name how to select : Information about the most expensive dish in each cuisine, including dish names and ingredients Dishes.objects.values('cuisine').annotate(max_price=Max("price")) In this way, we can only find the information with the highest price in each cuisine, excluding the names and ingredients of the dishes. It would be fine if we could query for cuisine and max_price from inner join, but what should we write in ORM? -
After clicking to like button redirecting to top of the page?
I am doing like and dislike the article. Like and dislike is working perfectly but the only problem is when I click I stay on the same page but I redirected to the top of the page. All I want to stay not only the page but also the same position my every article have images so to read the entire article we have to scroll down and the like button is the end of the article. Here are some details. post_detail page(like button) <form action="{% url 'like_post' single_post.category.slug single_post.slug %}" method="POST"> {% csrf_token %} <button type="submit" name="like_btn" value={{single_post.id}} class="ui red button like_btn" > <i class="heart icon"></i> Like ({{single_post.total_likes}}) </button> </form> urls.py path('<slug:category_slug>/<slug:post_slug>', views.post_detail , name="post_detail"), path('like/<slug:category_slug>/<slug:post_slug>', views.like_post, name="like_post") post model class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField(max_length=100) image = models.ImageField(upload_to = 'photos/post_image/%Y/%m/%d/', default="../static/images/pp2.jpg") category = models.ForeignKey(Category, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='post_likes') description = FroalaField() views = models.IntegerField(default=0) comments = GenericRelation(Comment) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super(Post, self).save(*args, **kwargs) def total_likes(self): return self.likes.count() def get_url(self): return reverse("post_detail", args=[self.category.slug, self.slug]) def __str__(self): return self.title views.py def like_post(request,category_slug, post_slug): post = get_object_or_404(Post, id=request.POST.get('like_btn')) liked = False if post.likes.filter(id … -
why Image is not loading in django template?
I uploaded a picture in the Django database but when I try to show this picture in Django templates, it's not showing anything but showing the image title. Here is my index.html {% for value in data %} <div class="product-box"> <div class="img-wrapper"> <div class="front"> <a href="product-page(no-sidebar).html"><img src="{{ value.product_img.url }}" class="img-fluid blur-up lazyload bg-img" alt=""></a> </div> <div class="back"> <a href="product-page(no-sidebar).html"><img src="{{ value.product_img.url }}" class="img-fluid blur-up lazyload bg-img" alt=""></a> </div> <div class="cart-info cart-wrap"> <button data-bs-toggle="modal" data-bs-target="#addtocart" title="Add to cart"><i class="ti-shopping-cart"></i></button> <a href="javascript:void(0)" title="Add to Wishlist"><i class="ti-heart" aria-hidden="true"></i></a> <a href="#" data-bs-toggle="modal" data-bs-target="#quick-view" title="Quick View"><i class="ti-search" aria-hidden="true"></i></a> <a href="compare.html" title="Compare"><i class="ti-reload" aria-hidden="true"></i></a> </div> </div> <div class="product-detail"> <div class="rating"><i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i></div> <a href="product-page(no-sidebar).html"> <h6>{{ value.product_title }}</h6> </a> <h4>{{ value.price }}</h4> <ul class="color-variant"> <li class="bg-light0"></li> <li class="bg-light1"></li> <li class="bg-light2"></li> </ul> </div> </div> {% endfor %} Here is my views.py def home(request): context={ 'data': Products.objects.all() } return render(request, 'auctionApp/index.html',context) -
Server Error (500) On Password Request when deployed Django Project at Heroku
I have deployed my Django Project on Heroku https://billpayy.herokuapp.com/. When I try to reset the password, it gives an Error 500 page. The Password Reset functionality works fine locally but gives this error when deployed. Also, couldn't decode much from the Error Logs: 2021-05-30T12:08:10.012088+00:00 heroku[router]: at=info method=POST path="/account/password_reset/" host=billpayy.herokuapp.com requ est_id=90b04f79-c813-4efa-8d2a-aa922d0bcae9 fwd="27.4.64.168" dyno=web.1 connect=4ms service=765ms status=500 bytes=403 protocol=http 2021-05-30T12:08:10.012273+00:00 app[web.1]: 10.30.51.66 - - [30/May/2021:12:08:10 +0000] "POST /account/password_reset/ HTTP/1.1" 50 0 145 "http://billpayy.herokuapp.com/account/password_reset/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, l ike Gecko) Chrome/91.0.4472.77 Safari/537.36" settings.py """ Django settings for billing_site project. Generated by 'django-admin startproject' using Django 3.2. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os import django_heroku from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['billpayy.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'billingapp.apps.BillingappConfig', 'users.apps.UsersConfig', 'bootstrap4', 'crispy_forms', 'bootstrap_datepicker_plus', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
How to use .filter correctly in Django and code seems not to be executed
I'm trying to map positions from one table to another table, but at the moment i am really confused about using .filter. I have a Worker class like this, class Worker(models.Model): """Model representing a worker.""" personal_id = models.IntegerField(primary_key=True, help_text='Unique ID for a worker in the whole company') position = models.ForeignKey(Position, on_delete=models.SET_NULL, null=True) Machine_of_Worker = models.ManyToManyField('Machine', blank=True, related_name = 'workers') """ insert filtering method here """ class Meta: ordering = ['personal_id'] def __str__(self): """String for representing the Model object.""" return f'{self.last_name}, {self.first_name}' def get_absolute_url(self): """Returns the url to access a detail record for this book.""" return reverse('worker-detail', args=[str(self.personal_id)]) a Machine class like this > class Machine(models.Model): > """Model representing a Machine.""" > machine_id = models.IntegerField(primary_key=True, help_text="enter machine number as unique id here") > Worker_On_Machine = models.ManyToManyField(Worker, blank=True, related_name = 'machines') > position = models.ForeignKey(Position, on_delete=models.SET_NULL, blank=True, null=True) and a position class according to this. class Position(models.Model): """ Model representation of the positions and ground states """ square_id = models.IntegerField(primary_key=True, help_text='Unique ID for a position square in x/y coordinate in the whole company') x_pos = models.IntegerField(default = 0, help_text="enter x coordinate here") y_pos = models.IntegerField(default = 0, help_text="enter y coordinate here") My WorkerAdmin looks like this class WorkerAdmin(admin.ModelAdmin): readonly_fields = ['worker_on_machine'] list_display … -
how to run many task parallel in celery?
I have code like this : def calculator(number): ( I/O bound operation .get data from API and insert to Redis ) def starter(): for i in range(100): calculator(i) this code takes 250 seconds to finish. I rewrite code with celery ,like this : @shared_task def calculator(number): ( I/O bound operation. get data from API and insert to Redis ) def starter(): for i in range(100): calculator.delay(i) and I start my celery worker with : celery -A my_app worker -l info -c 4 and it took me about 260 seconds and there isn't any difference in those both ways I take 250-260 seconds. I want to break 260 to 50 seconds to finish jobs. can anyone help me? -
How to 'convert' MP3 file to numpy array or list
I'm working on an audio-related project that connects with Django backend via rest api. Part of the front-end requires to display waveforms of associated mp3 files and for this, it in turn requires optimized data of each mp3 file in form of an array, which the front-end (javascript) then processes and converts to a waveform. I can pick the associated mp3 file from backend storage, the problem is converting it into an array which I can serve to the front-end api. I have tried several methods but none seem to be working. I tried this How to read a MP3 audio file into a numpy array / save a numpy array to MP3? which leaves my computer hanging until I forced it to restart by holding the power button down. I have a working ffmpeg and so, I have also tried this Trying to convert an mp3 file to a Numpy Array, and ffmpeg just hangs which continues to raise TypeError on np.fromstring(data[data.find("data")+4:], np.int16). I can't actually say what the problem is and I really hope someone can help. Thank you in advance! -
self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200
This is were the error comes from def test_single_status_retrieve(self): serializer_data = ProfileStatusSerializer(instance=self.status).data response = self.client.get(reverse("status-detail", kwargs={"pk": 1})) self.assertEqual(response.status_code, status.HTTP_200_OK) response_data = json.loads(response.content) self.assertEqual(serializer_data, response_data) It seems like the error is coming from somewhere else. This is what I got when I ran the test (ProjectName) bash-3.2$ python3 manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F......... ================================================================= FAIL: test_single_status_retrieve (profiles.tests.ProfileStatusViewSetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "path.../ProjectName/src/profiles/tests.py", line 101, in test_single_status_retrieve self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 10 tests in 1.362s FAILED (failures=1) Destroying test database for alias 'default'... -
How does Google Translate handle audio streaming for "Translate by Audio"
How to best way to stream microphone data from browser to server and are there any documentation about how does Google handle this topic? As an example in case: "Translate by Audio" in Google Translate. I use Django web framework in the backend, behind a Nginx reverse proxy and I would like to process microphone data coming from browser. Open for suggestions. Thx! -
Django - Use TextInput form to look up a ForeignKey
I'm currently trying to build an application in Django where users should be able to create new entries for a model. Said model contains a ForeignKey relation to a different model. However, the classic dropdown form field is not practical, because there could be hundreds of entries to choose from. Instead, I'd like to allow users to simply type in the name of the entry (all names are unique), which then gets transformed to the corresponding ID when pressing the Submit button. I feel like this should be pretty straightforward to do, but since I'm new to Django I'm having a hard time to figure out how to do it. Currently the problem is, that the form field is declared invalid, due to the ForeignKey not existing (since the user typed in the name and not the ID of the database entry). Code example: forms.py: class DogForm(ModelForm): class Meta: model = Dog fields = "__all__" widgets = {" shelter": widgets.TextInput(attrs={"id":" shelter", "placeholder":" Dog Shelter"}), "name": widgets.TextInput({"id":"name", "placeholder":"Name"}), def clean(self): shelter= self.data.get("shelter") self.cleaned_data["shelter"] = Shelter.objects.get(name=shelter) return self.cleaned_data views.py: class DogCreate(CreateView): model = Dog form_class = DogForm def form_valid(self, form): if form.is_valid(): instance = form.save(commit=False) instance.save() return super(DogCreate, self).form_valid(form) As you can … -
How to receive video in real-time for computation?
I want to create a Deep learning model which can detect objects in real time, I'll be creating an Android application which will send realtime video. The Backend which will be created in Django which will receive the video and forward it to the DL model to for further computation in real-time. After that the model will providee the results which needs to be sent back toh the Android application / client for displaying the results. How to receive the video in Backend in realtime so that the DL model can do the computation? -
Show pie chart based on status in Django template
Good Afternoon, I want to show a pie chart on my django project where the data feeding the chart will be the count of each individual status currently I have this in my views.py def pie_chart(request): labels = [] data = [] queryset = Task.objects.aggregate( ncompl = Count('pk', filter=Q(status='complete')), noverrun = Count('pk', filter=Q(status='overdue')), ninprog = Count('pk', filter=Q(status='in progress')), nnotstrtd = Count('pk', filter=Q(status='not started')) ) for task in queryset: labels.append(task.title) data.append(queryset) return render(request, 'pie_chart.html', { 'labels': labels, 'data': data, }) for my template.html I have <div class="map_section padding_infor_info"> <canvas id="pie_chart"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> var config = { type: 'pie', data: { datasets: [{ data: {{ data|safe }}, backgroundColor: [ '#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3' ], label: 'Population' }], labels: {{ labels|safe }} }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById('pie-chart').getContext('2d'); window.myPie = new Chart(ctx, config); }; </script> models.py class Task(models.Model): title = models.CharField(max_length=50) project = models.ForeignKey(Project, related_name="tasks", on_delete=models.CASCADE) priority = models.CharField(max_length=20, choices=priority) status = models.CharField(max_length=20, choices=status) assigned = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateField(default=date.today) end_date = models.DateField(default=date.today) def __str__(self): return '%s - %s' % (self.project.name, self.title) def get_absolute_url(self): return reverse('projects:task-details') i want to archive results as enter image description here -
Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2> ~
I don't want to fetch all the querysets and I would like to have their assigned values in those values Need to fix the problem? ValueError at /join/element_detail/ Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2>, <Designated: 3>, <Designated: 4>, <Designated: 5>, <Designated: 6>, <Designated: 7>, <Designated: 8>, <Designated: 9>]>": "Element.designated_code" must be a "Designated" instance. Request Method: POST Request URL: http://127.0.0.1:8000/join/element_detail/ Django Version: 3.1.5 Exception Type: ValueError Exception Value: Cannot assign "<QuerySet [<Designated: 1>, <Designated: 2>, <Designated: 3>, <Designated: 4>, <Designated: 5>, <Designated: 6>, <Designated: 7>, <Designated: 8>, <Designated: 9>]>": "Element.designated_code" must be a "Designated" instance. views.py from django.shortcuts import render # Create your views here. from zeronine.forms import ElementForm from zeronine.models import * def element_detail(request): designated_object = Designated.objects.all() element_object = Element.objects.all() value_object = Value.objects.all() if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] element.designated_code = designated_object element.save() return render(request, 'zeronine/list.html') else: form = ElementForm() return render(request, 'zeronine/detail.html', {'form': form, 'designated_object': designated_object, 'element_object': element_object, 'value_object': value_object}) -
Application Error in Heroku while deploying Django app, specifically, the log tail says = Build failed -- check your build output: *link*
This is my very first time deploying a Django app in heroku and I was following an article to git push and all the other tasks. The problem started when I started to push master. My app was not loading. So from heroku documentation I moved the push to main and deleted the master. And a new problem arose that is the application error, and asked to heroku log --tails. Later I found the Procfile didn't had the right app name. corrected that and restarted heroku. Still it shows application error with the line in red saying : Build failed -- check your build output: https://dashboard.heroku.com/apps/6609d304-92ca-454e-8659-561a8adbb11a/activity/builds/6c1dd096-0d90-49af-a5db-55eec4dff27b for the heroku logs --tail. terminal : heroku logs --tail (env) D:\DJPROJ\OFFSET_V1.1\v1>heroku logs --tail 2021-05-30T08:27:39.043493+00:00 app[api]: Initial release by user aera4242@gmail.com 2021-05-30T08:27:39.043493+00:00 app[api]: Release v1 created by user aera4242@gmail.com 2021-05-30T08:27:39.615588+00:00 app[api]: Enable Logplex by user aera4242@gmail.com 2021-05-30T08:27:39.615588+00:00 app[api]: Release v2 created by user aera4242@gmail.com 2021-05-30T08:33:03.000000+00:00 app[api]: Build started by user aera4242@gmail.com 2021-05-30T08:33:32.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/6609d304-92ca-454e-8659-561a8adbb11a/activity/builds/bb5f0314-a49e-4e29-b6a0-1ec421b92733 2021-05-30T08:47:08.146897+00:00 app[api]: Starting process with command `python manage.py migrate` by user aera4242@gmail.com 2021-05-30T08:47:08.852782+00:00 heroku[run.2613]: State changed from starting to up 2021-05-30T08:47:09.202077+00:00 heroku[run.2613]: Awaiting client 2021-05-30T08:47:09.491181+00:00 heroku[run.2613]: Starting process with command `python manage.py migrate` … -
Django Bootstrap column issue and help/explanation
Hey guys I need help with Django logic & bootstrap, as well as an explanation if possible. I am trying to achieve the attached file. I did it with plain html/bootstrap, but I am unable to do it in Django, so there is definitely some flow within my code. what I am trying to achive <div class="container-fluid"> <div class="row"> {% for post in object_list %} <div class="col-lg-3 col-sm-12"> {% if post.is_on_home_page post.is_side_story is True %} {% if post.home_or_category_image %} <div class="top-articles-images"><img class="img-fluid" src="{{ post.home_or_category_image.url }}"></div> {% endif %} <div class="cover-info"> <a class="top-articles-label" href="{% url 'categories' post.category.slug %}">{{ post.category }}</a> <h4> <a href="{% url 'article-detail' post.slug %}"> {{ post.title }}</a> </h4> <p> {{ post.snippet }} </p> <p> By: {{ post.author }} </p> {% endif %} </div> <div class="col-lg-6 col-sm-12"> {% if post.is_on_home_page and post.is_main_on_home_page is True %} {% if post.home_or_category_image %} <div class="top-articles-images"><img class="img-fluid" src="{{ post.home_or_category_image.url }}"></div> {% endif %} <div class="cover-info"> <a class="top-articles-label" href="{% url 'categories' post.category.slug %}"> {{ post.category }} </a> <h4> <a href="{% url 'article-detail' post.slug %}"> {{ post.title }}</a> </h4> <p> {{ post.snippet }} </p> <p> By: {{ post.author }} </p> {% endif %} </div> <div class="col-lg-3 col-sm-12"> {% if post.is_on_home_page and post.is_side_story is True %} {% …