Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run tests in Django app? Setting error
I try to write tests for my Django app but I'm getting an error and don't know how to fix it. Inside my sport_field_app folder I have files: conftest.py: import pytest from django.test import Client @pytest.fixture def client(): client = Client() return client tests.py: def test_list(client): response = client.get("sport-field-list/") assert response.status_code == 200 I've also added a file pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = test.settings After running pytest test.py I got a message: Traceback (most recent call last): File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/pytest_django/plugin.py", line 179, in _handle_import_error yield File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/pytest_django/plugin.py", line 351, in pytest_load_initial_conftests dj_settings.DATABASES File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'test.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/bin/pytest", line 8, in <module> sys.exit(console_main()) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main code = main() File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 145, in main config = _prepareconfig(args, plugins) File "/home/maryla/marylaGIS_github/sport_field_reservation_v2/venv/lib/python3.8/site-packages/_pytest/config/__init__.py", line 324, in _prepareconfig config = pluginmanager.hook.pytest_cmdline_parse( … -
Import "article.models" could not be resolved (from article.models import ArticlePost)
This is a python code from my classmate, but I found a warning Import "article.models" could not be resolved at line from article.models import ArticlePost How to solve this? I use django 4.0.4 and did not find anything like ArticlePost in django-documentation from django.db import models from django.contrib.auth.models import User from article.models import ArticlePost from ckeditor.fields import RichTextField from mptt.models import TreeForeignKey # comments class Comment(models.Model): article = models.ForeignKey(ArticlePost, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') body = RichTextField() parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) reply_to = models.ForeignKey( User, null=True, blank=True, on_delete=models.CASCADE, related_name='replyers' ) created = models.DateTimeField(auto_now_add=True) class MPTTMeta: order_insertion_by = ['created'] def __str__(self): return self.body[:20] -
Display Data in Django table where data has similarities betwen row and column
Currently i'm dealing with timetable project, have a list of schedule saved in database and i want to print them in a table where a schedule should be placed on a right place based on row(days) and columns (timeslots). i have tried to arrange schedule and it appear as follows: appearance of current tried schedule arrangement picture The view used is as follows def lecturerTimeTable(request): lecname=Lecturer.objects.get(user=request.user.id) context={ 'schedule': TeachingTimetable.objects.filter(lecturer=lecname).order_by('meet_time'),#get lecturer 'program': Program.objects.all(), 'days': MeetingTime.objects.all().values('day').distinct(), #day 'slots': MeetingTime.objects.all().values('time').distinct(),#timeslot 'url_name':'class',#for active link 'lecturer':lecname, 'StarterPage':'Class-Timetable'# for head } return render(request,'users/class_timetable.html',context) The template table is as follows <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th colspan="8"><center>{{lecturer}}</center</th> </tr> <tr> <th></th> {% for time in slots %} <th class="time">{{time.time}}</th>{% comment %} timeslot from 07:00-09:00 to 17:00-21:00 {% endcomment %} {% endfor %} </tr> </thead> <tbody> {% for day in days %} <tr> <th>{{day.day}} </th> {% for lesson in schedule %} {% if lesson.meet_day == day.day%} {% if lesson.meet_time == '13:00 - 15:00' %} <td>{{lesson.course}} <br> {{lesson.lecturer}}<br> {{lesson.venue}}<br> {{lesson.meet_day}} {{lesson.meet_time}}</td> {% comment %} {% endif %} {% endcomment %} {% endif %} {% endfor %} </tr> {% endfor %} So i appreciate i will get help soon! Thanks -
Django, generic view dynamic filtering
i'm starting out with Django and trying to render all Shows(screenings) that selected Movie had. Here's the code: url path('movie/<int:pk>/', MovieDetails.as_view(), name='movie'), Models class Movie(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=255, blank=True) def __str__(self): return f'{self.title}' class Show(models.Model): show_date = models.DateField() start_time = models.TimeField() movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, blank=True) def __str__(self): return f'{self.show_date}' View class MovieDetails(DetailView): model = Movie context_object_name = 'movie' def get_queryset(self): self.movie = get_object_or_404(Movie, id=self.kwargs['pk']) #find movie by id from url shows_played = Show.objects.filter(movie=self.movie) print(shows_played) #prints out some shows return shows_played def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shows_played'] = Show.objects.filter(movie=self.movie) return context The shows_played prints out some shows, so it seems like everything is fine but when the url: /movies/1 is called I get a 404, No show found matching the query rendered in browser and Not Found: /movie/1/ printed in console What am i doing wrong? Thank you -
nginx alias : where is the alias taking place (3 containers and a reverse proxy)
Im trying to get working a single page application with django/wagtail and react. But at the moment im serving django content via restframework and the request on media/ and djangostatic/ are not working. I have configured nginx to serve /media and /djangostatic to alias /app/media and /app/static but this is not working properly. Here is the nginx.conf file: server { listen 80; server_name localhost; location / { proxy_pass http://172.20.128.3:3000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 20M; } location /wagtail { proxy_pass http://172.20.128.2:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Script-Name /wagtail; client_max_body_size 20M; } location /djangostatic/ { alias /app/static/; } location /media/ { alias /app/media/; } } When a page in need of /djangostatic is querried, i get the error : 2022/06/12 08:30:10 [error] 22#22: *2 open() "/app/static/wagtailadmin/js/vendor/jquery.datetimepicker.js" failed (2: No such file or directory), client: 172.20.0.1, server: localhost, request: "GET /djangostatic/wagtailadmin/js/vendor/jquery.datetimepicker.js?v=021047c1 HTTP/1.1", host: "localhost", referrer: "http://localhost/wagtail/cms-admin/login/?next=/wagtail/cms-admin/" So the alias seems to work (it is replaced by /app/media) but it doesnt open the file. I have checked the backend server container and the file exists. So my question is simple : on which server does the alias takes effect? I have actually three … -
SMTP email error after Google's removal of less secure app access
Error: SMTPAuthenticationError at /accounts/signup/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials n1-20020a05620a294100b006a6b6638a59sm3664075qkp.53 - gsmtp') Before the update, the email sender works. Now after the update the email sender has a STMP authentication error. How can I fix this error? Code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'tonoabot.noreply@gmail.com' EMAIL_HOST_PASSWORD = os.environ['mailbotPass'] EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
local variable 'med' referenced before assignment - Django
I have 2 models 1) patientprofile and 2) medInfo. In the first model patientprofile, I am trying to get patients informations like (name and other personal information) and 2nd model I want to add patients Medical information data.. when I am trying check is there a existing medical information for the patient then show and update it. otherwise need to create and update it. in medinfo model using forignkey of patientprofile (id). Its working good in admin panel perfectly. but when I am trying to do it UI getting error. below is code:view.py @login_required def medinfoupdate(request, patid): # to get patient name and id in medinfo page accessing patientprofile data patprofileedit = patientprofile.objects.get(id=patid) try: med = medInfo.objects.get(pat_ID=patid) if request.method == 'GET': form = medInfo_form(instance=med) return render(request, 'pmp/medinfo.html', {'med': med, 'form':form, 'patprofileedit' : patprofileedit} ) except: if request.method == 'GET': return render(request, 'pmp/medinfo.html', {'patprofileedit' : patprofileedit} ) if request.method == 'POST': try: form = medInfo_form(request.POST, instance=med) form.save() return redirect(patientlist) except ValueError: return render(request, 'pmp/medinfo.html', {'form': form, 'error': 'Data entered is wrong!'}) below is error : UnboundLocalError at /medinfo/pat-11 local variable 'med' referenced before assignment Request Method: POST Request URL: http://localhost:8000/medinfo/pat-11 Django Version: 4.0.4 Exception Type: UnboundLocalError Exception Value: local variable 'med' … -
How can I simplify retrieval of corresponding foreign key objects
I use Django on the backend and React on the frontend. I have quotes that are related to a character by foreign key, for example: class Quotes(models.Model): quote = models.CharField(max_length=1000, unique=True, null=True, blank=False) quote_ja = models.CharField(max_length=1000, unique=True, null=True, blank=True) quote_by = models.ForeignKey(Characters, on_delete=models.SET_NULL, null=True, blank=True) quote_from = models.ForeignKey(Media, on_delete=models.SET_NULL, null=True, blank=True) date_added = models.DateField(auto_now=True) I have some models with multiple foreign keys, for example in the above, quote_by returns the keys to the corresponding characters. image of the foreign keys in api This is the Characters Model connected to quote_by: class Characters(models.Model): first_name = models.CharField(max_length=100, null=True, blank=False) last_name = models.CharField(max_length=100, null=True, blank=True) ja_name = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='characters/', null=True, blank=True) I would like to access the data from fields such as quote_by/quote_from with React. At the moment it seems overly complicated and I'm wondering if I should make a change to the backend. -
When I paginate my Django page my tables sizes and buttons positions are changing
In my Django site I want to show a table. Because of I can't show all table rows in one page I am using pagination. But every time I go to other page my tables size and buttons positions is changing. How can I fix their size and positions same on every page? This is the view I using: class TableView(ExportMixin, SingleTableView): model = MyModel table_class = MyTable template_name = 'table_list.html' context_object_name = 'table_list' paginate_by = 8 My html page: <div class="container"> <h1>Table</h1> <span class="current"> <h3>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</h3> </span> {% if page_obj.has_previous %} <a id="left-arrow" href="?page={{ page_obj.previous_page_number }}">PREVİOUS</a> {% else %} <div class="current"> <a id="left-arrow" href="#">PREVİOUS</a> </div> {% endif %} {% if page_obj.has_next %} <a id="right-arrow" href="?page={{ page_obj.next_page_number }}">NEXT</a> {% endif %} <table class="table" border=1 id="mytable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>School</th> <th>Email</th> <th>Note</th> </tr> </thead> <tbody> {% for customer in customers %} <tr> <td>{{table_list.name}}</td> <td>{{table_list.age}}</td> <td>{{table_list.school}}</td> <td>{{table_list.email}}</td> <td>{{table_list.note}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> -
Link to detailpage of object with todays date from navbar
In my application, I have objects that are connected to each day. The object's date must be unique. I want to include a link to the detailpage of the object of today from the navbar. However, I don't know how this should be implemented. Because essentially, I need to be able to get the pk of todays object from the navbar template. This is how I try to link to it right now in my navbar.html file: <a class="nav-link" href="{% url 'today' object.pk %}">Today</a> This is the url for the detail view: path('today/<int:pk>', TodaysView.as_view(), name='today') Is there anyway I could filter the dates inside of the template? -
Why does i am getting Django form: Key error
I am creating a creating a auction management system in which i was going to add the bid functionality and know i am facing this error i am highlighting the line in which i am getting error view.py class ItemDetailView(CreateView): template_name = "itemdetail.html" form_class = BidOnProduct success_url = reverse_lazy("auction:item_detail") def dispatch(self, request, *args, **kwargs): buyer_id = request.session.get("id") buyer_obj = Buyer.objects.filter(id=buyer_id) if buyer_obj: pass else: return redirect("auction:buyer_login") return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) item = Item.objects.get(slug=kwargs["slug"]) bids = Bid.objects.filter(item=item) context["item"] = item context["bids"] = bids return context def form_valid(self, form): buyer_id = self.request.session.get("id") if buyer_id: buyer_obj = Buyer.objects.get(id=buyer_id) form.instance.buyer = buyer_obj form.instance.item = Item.objects.get(slug=self.kwargs["slug"]) form.save() return redirect("auction:buyerhome") return super().form_valid(form) form.py class BidOnProduct(forms.ModelForm): class Meta: model = Bid fields = ["price"] Model.py class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) price = models.IntegerField() biding_time = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.user.username htmlcode {% if request.user.buyer %} <form class="form-horizontal" action="" method="post""> {% csrf_token %} {{form.as_p}} <button class=" btn btn-info"> Add product</button> </form> {%endif%} this is the error These are the line -
Problem in Setting backend data into dropdown using Django
I have a backend data and successfully set the data into dropdown but the thing is whenever click on button then it will give me the desire result but the thing is after getting the result, the drop down is like having null values in it so what can i do. could someone suggest me whenever i click on dropdown then it will get refress or other methods are appreciable. Thanks! views.py def index(request): sparqlQueries = get_data() if(request.POST['Case_name'] and request.method =='POST'): name_cases = sparqlQueries.nameOfCases() data = { "cases_name":name_cases, 'flag2':True, 'suffix':'Cases', 'title':'Name of Cases' } return render(request,'index.html',context = data) if(request.method =='POST'): casename = request.POST['Case_name'] question = request.POST['Question'] #print(casename) #print(question) ... -
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' …