Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to determine best batch_size for a queryset?
I have a model with 1M+ records. Whenever I do query on this model, I make sure not to get all the objects at once, so I use batching. Right now I use hard coded batch size of 100,000. But is there a way to determine best batch_size for any model I use. I mean on what factors does my batch_size depend on? I use MySQL as database. -
table * has no column named user_id,django
i have a app in which i have a foodpost model which has a foreign key for user. now when i m trying to save instance of foodpost model i m getting "table Food_foodpost has no column named user_id" i tried deleting migrations,makemigrations and migrate here is my foodpost model from django.db import models from django.contrib.auth.models import User # Create your models here. class FoodPost(models.Model): title = models.CharField(max_length=100,null=False) details = models.TextField() image = models.ImageField(upload_to='Food/',blank = True) quantity = models.IntegerField() category = models.CharField(max_length=100) location = models.CharField(max_length=100) price = models.IntegerField() # slug = models.SlugField(unique=True) created_post = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='FoodPost') # likes, no. of views def __str__(self): return self.title def delete(self,*args, **kwargs): self.image.delete() super().delete(*args,**kwargs) serializer class FoodPost_seriallizer(serializers.ModelSerializer): class Meta: model = FoodPost fields =['title', 'details', 'image', 'quantity', 'category', 'location', 'price', 'created_post', 'status', ] def create(self,validated_data): # print() # print(validated_data) foodPost = FoodPost(**validated_data,user=self.context.get("user")) foodPost.save() # foodPost.save() return foodPost and the view @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) # @parser_classes([JSONParser,FormParser,MultiPartParser]) def create_post(request): serializer = FoodPost_seriallizer(data = request.data,context = {"user":request.user}) if serializer.is_valid(raise_exception=True): foodpost = serializer.save() return Response(serializer.data) and of course the error File "/home/j0/anaconda3/envs/foodagram/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/j0/anaconda3/envs/foodagram/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: table Food_foodpost … -
Django webpage only displays properly if a character is placed after {% load static %}
If I structure the first two lines of my HTML doc like this: {% load static %} <!DOCTYPE html> It appears that none of the javascript or CSS run properly, and the webpage displays like this: However, if I put any character after the {% load static %} expression, For example, if I structure the first two lines of my HTML doc like this: {% load static %}. <!DOCTYPE html> Then the scripts and CSS components run properly and the webpage displays as it should. Why is this? -
How to make comments serializer work with post serializer in django rest framework.?
I have this comment serializer which is not working. It is showing this error { "post": [ "This field is required." ] } I am quite new to this, so can't really figure out how to properly link both the post and comment model. this is my serializer class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField() post = PostSerializer(many=True) class Meta: model = Comment fields = ['id', 'post', 'content', 'reply'] def create(self, validated_data): user = self.context['request'].user content = validated_data['content'] reply = validated_data['reply'] if reply: comment = Comment(user=user, content=content, reply=reply, post=post) comment.save() else: comment = Comment(user=user, content=content, post=post) comment.save() return validated_data view @api_view(['POST']) def comment_post_api(request, slug): try: post = get_object_or_404(Post, slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CommentCreateSerializer(post,data=request.data, context={'request':request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls path('<slug>/comment/', views.comment_post_api, name='comment_post'), Thanks -
Django when using python-ffmpeg-video-streaming get error The system cannot find the file specified in
In Django im using python-ffmpeg-video-streaming. AND this is my CODE: from django.conf import settings import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size video_file_path = settings.MEDIA_ROOT + '/' + self.video_path video = ffmpeg_streaming.input(video_file_path + 'video.mp4') _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264(), hls_list_size=10, hls_time=5) hls.representations(_480p, _720p) hls.fragmented_mp4() hls.output(video_file_path + 'hls.m3u8') when i run my i get this error. but i can see 'hls.m3u8' in file path directory. FileNotFoundError at /cpanel/videos/new/ [WinError 2] The system cannot find the file specified Request Method: POST Request URL: http://127.0.0.1:8000/cpanel/videos/new/ Django Version: 3.0.8 Exception Type: FileNotFoundError Exception Value: [WinError 2] The system cannot find the file specified -
Development wsgi server is getting stuck while returning a HttpResponse() in Django (debug=True)
I am sending username and password from the frontend using an ajax call to backends login() (in view.py) in django . where first I am authenticating the username and password and then setting the session variables for the same. After this, I am returning a message whether login is successful or not using: def login(request): user = request.POST.get('user') pwd = request.POST.get('pwd') msg = verify_user_credentials(user, pwd) if msg == True: reuest.session['user'] = user request.session['pwd'] = pwd return HttpResponse(msg) But while returning it is getting stuck and holding a terminal. So, the whole tool is getting hung. login() successfully checking the credentials and adding them up in session successfully each and every time but don't know why it is getting stuck while returning the HttpResponse(msg) in some cases. Additional Information: verify_user_credentials() is an internal function that verifies the user credentials. I am using debug = True, As tool is running in development mode. -
django error 1146 "Table 'buysell.sell_sellform' doesn't exist"
I am trying to create a form and store its data in the database I have created the model but then also it is showing error. models.py from django.db import models from django.contrib.auth.models import User class SellForm(models.Model): FICTION = 'fiction' Course = 'course' Non_Fiction = 'nonfic' book_category = [ (FICTION, 'Fiction'), (Course, 'Course'), (Non_Fiction, 'Non fiction'), ] NEW = 'new' OLD = 'old' book_condition =[ (NEW,'new'), (OLD, 'old'), ] ENGLISH = 'eng' HINDI = 'Hindi' book_lang =[ (ENGLISH,'english'), (HINDI,'hindi'), ] title = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.IntegerField() Category = models.CharField(max_length=20,choices=book_category,default=Course,) Condition = models.CharField(max_length=20,choices=book_condition,default=OLD) Language = models.CharField(max_length=20,choices=book_lang,default=HINDI) Description =models.CharField(max_length=200) book_img = models.ImageField(upload_to='images/') user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py from django import forms from .models import SellForm class FromSellForm(forms.ModelForm): class Meta: model = SellForm fields = ["title","author","price","Category","Condition","Language","Description","book_img"] views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import FromSellForm # Create your views here. def sell_book(request): if request.method == 'POST': form = FromSellForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = FromSellForm() context = {'form':form} return render(request,'buy/sellbook.html',context) sellbook.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> urls.py of sell app from django.urls import path from . import views urlpatterns = [ path('sell_book/', views.sell_book,name="sell_book"), ] … -
Django reset password: invalid token
I have deployed my Django project on production and test password reset using Django authentication I receive an email with link but I got the message 'Invalid token' meaning that link is invalid Settings.py ALLOWED_HOSTS = ['192.xxx.xx.xx','http://example.com/','https://example.com/'] #example.com replace by my real domain CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['example.com'] password_reset_email.html Une demande de modification de mot de passe a été demandé par {{ email }}. Veuillez suivre ce lien : {{ protocol}}://example.com{% url 'password_reset_confirm' uidb64=uid token=token %} PS : Merci de ne pas répondre à cet email -
making normal paginator buttons in django and bootstrap
i use django Paginator and use bootstrap4 in my templates projects. this my paginator code in my view : if request.method == "GET": orders = ProductOrder.objects.filter(status=1).order_by('-created_at') orders = Paginator(orders,5) page = request.GET.get('page') if page is None : page = 1 order_list = orders.page(page) print(len(orders.page_range)) index = order_list.number - 1 max_index = len(orders.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = list(orders.page_range)[start_index:end_index] for o in order_list: o.product.name = get_product_name(o.product) statuses = Status.objects.all() context = { 'orders' : order_list, 'page_range' : page_range, 'statuses' : statuses } return render(request,'staff/orders/products.html',context) and this is paginator section in html template : <ul class="pagination"> {%if orders.has_previous%} <li class="page-item"> <a class="page-link" href="?page={{orders.previous_page_number}}" tabindex="-1">قبلی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">قبلی</a> </li> {%endif%} {% for pg in page_range %} {% if blogs.number == pg %} <li class="page-item active"><a href="?page={{pg}}" class="page-link">{{pg}}<span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a href="&page={{pg}}" class="page-link">{{pg}}</a></li> {% endif %} {% endfor %} {%if orders.has_next%} <li class="page-item"> <a class="page-link" href="?page={{orders.next_page_number}}" tabindex="-1">بعدی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">بعدی</a> </li> {%endif%} </ul> code above render a paginator like this : paginator section as well you see last … -
Is it bad to design form layout in forms.py Django?
I'm new to Django. After few weeks learning, I've designed my form layout inside forms.py, like this: But it's quite annoying when I have to write html tag in string format without IDE styling, So do you guys have any ideas to design form layout in Django that is more clear and easy to maintain? Thank you... -
How to serve different CSS file when user change language in Django i18n translation
I am using Django i18n translation system and there are two languages: LANGUAGES = ( ('fa', _('Persian')), ('en', _('English')), ) Persian is Right-To-Left and I want to serve another CSS file when user change language to persian. Or maybe there is a better way to change LTR to RTL when user change the language? I am using nginx with wsgi on a Ubuntu vps. -
How to make Django url template with variable find the correct url
In my urls.py I have: path('experiments/charts/<str:part_tag>/', ExpViews.bokehChart, name='part_tag') I'd like to pass a string argument "part_tag" to the function bokehChart. and I'm trying to give the "path_tag" string variable some values as follows: {% for part in parts %} <ul class="list=group"> {% for datapoint in part.datapoints %} <a href="{% url 'part_tag' part.tag %}" class="list-group-item list-group-item-success"> {{datapoint}} </a> {% endfor %} </ul> {% endfor %} I get the following error on my webpage: Reverse for 'part_tag' not found. 'part_tag' is not a valid view function or pattern name. I know similar questions have been asked, but I can't get it to work in my case. -
How to delete a row and create new one with updated info in pre_save signal to avoid already exists error?
I want to edit existing row with pre_save signal and update quantity. here is my models class RFIDItem(models.Model): rfid = models.ForeignKey(RFIDInfo, on_delete=models.CASCADE, null=True, blank=True, related_name='rfid_item_rfid', help_text="Select RFID") product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True, related_name='rfid_item_pr_type', help_text="Select Product Type") quantity = models.PositiveIntegerField(_("Quantity"), default=0) expire_date = models.DateTimeField(default=datetime.now()) created_date = models.DateField(auto_now=False, auto_now_add=True) updated_date = models.DateField(auto_now=True, auto_now_add=False) If i add duplicate RFIDItems then my signal will edit/create new one with new quantity. I tried to do this i signal's pre_save method. Any Idea How can i do this. Thank You. and here is my signals. @receiver(pre_save, sender=RFIDItem) def create_related_models(sender, instance=None, *args, **kwargs): rfid = instance.rfid product_type = instance.product_type expire_date = instance.expire_date if RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date).exist(): rfid_item = RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date).last() rfid_item.delete() new_rfid = RFIDItem.objects.filter(rfid=rfid, product_type=product_type, credit_type=credit_type,expire_date=expire_date) new_rfid.quantity += instance.quantity new_rfid.save() -
I'm trying to get the environmental conditions of a city but this schema error keeps popping up
im trying to find the weather for a city and this error pops up. what does it mean ? my views def index (request) : url='api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=abb1576248c3805529abb4a8bd6a2b61' city='Las Vegas' r=requests.get(url.format(city)) print(r.text) return render(request,'weather/weather.html') mu urls urlpatterns = [ path('', views.index) ]``` -
How are Django custom widget assets retrieved by the browser?
I have been reading this part of the django documentation : https://docs.djangoproject.com/en/3.0/topics/forms/media/#assets-as-a-static-definition and this raised a question for me. I think in order for the animations and actions js files to be used by the browser they have to be referenced in a script html tag. As defining js assets in the form widget, like shown in the documentation, does not add any tag in the html template I do not understand how these files will be retrieved by the browser. -
Call a separate Python script in Django Views present at same location
I have a Django project name 'myproject' & app name 'dbapp' like this - myproject | |----dbapp | |----model.py | : |----views.py | |----start.py I want to run a Python script name 'start.py' through Django Views. I am using this syntax - @api_view(['GET', 'POST']) def page(request, uuid): if request.method == 'GET': call(["python3", "start.py"]) return Response('dbname') Python Script - 'start.py' call 2 other python scripts like this - call(["python3", "create_host.py"]) call(["python3", "create_main.py"]) If I run start.py, it works as expected running both the called python files. But Django Views is giving error when it call start.py script using given syntax. Error - python3: can't open file 'start.py': [Errno 2] No such file or directory How can I call a separate python file through Django views. I even tried this syntax - call(["python3", "urldbapp/start.py"]) This gives error like this - python3: can't open file 'start.py': [Errno 2] No such file or directory What syntax should I use? P.S. - 'start.py' is a small Python script but it further calls 2 Python scripts. -
How to display "permission_denied_message" in custom 403.html page in Django
How do we correctly display exception message in custom 403 error in Django? In my signup view I am using: class SignUpView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): login_url = 'error_403' # .... # ... permission_denied_message = 'You are not allowed this transaction!! Ha Ha!!' # raise PermissionDenied() # ('permission_denied_message') raise_exception = True Now how do I display the message ("permission_denied_message"?) in my custom 403.html? This is my function to render the error page: def error_403(request, exception): data = {} add_user = 'add_user' data = {'perm': add_user} return render(request, '403.html', data) I have been through a lot of matter on the subject (including those on SO) but could not succeed in displaying the error message (except the static message that I have put in my "403.html"). I have used {{ exception}} in the template but nothing gets displayed (execpt the static message that I already have). 1. How do I display the permission_denied_message in custom 403 page? 2. Presently I am manually updating some raw data in dict data{} in function error_403, which gets rendered on the 403 error page. What is the correct usage of the dict? -
How to prevent extra query for this field in Django?
I have models like this: class City(models.Model): some_field = models.ForeignKey('self') name = models.CharField(max_length=100) class Author(models.Model): city = models.ForeignKey(City) # other fields def get_some_field(self): return self.city.some_field some_field = cached_property(get_some_field, name='some_field') I fetch Author queryset something like this: author_qs = Author.objects.filter(**some_filter).select_related('city') Now after fetching the queryset, I do something like this: city_name = author_qs.some_field.name But this line is querying the database again for City model. How can I prevent this extra query, and get city_name with previous query only. P.S. I cannot directly get author_qs.city.name. I require it to call from some_field only -
Subtraction in Django using many to many relationship
I have two models Order and Supplement, The Order model has many to many relationship with the Supplement model. I'm using celery to run a task that subtracts the quantity of a selected supplement. The problem I'm facing is that I'm only able to subtract from 1 supplement even if I have selected more than 1 supplement in my order.supplement field. class Order(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=100) status = models.CharField(max_length = 100) box = models.IntegerField(max_length = 100) supplement = models.ManyToManyField('Supplement') class Supplement(models.Model): stockId = models.AutoField(primary_key=True) brand_name = models.CharField(max_length=100) supplement_name = models.CharField(max_length=100) supplement_type = models.CharField(max_length=100) quantity = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.supplement_name tasks.py def deduct_inventory(): orders = Order.objects.all() for order in orders: if order.status == 'Shipped': for supplement in order.supplement.all(): Supplement.objects.filter(supplement_name=supplement.supplement_name).update(quantity=F('quantity') - order.box*30) Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-order.box) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-order.box) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-order.box) order.status='Delivered' order.save() return None -
ValueError: Missing staticfiles manifest entry for 'favicon.png'
I'm trying to deploy my django web app to heroku for the first time, but I keep getting a 500 server error. This is what I see when I check the logs: 2020-07-30T05:03:27.965070+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 423, in stored_name 2020-07-30T05:03:27.965070+00:00 app[web.1]: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2020-07-30T05:03:27.965070+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'favicon.png' 2020-07-30T05:03:27.965366+00:00 heroku[router]: at=info method=GET path="/" host=programatic-learning.herokuapp.com request_id=1332a937-88d1-48f0-8aac-0847852e467d fwd="67.70.149.199" dyno=web.1 connect=1ms service=72ms status=500 bytes=380 protocol=https 2020-07-30T05:03:27.965534+00:00 app[web.1]: 10.63.123.248 - - [30/Jul/2020:05:03:27 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" 2020-07-30T05:33:17.000000+00:00 app[api]: Build started by user stephenlang91@gmail.com 2020-07-30T05:34:28.791656+00:00 app[api]: Deploy 599627a3 by user stephenlang91@gmail.com 2020-07-30T05:34:28.791656+00:00 app[api]: Release v8 created by user stephenlang91@gmail.com 2020-07-30T05:34:28.961452+00:00 heroku[web.1]: Restarting 2020-07-30T05:34:28.976045+00:00 heroku[web.1]: State changed from up to starting 2020-07-30T05:34:30.150144+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2020-07-30T05:34:30.184774+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [9] [INFO] Worker exiting (pid: 9) 2020-07-30T05:34:30.184787+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-07-30T05:34:30.185022+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [4] [INFO] Handling signal: term 2020-07-30T05:34:30.385825+00:00 app[web.1]: [2020-07-30 05:34:30 +0000] [4] [INFO] Shutting down: Master 2020-07-30T05:34:30.461780+00:00 heroku[web.1]: Process exited with status 0 2020-07-30T05:34:35.278873+00:00 heroku[web.1]: Starting process with command `gunicorn blog.wsgi --log-file -` 2020-07-30T05:34:37.599742+00:00 … -
how can i controll static entry in django?
I want call django static files. i use django_debug_toolbar anddrf_yasg. my stage is local and dev (deploy docker container, DEBUG=True). and Staticfile in AWS S3 django_storages when i access swagger page in local stage, chrome development tool Source like this. - top - 127.0.0.1:8000 - swagger - index - static - debug_toolbar - drf_yasg and dev stage, chrome development tool Source like this. - top - 127.0.0.1:8000 - swagger - index - blarblar.s3.amazonaws.com - static/drf_yasg can u see that? i dont understatnd this. i want static both debug toolbar and drf yasg. my settings base.py STATIC_URL = '/static/' local.py STATIC_ROOT = os.path.join(ROOT_DIR, 'static') dev.py AWS_S3_REGION_NAME = os.environ.get('AWS_REGION', 'ap-northeast-2') AWS_STORAGE_BUCKET_NAME = S3_Storange_name STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storage.StaticStorage' what can i do? i don't know what i should do. -
Django-silver package pip installer error
First time trying to ask question here. I was trying to install django-silver (a Django package for invoice). However I encountered the following error in my Windows command line. I have made sure my python, pip, django versions are all up-to-date. I am using virtual environment to install django-silver package. Error here (I can't insert all due to character limit): C:\Users\bigfa\PycharmProjects\silver_test\venv\silver_test\Scripts>pip install django-silver Processing c:\users\bigfa\appdata\local\pip\cache\wheels\96\1a\a5\28dd03757aa4e0922a390c62c65bf74a95011c6cb9af20432f\django_silver-0.10.0-py3-none-any.whl Requirement already satisfied: django-livefield<3.3,>=2.8 in c:\python38\lib\site-packages (from django-silver) (3.2.1) Requirement already satisfied: django-autocomplete-light<3.3,>=3.2 in c:\python38\lib\site-packages (from django-silver) (3.2.10) Requirement already satisfied: python-dateutil<2.8,>=2.6 in c:\python38\lib\site-packages (from django-silver) (2.7.5) Processing c:\users\bigfa\appdata\local\pip\cache\wheels\ea\13\5b\39f00fc59997caaaa0031e791afc8a2618f35c4eb92f646461\furl-1.2.1-py3-none-any.whl Requirement already satisfied: sqlparse<0.3,>=0.2 in c:\python38\lib\site-packages (from django-silver) (0.2.4) Processing c:\users\bigfa\appdata\local\pip\cache\wheels\b1\1a\8f\a4c34be976825a2f7948d0fa40907598d69834f8ab5889de11\pypdf2-1.26.0-py3-none-any.whl Requirement already satisfied: django-annoying<0.11,>=0.10 in c:\python38\lib\site-packages (from django-silver) (0.10.6) Requirement already satisfied: django-filter<2.1,>=1.1 in c:\python38\lib\site-packages (from django-silver) (2.0.0) *various requirement satified* Requirement already satisfied: cffi!=1.11.3,>=1.7 in c:\python38\lib\site-packages (from cryptography<2.4,>=1.9->django-silver) (1.14.0) Requirement already satisfied: setuptools in c:\users\bigfa\pycharmprojects\silver_test\venv\silver_test\lib\site-packages (from djangorestframework-bulk<0.3->django-silver) (49.2.0) Requirement already satisfied: pytz in c:\python38\lib\site-packages (from Django<2.3,>=1.11->django-silver) (2020.1) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (1.25.10) Requirement already satisfied: certifi>=2017.4.17 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (2020.6.20) Requirement already satisfied: chardet<4,>=3.0.2 in c:\python38\lib\site-packages (from requests<3.0,>=1.0.0->pyvat<1.4,>=1.3->django-silver) (3.0.4) Collecting webencodings Using cached webencodings-0.5.1-py2.py3-none-any.whl (11 kB) Requirement already satisfied: pycparser in c:\python38\lib\site-packages (from cffi!=1.11.3,>=1.7->cryptography<2.4,>=1.9->django-silver) (2.20) Building wheels for collected … -
Error 'expected string or bytes-like object' in Django
I'm trying to create a new record in my Django model but I just can't. Here is the Sell class model: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) discount = models.DecimalField(max_digits=6, decimal_places=2) total_paid = models.DecimalField(max_digits=6, decimal_places=2) buyer = models.ForeignKey(User, related_name='sell', on_delete=models.CASCADE) Here is the code in my view.py: Sell.objects.create(item=item, date=timezone.now, discount=Decimal(0.00), total_paid=cart.get_total_price(), buyer=request.user, ) If I print all of this variables, the result is: print(item) 266 print(type(item)) <class 'dma.models.Buy'> print(timezone.now) <function datetime.date at 0x03D3F460> print(type(timezone.now)) <class 'function'> print(type(Decimal(0.00))) <class 'decimal.Decimal'> print(cart.get_total_price()) 68.00 print(type(cart.get_total_price())) <class 'decimal.Decimal'> print(request.user) Felipe print(type(request.user)) <class 'django.utils.functional.SimpleLazyObject'> Error: Exception Type: TypeError Exception Value: expected string or bytes-like object -
Django AttributeError: <Object> needs to have a hvalue for field "id" before this many-to-many relationship can be used
My issue: I'm trying to add some models to my database through the admin path on my django project, but this error keeps popping up when I try to create an instance of my model. The clean function exists to ensure that each Pokemon model can only have up to 2 types selected from a list of all possible types. My code: from django.db import models from django.core.validators import MinValueValidator as min, MaxValueValidator as max from django.core.exceptions import ValidationError class PokeType(models.Model): poke_type = models.CharField(max_length=15) def __str__(self): return self.poke_type #Current generation of games for gen_added field gen = 8 class Pokemon(models.Model): poke_name = models.CharField(max_length=30) poke_type = models.ManyToManyField(PokeType, blank=True, null=True) evolves_from = False evolves_into = False gen_added = models.PositiveIntegerField(validators=[min(1), max(gen)]) def clean(self): #Allow max of 2 poke_types to be selected if self.poke_type.count() > 2: raise ValidationError('A Pokemon has a maximum of two types.') class Meta: verbose_name_plural = 'Pokemon' abstract = True class CustomPokemon(Pokemon): name = models.CharField(max_length=30) level = models.PositiveIntegerField(blank=True, null=True) def __str__(self): return self.name What I (kind of) know: Based on what I've seen from other people asking this question, I need to save the instance of my model before I can use the many-to-many relationship in the clean function. Also, I … -
Dockerized Django Project on Heroku -- User Account App Gives HTTP 500 Error
I have just deployed a Dockerized Django project to a Heroku Hobby Dyno, and there seems to be some issues with users logging in and accessing the account portion of the website. The homepage app works perfectly, but that's about all that works. Even as a superuser, I can access the main screen of the admin page, but when I click on one of the model names, a 500 error code is thrown. The only model I can access is the default user model Django provides. This is also the case for any users trying to access accounts. I can get new users registered and added to the User model, but they are unable to reach any portion of the website that requires being logged in--not even their profile page. Here is my project directory: project-root >account #this is the app causing the issues >env #env directory >homescreen #this app works fine >media #user-upload directory >mementos -.dockerignore -.gitignore -db.sqlite3 -Dockerfile -manage.py -Pipfile -requirements.txt The Heroku logs are pretty vague. Here's what I get when a user tries to access their account: 2020-07-30T04:04:14.923403+00:00 heroku[router]: at=info method=GET path="/account/" host=**********.herokuapp.com request_id=c9cbe319-7ff0-4dc8-8105-0b16e10d74ae fwd="35.25.10.57" dyno=web.1 connect=0ms service=68ms status=500 bytes=413 protocol=http Same thing happens when I …