Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a value to a Bootstrap modal in Django
I'm trying to implement a feature where I get to change a product by passing its id to a modal and change it there, then reflect the changes in the same page, where the user can click on the product name, a modal page appears with the product name and a list of products, then he can change the product from the list of products, click save changes, the modal page closes, and the product is now updated. The problem is that I was facing difficulty in passing the product id to the modal div that exist in the same template, but couldn't figure it out, then I saw Martín De la Fuente's approach and tried it, but it didn't work with me as well. It shows me this error message: django.urls.exceptions.NoReverseMatch: Reverse for 'products_modal' not found. 'products_modal' is not a valid view function or pattern name. My code is as the following: In product template: Sending product id to the product_modal template: <td> <a href="#" class="open-modal" data-url="{% url 'products_modal' product.id %}"><span>{{product.name}}</span></a> </td> Creating an empty div to insert the product_modal in it: <div id="product-modal-div"></div> Javascript part: <script> var productModalDiv=$("#product-modal-div") $(".open-modal").on("click",function(){ $.ajax({ url:$(this).attr("data-url"), success:function(data){ productModalDiv.html(data); $("#ProductModal").modal(); } }) }) </script> … -
Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<category>[^/]+)\\Z']
Based on an answer to my previous question here This is my html code: <a href="{% url 'Tools' %}"><p>Tools</p></a> When I used category like this def home( request,category) in my views, I got a positional argument error so I used this : def home( request,**kwargs ): p=product.objects.filter(category__name= category) return render(request,'home.html',{'p':p}) This is URLs: urlpatterns = [ path('',views.home), path('home/<str:category>', views.home,name='Tools'), ] But after going to this URL http://127.0.0.1:8000/home/Tools I got this error : NoReverseMatch at /home/Tools Reverse for 'Tools' with no arguments not found. 1 pattern(s) tried: ['home/(?P<category>[^/]+)\\Z'] Why do I get this error? Or how can I solve this error home() missing 1 required positional argument: 'category' if I want to use this : def home( request,category)? -
How to send attribute through argument in function
What i want to do: I have a model: class Example(models.Model) exmpl1=models.TextField(blank=True,null=True) anotherexmpl=models.TextField(blank=True,null=True) I want to create a function to change a row and save it, using row name in argument Like: def example(row,id): item=Example.objects.get(id=id) item.row="Example" item.save() example(exmpl1,1) example(anotherexmpl,1) example(anotherexmpl,1) How can i do this? -
how to can we search JSON data from the Django admin?
how to can we search and filter JSON data from the Django admin and how can we pass the JSON key in search list in the admin.py file during model registration?? -
How to get and update complete querySet in django model
please I am having issues with my code. Model class: class Skill(models.Model): class Meta: verbose_name = ".4 skill" class SkillCategory: categories = (("frontend", "frontend"), (" backend", "backend") title = models.CharField(max_length=255) category = models.CharField(choices=SkillCategory.categories, max_length=255) Views.py: def edit_skill(request): get_data = Skill.objects.get(pk=1) In my case from the code snippet in views.py am supposed to get a <QuerySet [<Skill: HTML>, ...]> everything works fine. My problem came in when I needed to update a particular data in my Skill model using primay key(pk), in this manner: get_update_data = Skill.objects.get(pk=1) for skill in get_update_data: skill.title = " ReactJs" skill.category = "frontend" if skill.save(): return JsonResponse({"data": 200}) return JsonResponse({"data": 500}) Problem: From the above, I incurred a Python bug stating: get_update_data is not iterable. After deploying other debugging method I discovered that in my QuerySet I got a returned data of Skill with only title, and which in my update I needed to update title and category. Please I am confused at this point on the approach to take in fixing the bug and I will appreciate an helping hand at this point. Thank you for your anticipating assistance. -
django SQL Error (1054, "Unknown column 'utility_voter.Id' in 'field list'")
Following are models In Model.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class election_type(models.Model): Id = models.AutoField(primary_key=True) type_of_election=models.CharField(max_length=200) class party(models.Model): Id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) symbol = models.ImageField(upload_to='images') class constituency(models.Model): Id = models.AutoField(primary_key=True) name=models.CharField(max_length=200) State=models.CharField(max_length=200) total_voters=models.IntegerField() class constituency_type(models.Model): Id = models.AutoField(primary_key=True) election_type_id=models.ForeignKey("election_type",on_delete=models.DO_NOTHING) constituency_id=models.ForeignKey("constituency",on_delete=models.DO_NOTHING) class booth_manager(models.Model): Id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.EmailField(max_length=50,unique=True) phone_no = PhoneNumberField(max_length=13,unique=True) aadhaar_no = models.CharField(unique=True,max_length=50) constituency_id = models.ForeignKey("constituency",on_delete=models.DO_NOTHING) USERNAME_FIELD = 'email' Reqired_FIELDS = ['name','phone_no','aadhaar_no','constituency_id'] class voter(models.Model): voter_id = models.IntegerField(unique=True) Id = models.AutoField(primary_key=True,unique=True) aadhaar_no = models.CharField(unique=True,max_length=50) name = models.CharField(max_length=100) age = models.IntegerField() address = models.TextField(max_length=200) email = models.EmailField(max_length=50, blank=True) phone_no = PhoneNumberField(max_length=13,unique=True) Reqired_FIELDS = ['name','phone_no','aadhaar_no','constituency_id'] class voter_constituency(models.Model): Id = models.AutoField(primary_key=True) voter_id=models.ForeignKey("voter",on_delete=models.DO_NOTHING) loksabha_id=models.IntegerField() vidhansabha_id=models.IntegerField() class candidate(models.Model): Id = models.AutoField(primary_key=True) name=models.CharField(max_length=200) phone_no=models.IntegerField() email= models.EmailField(max_length=200) aadhaar_no=models.CharField(unique=True,max_length=50) class candidate_party(models.Model): Id = models.AutoField(primary_key=True) candidate_id=models.ForeignKey("candidate",on_delete=models.DO_NOTHING) party_id=models.ForeignKey("party",on_delete=models.DO_NOTHING) class candidate_constituency(models.Model): Id = models.AutoField(primary_key=True) candidate_id=models.ForeignKey("candidate",on_delete=models.DO_NOTHING) constituency_id=models.ForeignKey("constituency",on_delete=models.DO_NOTHING) election_type_id=models.ForeignKey("election_type",on_delete=models.DO_NOTHING) class votes(models.Model): Id = models.AutoField(primary_key=True) candidate_id=models.ForeignKey("candidate",on_delete=models.DO_NOTHING) total_votes=models.IntegerField() class voter_vote_status(models.Model): Id = models.AutoField(primary_key=True) voter_id=models.ForeignKey("voter",on_delete=models.DO_NOTHING) casted_vote=models.BooleanField(null=False) Want to get details from voter model I'm getting this sql error when trying to get data in my view function. Someone Please Help resolving this error is it caused to some fault in declaration of models or is there something else? … -
Cleaned data from formset
How do I access form claned_data in frame sets in forms.py? I want for example get amount value that user entered and calculate -
How to query through a Django model and get access to another Django model without a ManyToMany relationship?
I have a model called WatchList with an object called listing which corresponds to the Listings Model through a Foreign Key. I want to be able to query through the WatchList Model to get all the listings on a user's particular watchlist and display all the objects of all the listings on a webpage. I do not want to do this using a ManyToMany Field because I just got a different part of my web application that deals with the WatchList Model to work. Is there any other way to do this? views.py def watchlist(request): watchlists = WatchList.objects.filter(user=request.user) for listing in watchlists.listing: listings_needed = watchlists.listing() watchlist_listing = watchlists.get(listing) listings = Listings.objects.all().filter(watchlist_listing) return render(request, "auctions/watchlist.html",{ "listings": listings }) models.py class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE, default="") class WatchList(models.Model): listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") This error is also occurring with the current code: arg, value = filter_expr TypeError: cannot unpack non-iterable function object This … -
AWS Boto3 Compatibility Issue, How can I install an older version of Boto3?
I'm trying to deploy my Django project to AWS Elastic Beanstalk. The tutorial I am following is suggesting I use Boto3 to link up my S3 Database. The problem is when I am installing Boto3 i am getting this message in red. awsebcli 3.20.3 requires botocore<1.24.0,>1.23.41, but you have botocore 1.27.7 which is incompatible. So I'm trying to install the older version of Botocore, 1.24.0 or 1.23.41, but after looking at PyPi I can't seem to find it since it just says use pip3 install boto3. Any suggestions? -
How to resolve "NoReverseMatch" Error in Django?
So I'm trying to create a table of hosts, and as one of the fields of that table include a clickable link to an update page. Which will pass the host_id to the update page. I was hoping someone could tell me what I'm doing wrong with regards to passing the correct parameter to upate/<host_id>. As I'm not quite sure as to how to fix the issue and make it so I can direct people via a clickable button in the table rendered to the appropriate update page. When I attempt to render the page with that added in I'm getting the following error: NoReverseMatch at /website/home/ Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>'] Request Method: GET Request URL: http://127.0.0.1:8000/website/home/ Django Version: 4.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'update' with arguments '(1,)' not found. 1 pattern(s) tried: ['website/update/<host_id>'] It is also spiecificlly pointing to the following line of code as the issue: <td><a href="{% url 'update' beacon.host_id %}"</a>Issue Command</td> This line is found in the following HTML segment. Relevant HTML Section {% for beacon in hosts %} <tr> <td>{{ beacon.host_id }}</td> <td>{{ beacon.hostname }}</td> <td>{{ beacon.internalIp }}</td> <td>{{ beacon.externalIp }}</td> <td>{{ beacon.current_user }}</td> … -
Unable to save webp file to model field
I'm not sure if this is entirely django related, but if someone could help me, that would be so much appreciated! I'm having trouble generating a webp file from the following code from io import BytesIO from PIL import Image import requests I've got the following model class UserImage(models.Model): user_provided_image = VersatileImageField(upload_to=folder10, null=True, blank=True) nextgen_image = models.FileField(upload_to=folder10,null=True, blank=True) #for WebP images I'm creating a webp file. This code works, but it saved it to the file to the root directory of my project and I'm not sure how to save it to the FileField (i.e. nextgen_image ) on my model def create_webp_image(sender, instance, *args, **kwargs): image_url = instance.image.thumbnail['1920x1080'].url try: response = requests.get(image_url, stream=True) path = image_url except: #local env path = "http://localhost:8000" + image_url response = requests.get(path, stream=True) img = Image.open(BytesIO(response.content)) #build file path position = path.rfind("/") + 1 newpath = path[0:position] #build file name image_name = path[position:] name_of_file = image_name.split('.')[0] + ".webp" #this creates the webp file img.save(name_of_file,"webp") #save image to model #instance.nextgen_image = ? post_save.connect(create_webp_image, sender=UserImage) Thanks! -
"Tainted canvases may not be exported" even after allowing all URLs with Django CORS Headers module
Using Django, I'm attempting to pull a texture from textures.minecraft.net, crop, zoom, and display a section of said texture. CORS of course has a problem with this. In response to this, I've installed the pip module "django-cors-headers" and set up my settings according to the instructions here. Here's what my settings.py looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # here it is 'users.apps.UsersConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # here it is 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True # Yes, it's unsafe. I just want a working prototype for now CORS_ALLOW_CREDENTIALS = True I have a JS that attempts to create a new image with the source of the above texture. Here's the JS snippet: let skin = "http://textures.minecraft.net/texture/74d1e08b0bb7e9f590af27758125bbed1778ac6cef729aedfcb9613e9911ae75"; let testImg = new Image(); testImg.height = 64; testImg.width = 64; testImg.setAttribute('crossorigin', 'anonymous'); testImg.src = skin; This script is loaded in VIA django like so: <!-- Load the JS script into the base html on this page --> {% block bodyscripts %} <script src="{% static 'js/test.js' %}" defer></script> {% endblock bodyscripts %} My Pipfile contains: django-cors-headers = "*" Yet I still receive the error "Access to image at 'http://textures.minecraft.net/texture/74d1e08b0bb7e9f590af27758125bbed1778ac6cef729aedfcb9613e9911ae75' from origin … -
Django: save multiple images on upload
I want to save multiple versions of a picture and based my solution on this thread: Django / PIL - save thumbnail version right when image is uploaded The model Class overrides the save() function, which calls the make_thumbnail() function, to scale the image. The issue is, that this code, does not save the uploaded file, but it takes the default image. Where is the issue? models.py pic_formats = [(640, 480), (1280, 960), (1920, 1440) ] def path_and_rename(path, sufix=None): def wrapper(instance, filename): file_extension = filename.split('.')[-1] # get filename if instance.pk: filename = f'{instance.pk}_{sufix}.{file_extension}' else: # set filename as random string filename = f'{uuid4().hex}.{file_extension}' # return the whole path to the file return os.path.join(path, f'user_{str(instance.pk)}', filename) return wrapper class UserProfile(models.Model): email = models.OneToOneField(User, on_delete=models.CASCADE) # Profile Pictures profile_pic_orig = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='orig'), default='img/profile_picture/default.jpg', verbose_name=_('profile picture')) profile_pic_640 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='640'), default='img/profile_picture/default_640.jpg', verbose_name=_('profile picture 640px'), null=True) profile_pic_1280 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='1280'), default='img/profile_picture/default_1280.jpg', verbose_name=_('profile picture 1280px'), null=True) profile_pic_1920 = models.ImageField(upload_to=path_and_rename(path='img/profile_picture/', sufix='1920'), default='img/profile_picture/default_1920.jpg', verbose_name=_('profile picture 1920px'), null=True) def make_thumbnail(self, formats: list): from PIL import Image from io import BytesIO from django.core.files.base import ContentFile from django.core.files.uploadedfile import SimpleUploadedFile import copy image = Image.open(BytesIO(self.profile_pic_orig.read())) thumb_name, thumb_extension = os.path.splitext(self.profile_pic_orig.name) thumb_extension = thumb_extension.lower() if thumb_extension in ['.jpg', '.jpeg']: FTYPE = 'JPEG' … -
django-autocomplete-light generic foreign key invalid view function
I am trying to use django autocomplete light to set up Autocompletion for GenericForeignKey However I am getting this error when I try to view the form: I have a simple a setup. My best guess is that because the urls are in an app's urls.py (and not in the project's urls.py), it's looking for them at root, instead of in the app? But I'm not sure how to get DAL to look for these views in the app, if that's even the problem. models.py class Prereq(IsAPrereqMixin, models.Model): name = models.CharField(max_length=256, null=True, blank=True) prereq_content_type = models.ForeignKey(ContentType, related_name='prereq_item', verbose_name="Type of Prerequisite", on_delete=models.CASCADE) prereq_object_id = models.PositiveIntegerField(verbose_name="Prerequisite") prereq_object = GenericForeignKey("prereq_content_type", "prereq_object_id") # lots more fields ignored for now forms.py from dal import autocomplete from prerequisites.models import Prereq class PrereqForm(autocomplete.FutureModelForm): prereq_object = autocomplete.Select2GenericForeignKeyModelField( model_choice=[(Prereq, "Prereq"), ] ) class Meta: model = Prereq fields = ['name'] urls.py from django.urls import path from prerequisites import views from prerequisites.forms import PrereqForm app_name = 'prerequisites' urlpatterns = [ path('edit/<int:pk>/', views.PrereqUpdateView.as_view(), name='prereq_edit'), ] # https://django-autocomplete-light.readthedocs.io/en/master/gfk.html#register-the-view-for-the-form urlpatterns.extend(PrereqForm.as_urls()) -
Django ModelForm submit button not working
I am trying to make a Django ModelForm that retrieves data from my database using the GET method. When I click the submit button nothing happens. What am I doing wrong? HTML doc <form role="form" action="" method="GET" id="form-map" class="form-map form-search"> <h2>Search Properties</h2> {% csrf_token %} {{ form.as_p }} <input type="submit" action= "" class="btn btn-default" value="Submit"> <input type="reset" class="btn btn-default" value="Reset"> </form><!-- /#form-map --> forms.py from django import forms from .models import StLouisCitySale208 from django.forms import ModelForm, ModelMultipleChoiceField class StLouisCitySale208Form(ModelForm): required_css_class = 'form-group' landuse = forms.ModelMultipleChoiceField(label='Land use', widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('landuse', flat=True).distinct()) neighborho =forms.ModelMultipleChoiceField(label='Neighborhood',widget=forms.SelectMultiple, queryset=StLouisCitySale208.objects.values_list('neighborho', flat=True).distinct()) policedist = forms.ModelMultipleChoiceField(label='Police district',widget=forms.SelectMultiple,queryset=StLouisCitySale208.objects.values_list('policedist', flat=True).distinct()) class Meta: model = StLouisCitySale208 fields = ['landuse', 'neighborho', 'policedist', 'precinct20','vacantland', 'ward20', 'zip', 'zoning','asmtimprov', 'asmtland', 'asmttotal', 'frontage', 'landarea','numbldgs', 'numunits'] -
Converting to WebP - 'VersatileImageFieldFile' object has no attribute 'mode'
I've got the following model class UserImage(models.Model): user_provided_image = VersatileImageField(upload_to=folder10, null=True, blank=True) nextgen_image = models.FileField(upload_to=folder10,null=True, blank=True) #for WebP images I'm attempting to save the user uploaded image to WebP. def create_webp_image(sender, instance, *args, **kwargs): image = instance.user_provided_image.thumbnail['1920x1080'].url #Create webp image webp.save_image(image, 'image.webp', quality=80) #save image to model instance.nextgen_image = webp post_save.connect(create_webp_image, sender=UserImage) I'm getting the following error: 'str' object has no attribute 'mode' The traceback indicates that it fails on the 3rd line of this block from the webp codebase: @staticmethod def from_pil(img): if img.mode == 'P': if 'transparency' in img.info: img = img.convert('RGBA') else: img = img.convert('RGB') return WebPPicture.from_numpy(np.asarray(img), pilmode=img.mode) Thanks! -
Django + PostgreSQL best way to improve performance of slow summary aggregation?
Context I have a Django REST API using PostgreSQL database with millions of Items. These Items are processed by several systems and the processing details are sent back and stored a Records table. The simplified models are: class Item(models.Model): details = models.JSONField() class Record(models.Model): items = models.ManyToManyField(Item) created = models.DateTimeField(auto_created=True) system = models.CharField(max_length=100) status = models.CharField(max_length=100) details = models.JSONField() Goal I would like to do arbitrary filters on the Items's table and get a summary of various systems. This summary obtains the latest status for each selected Item for each system, and displays a count of each status. For example if I filter for 1055 items an example return is: { System_1: [running: 5, completed: 1000, error: 50], System_2: [halted: 55, completed: 1000], System_3: [submitted: 1055] } I currently have this working doing queries like below, which returns the count of processing statuses for System_1 and repeat for the other systems and package into a JSON return. Item.objects.filter(....).annotate( system_1_status=Subquery( Record.objects.filter( system='System_1', items__id=OuterRef('pk') ).order_by('-created').values('status')[:1] ) ).values('system_1_status').annotate(count=Count('system_1_status')) We have millions of Items and Records and this works reasonably well if we select less than a thousand Items. Above this it takes minutes. Trying to do it for hundreds of thousands of items … -
Is the UML/Design Pattern for my portfolio correct or how could it be improved (should?)?
First of all, I'm trying to create my web portfolio with Django and React to start as a Full Stack developer. I thought it would be a good idea to show already on my portfolio some of the things I can do (my portfolio would be ALREADY a fullstack project). So this is what I want to do: A web portfolio that is managed by me, with kind of a blog/comment functionality. I can add a project whenever I have sth new to display Those projects can be reviewd by users (who may or may not register to my site) Those projects can be liked only by registered users (I figured that might be simpler) Reviews can be answered by anyone It doesn't need to be complicated, so if you think that might work, just say so BUT, if you notice ANY problem I might run into with this design, please let me know. I don't know much about UML, but I noticed it makes your life so much simpler to actually create the backend once you designed your tables. The Tables shown on the graphic below will be represented by the Models on Django. This is the UML that … -
Django: how to set ForeignKey related_name in Abstract Model class?
I want to create on Abstract Model class for future inheriting like this: class AbstractModel(models.Model): created_at = models.DateTimeField( auto_now_add=True, blank=True, null=True, ) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='XXX_created_by', blank=True, null=True, ) class Meta: abstract = True Field 'created_at' is working fine, but how to generate related_name in 'created_by' for my child classes to prevent clashing? -
Testing Django project with pytest
All local tests passed successfully with pytest in my virtual environment. However, when I setted up a workflow (pipeline) in github actions, all tests fails. Could you please help me ? Here is my pipeline: name: Django CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.8, 3.9] steps: # Checkout the Github repo - uses: actions/checkout@v3 # Install Python - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} # Install project dependencies - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt # Move into the django project folder (Sigma) and run pytest - name: Run Tests with pytest working-directory: . run: | pip install pytest pytest -v -
Django Object Detection Webcam Video feed, TypeError: fromarray() missing 1 required positional argument: 'obj'
I have been asking questions on StackOverflow but have not been getting any positive responses. Got banned multiple times from posting further questions. Please provide help this time. I want to perform custom object detection using custom trained YOLOv5 model on a real-time video feed taken from the webcam. I am using Django for this purpose (later on I will connect this with React.js frontend). I have been successful with accessing the webcam feed using Django but when I try to run my custom yolov5 model on the video feed. I am getting this error and there is no video showing up in index.html. [12/Jun/2022 02:43:03] "GET / HTTP/1.1" 200 329 Traceback (most recent call last): File "c:\users\mh_s1\appdata\local\programs\python\python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "c:\users\mh_s1\appdata\local\programs\python\python37\lib\wsgiref\handlers.py", line 183, in finish_response for data in self.result: File "D:\University\FYP\FYP-CovidDefence\stream\webcam\views.py", line 42, in stream data=im.fromarray() TypeError: fromarray() missing 1 required positional argument: 'obj' Here is my views.py file code: from django.http import StreamingHttpResponse import cv2 from PIL import Image as im import yolov5 from yolov5.utils.general import (check_img_size, non_max_suppression, scale_coords, check_imshow, xyxy2xywh, increment_path) from yolov5.utils.torch_utils import select_device, time_sync from yolov5.utils.plots import Annotator, colors import io import torch # Create your views here. def index(request): return render(request,'index.html') … -
AttributeError: module 'django.db.models' has no attribute 'ManyToMany'
I am trying to make one of my model objects a ManyToMany Field, so I can access the objects through both models. I am receiving the following error. listing = models.ManyToMany(Listings, blank=True, related_name="listing") AttributeError: module 'django.db.models' has no attribute 'ManyToMany' models.py class WatchList(models.Model): listing = models.ManyToMany(Listings, blank=True, related_name="listing") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") -
The change in the django view is not reflected to the page until restarting uwsgi
I installed Django + Uwsgi + Nginx. Project is running. But when i change something in the view, the change is not reflected to page until i restart uwsgi. Should i restart uwsgi everytime i make a change in the view? But when i add time to view to show in the page. The displayed time is changing everytime i refresh the page. My view is : from django.shortcuts import render from django.http import HttpResponse # added from django.utils import timezone def home(request): return HttpResponse('This is the home page. 101' + str(timezone.now())) My urls.py : from django.contrib import admin from django.urls import path from godentiapp import views # added urlpatterns = [ path('', views.home, name='home'), # added path('admin/', admin.site.urls), ] -
django.core.exceptions.ImproperlyConfigured each time running pytest
Whenever I open my django project and try to test it I get django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Or it can be other explanation with the same Error (not always with INSTALLED_APPS...). I can fix it with command: export DJANGO_SETTINGS_MODULE=<project_name>.settings But I would have to do it every time I open the project. Is there a way for this to be fixed once and forever? -
Django IntegrityError; NOT NULL constraint failed when trying to post on django blog web app
I am trying to upload text to my blog web app but I keep getting an intergity error saying 'NOT NULL constraint failed'. Can anyone help me resolve this issue? My models.py file looks like this: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class File(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=True) date_uploaded = models.DateTimeField(default=timezone.now) uploader = models.ForeignKey(User, on_delete=models.CASCADE) id = models.BigAutoField(primary_key=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('file-detail', kwargs={'pk': self.pk}) auto_now_add=True