Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix nextToken for amazon api and python
i need some help to fix nextToken for this method : https://sp-api-docs.saleweaver.com/endpoints/inventories/ this is my code it's work but bring just 50 products and there is more then that, i try but i don't know how to fix it: product_client = Inventories(credentials=credentials) product_c = ListingsItems(credentials=credentials) res = product_client.get_inventory_summary_marketplace(**{"details": True,"marketplaceIds": ["********"]},next_token=None).payload for item in res.get("inventorySummaries"): try: _sellerSku=item.get("sellerSku") _asin =item.get("asin") resultat = product_c.get_listings_item(sellerId='********', sku=_sellerSku).payload for summaries in resultat.get("summaries"): _created_date = summaries.get("createdDate") _lastupdate_date = summaries.get("lastUpdatedDate") _mainImage = summaries.get("mainImage").get("link") _title =summaries.get("itemName") _condition =summaries.get("conditionType") inst = ProduitsAmz(asin=_asin, sellersku=_sellerSku,created_date=_created_date,lastupdate_date=_lastupdate_date,mainImage=_mainImage,title=_title,condition=_condition) inst.save() except: pass response is like this with more result : 'rate_limit': '5.0'} {'errors': None, 'headers': {'Date': 'Tue, 10 May 2022 16:12:10 GMT', 'Content-Type': 'application/json', 'Content-Length': '483', 'Connection': 'keep-alive', 'x-amzn-RequestId': 'c8eae15a-****-427c-b463-********', 'x-amzn-RateLimit-Limit': '5.0', 'x-amz-apigw-id': 'R******=', 'X-Amzn-Trace-Id': 'Root=1-627a8eda-*********'}, 'next_token': None, 'pagination': None, 'payload': {'sku': '*******', 'summaries': [{'asin': '*******', 'conditionType': 'used_good', 'createdDate': '2022-04-13T00:43:02.348Z', 'fnSku': '*******', 'itemName': 'Deadly Dose: The Untold Story of a ' "Homicide Investigator's Crusade for " 'Truth and Justice', 'lastUpdatedDate': '2022-04-13T01:46:25.755Z', 'mainImage': {'height': 500, 'link': 'https://m.media-amazon.com/images/I/******.jpg', 'width': 311}, 'marketplaceId': '*******', 'productType': 'ABIS_BOOK', 'status': ['DISCOVERABLE']}]}, I need some help to fix nexttoken and if there is any option to bring link for offer please (url in amazon), it's my seller account and i use amazon sp-api. Thank … -
problem with migrating on heroku with django windows 10
I am trying to migrate the database from django to heroku, the deploy is done correctly, but when doing heroku run python manage.py migrate, I get the following error https://www.toptal.com/developers/hastebin/kumayunigu.sql Does anyone know what is going on? here is my log https://www.toptal.com/developers/hastebin/uciyoxecuq.sql heroku error -
http status code 502, normal after refresh. uwsgi caused? nginx caused?
python + Django + uwsgi + nginx when the user visits the webpage, HTTP request returns 502 status code. And then the user immediately refreshes the page, it can be opened normally. Many users are getting this error. At this time, the concurrency is not large, no more than 20 users. I don't know what is causing the 502 error. Does anyone know how to solve it? For 502 errors, the uwsgi received a lot of error logs. like this: 9 16:07:37 2022] GET /usernames/chengyuyao@/count/ => generated 1658 bytes in 5 msecs (HTTP/1.0 404) 9 headers in 310 bytes (3 switches on core 0) uwsgi_proto_http_parser(): Bad address [proto/http.c line 463] !!! uWSGI process 115 got Segmentation Fault !!! *** backtrace of 115 *** /usr/local/bin/uwsgi(uwsgi_backtrace+0x2f) [0x55c95079ca7f] /usr/local/bin/uwsgi(uwsgi_segfault+0x23) [0x55c95079ce43] /lib/x86_64-linux-gnu/libc.so.6(+0x3bd60) [0x7f6e96acad60] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x1c) [0x7f6e96b1973c] /usr/local/bin/uwsgi(uwsgi_close_request+0x13b) [0x55c9507519eb] /usr/local/bin/uwsgi(py_uwsgi_gevent_request+0x100) [0x55c9507c3e20] /usr/local/lib/libpython3.6m.so.1.0(PyCFunction_Call+0x45) [0x7f6e96d9f5f5] /usr/local/lib/python3.6/site-packages/gevent/_gevent_cgreenlet.cpython-36m-x86_64-linux-gnu.so(+0x10b6c) [0x7f6e91034b6c] /usr/local/lib/python3.6/site-packages/gevent/_gevent_cgreenlet.cpython-36m-x86_64-linux-gnu.so(+0x29182) [0x7f6e9104d182] /usr/local/lib/python3.6/site-packages/gevent/libev/corecext.cpython-36m-x86_64-linux-gnu.so(+0x23fff) [0x7f6e91e13fff] /usr/local/lib/libpython3.6m.so.1.0(_PyObject_FastCallDict+0x8a) [0x7f6e96d7418a] /usr/local/lib/libpython3.6m.so.1.0(_PyObject_Call_Prepend+0x67) [0x7f6e96d74b07] /usr/local/lib/libpython3.6m.so.1.0(PyObject_Call+0x47) [0x7f6e96d74587] /usr/local/lib/python3.6/site-packages/greenlet/_greenlet.cpython-36m-x86_64-linux-gnu.so(+0x3819) [0x7f6e92898819] /usr/local/lib/python3.6/site-packages/greenlet/_greenlet.cpython-36m-x86_64-linux-gnu.so(+0x3a8f) [0x7f6e92898a8f] [0x7f6e8eff1588] *** end of backtrace *** uwsgi config: stdout_logfile_backups=5 enable-threads = true processes = 16 workers = 16 threads = 8 max-requests = 10000 master = true listen = 65536 #http-keepalive = true disable-logging = True nginx local.conf: client_body_buffer_size 128k; proxy_buffer_size 64k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; … -
What are the names of the endpoints provided by the Django auth app?
What are the names of the endpoints provided by the Django auth model? E.g., if I want to link to the login page, what do I put in the template? <a href={% url ???? %}>Login</a> -
Object of type Decimal is not JSON serializable
I got an error: TypeError at /cart/ Object of type Decimal is not JSON serializable Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: Object of type Decimal is not JSON serializable The fact is that I store my favorites and the basket in the same session, and when one of these is not filled (favorites / basket), this error appears. When the products are in both lists everything is fine. allow_nan True check_circular True cls <class 'json.encoder.JSONEncoder'> default None ensure_ascii True indent None kw {} obj {'cart': {'2': {'price': Decimal('123123.12'), 'product': <Product: test1>, 'quantity': 2, 'total_price': Decimal('246246.24'), 'update_quantity_form': <CartAddProductForm bound=False, valid=Unknown, fields=(quantity;update)>}}, 'featured': {}} separators (',', ':') skipkeys False sort_keys False How can i fix it? -
Python mixin: Why is my serialized field not coming through?
Trying to write a very simple python mixin for setting ReadOnly status'. This is what i have class ReadOnlyMixin: readonly_fields = serializers.SerializerMethodField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.get_readonly_fields(): self.fields[field].read_only = True def get_readonly_fields(self): raise NotImplementedError( "Classes subclassing ReadOnlyMixin must implement a " "`get_readonly_fields` method" ) and in my serializer class, I have class TestSerializer(mixins.ReadOnlyMixin, serializers.ModelSerializer): class Meta: model = models.Test fields = '__all__' def get_readonly_fields(self): exp = self.instance return ['status'] if exp.status != 'Pending' else [] Other fields in the serializer come thru, but readonly_fields does not. Everything is getting called as well because my self.fields['status'].read_only is getting upddated to True. Even if I just assign readonly_fields = ['status'], it still doesnt come thru. What am i doing wrong? -
Django: URLs to apps showing 404 errors
I have added three apps to my django website: application, blog, and feedback. All three have the same problem: when I click a link, or enter a URL, to any of them, I get a 404 error. I'm attaching code and other documentation below for one of the problem addons. For further context, if necessary, my full code can be found at https://github.com/kkerwin1/pensdnd. Directory structure (venv) kris@adjutant:~/venv/pensdnd$ tree -if . ./application ./application/admin.py ./application/apps.py ./application/forms.py ./application/__init__.py ./application/migrations ./application/models.py ./application/templates ./application/templates/application.html ./application/templates/application_thanks.html ./application/tests.py ./application/urls.py ./application/views.py ./blog ./blog/admin.py ./blog/apps.py ./blog/models.py ./blog/templates ./blog/templates/blog_list.html ./blog/templates/blog_post.html ./blog/tests.py ./blog/urls.py ./blog/views.py ./feedback ./feedback/admin.py ./feedback/apps.py ./feedback/forms.py ./feedback/models.py ./feedback/templates ./feedback/templates/feedback.html ./feedback/templates/feedback_thanks.html ./feedback/tests.py ./feedback/urls.py ./feedback/views.py ./manage.py ./pensdnd ./pensdnd/settings.py ./pensdnd/static ./pensdnd/static/css ./pensdnd/static/css/main.css ./pensdnd/static/html ./pensdnd/static/html/arvon_rules.html ./pensdnd/static/html/be_a_dm.html ./pensdnd/static/html/community_rules.html ./pensdnd/static/html/guild_rules.html ./pensdnd/static/html/index.html ./pensdnd/static/html/volunteer.html ./pensdnd/static/img ./pensdnd/static/img/carbon_fibre.png ./pensdnd/static/img/github_icon.png ./pensdnd/static/js ./pensdnd/static/misc ./pensdnd/static/templates ./pensdnd/static/templates/base.html ./pensdnd/static/templates/partials ./pensdnd/static/templates/partials/blogbar.html ./pensdnd/static/templates/partials/feedback.html ./pensdnd/static/templates/partials/footer.html ./pensdnd/static/templates/partials/navbar.html ./pensdnd/static/templates/partials/newsbar.html ./pensdnd/static/vid ./pensdnd/urls.py ./pensdnd/views.py ./pensdnd/wsgi.py ./requirements.txt ./pensdnd/urls.py from django.contrib import admin from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.HomePageView.as_view()), path('admin/', admin.site.urls), path('be_a_dm', views.BeADM.as_view()), path('blog', include('blog.urls')), path('feedback', include('feedback.urls')), path('application', include('application.urls')), path('guild_rules', views.GuildRules.as_view()), path('community_rules', views.CommunityRules.as_view()), path('arvon_rules', views.ArvonRules.as_view()), path('volunteer', views.Volunteer.as_view()), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ./blog/urls.py from . import views from django.urls import path urlpatterns = [ path('blog', views.PostList.as_view()), path('blog/<slug:slug>/', views.PostDetail.as_view(), … -
Django Conditional Expressions to display different text strings based on Foreignkey value
I am trying to get a product description to automatically format based on the fields in the database record. I have looked at the Case() method but not sure if I can use it? The function is not working and only displays the value in the elif at the end, which I have given "not working" as a test. Models.py: from django.db import models from django.utils.functional import cached_property class FilmSpecs(models.Model): NO_UP = ( (1,'1 Up'), (2,'2 Up'), (4,'4 Up'), (6,'6 Up'), (8,'8 Up'), ) TINTS = ( ('NAT', 'Natural'), ('TNT', 'Tinted'), ('OPQ', 'Opaque'), ) SLIPLEVEL = ( ('STD', 'Standard'), ('LOW', 'Low Slip'), ('HIGH', 'High Slip'), ) stock_code = models.CharField(max_length=200, verbose_name="Stock Code", unique=True) desc = models.CharField(max_length=200, null=False, blank=False, verbose_name="Film Description") label_desc = models.CharField(max_length=200, verbose_name="Label Description") film_type = models.ForeignKey('settings.FilmType', on_delete=models.CASCADE, null=True, blank = False, related_name='film_type', verbose_name="Film Type") sale_type = models.ForeignKey('settings.SaleType', on_delete=models.CASCADE, null=True, blank = False, related_name='sale_type', verbose_name="Sale Type") film_width = models.IntegerField(null=True, blank=False, verbose_name="Film Width (mm)") guss_closed_width = models.IntegerField(null=True,blank=False, default=0, verbose_name="Gussetted Closed Width (mm)") micron = models.FloatField(null=False,blank=False, default=0,verbose_name="Micron") slip_level = models.CharField(max_length=30, choices=SLIPLEVEL, null=True) roll_weight = models.IntegerField(null=True, blank=True, verbose_name="Roll Weight (kg)") strip_out_size = models.IntegerField(null=True, blank=True, verbose_name="Strip Out Size (mm)") edge_trim_size = models.IntegerField(null=True, blank=True, verbose_name = "Edge Trim (mm)") tint = models.CharField(choices=TINTS, max_length=200, default="NAT", null=True, … -
Django/Python: execute code (sending email) without waiting for it to finish then immediately response to the client side
My question is basically the Python version of this question: code structure: def save(request): if request.method == 'POST': ... obj.save() # write data into database # the below sendmail step takes too long to finish # how to execute it without waiting for it to finish # then immediately run the last step: return render(request, 'success.html') sendmail(email) # return render(request, 'success.html') -
Django Python - Post not saving in Database Postgresql
I have an issue where my Django form is not posting into my Postgres database. Payload seems like all data is captured in variables. Here is my code if anyone can shine some light? Form is posted and redirect back to form etc however data isn't passed onto the database. Have tried this as an AJAX post too but still the same, capturing variables but not passing into the database for some reason. Views.py def createResidential(request): if request.method!="POST": return HttpResponseRedirect(reverse("apps:customers.create")) else: residential_firstname=request.POST.get("residential_firstname") residential_lasttname=request.POST.get("residential_lasttname") residential_contact=request.POST.get("residential_contact") residential_mobile=request.POST.get("residential_mobile") residential_email=request.POST.get("residential_email") residential_houseflatno=request.POST.get("residential_houseflatno") residential_houseflatname=request.POST.get("residential_houseflatname") residential_streetname=request.POST.get("residential_streetname") residential_city=request.POST.get("residential_city") residential_county=request.POST.get("residential_county") residential_postcode=request.POST.get("residential_postcode") try: postResidential=ResidentialCustomer( residential_firstname=residential_firstname, residential_lasttname=residential_lasttname, residential_contact=residential_contact, residential_mobile=residential_mobile, residential_email=residential_email, residential_houseflatno=residential_houseflatno, residential_houseflatname=residential_houseflatname, residential_streetname=residential_streetname, residential_city=residential_city, residential_county=residential_county, residential_postcode=residential_postcode, ) postResidential.save() messages.success(request,"Data Save Successfully") return HttpResponseRedirect(reverse('apps:customers.create')) except: messages.error(request,"Error in Saving Data") return HttpResponseRedirect(reverse('apps:customers.create')) Models.py class ResidentialCustomer(models.Model): residential_firstname = models.TextField() residential_lasttname = models.TextField() residential_contact = models.IntegerField() residential_mobile = models.IntegerField() residential_email = models.EmailField() residential_houseflatno = models.IntegerField() residential_houseflatname = models.TextField() residential_streetname = models.TextField() residential_city = models.TextField() residential_county = models.TextField() residential_postcode = models.TextField() residential_dateCreated = models.DateTimeField(default=timezone.now) agent = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return f"{self.residential_firstname} {self.residential_lasttname}" Form in html page <form action="{% url 'apps:createResidential' %}" method="POST" class="vertical-navs-step">{% csrf_token %} <div class="form-floating"> <input type="text" class="form-control" name="residential_firstname" placeholder="John"> <label for="residential_firstname">First Name</label> </div> Same for all other fields I need to capture … -
How can I move Django models to a different django app? I'm not sure the migrage --fake option can work for me since I have 2 cases to consider
In moving models from one django app to another, I used the approach recommended from this question: Moving multiple models from one django app to another class Post(models.Model): title = models.CharField(max_length=120) class Meta: db_table = 'blog_post' However, in my case, I also have some models that need to migrate, in addition to the ones that I'm moving to another app. Since I want some tables to stay intact (the ones migrating to another app), and some others to actually change, then I don't think the migrate --fake is an option I can use. What can I do? -
How to test django using test sqlite3 database instead default mysql database?
My databases in settings.py 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'mydb.com', 'TEST': { # it's not works 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } But TEST section not work. I use this code and it works but i don't like it. Maybe there are other way in databases section describe test database? if 'test' in sys.argv: DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } -
Can't hit django views.py function from URL
I'm new to Django-react and having problem in hitting specific function of views.py file using URL. Here is my main project URL file urlpatterns = [ path('admin/', admin.site.urls), path('company/', include('manageCompany.urls')), ] Here it's manageCompany.urls file router = DefaultRouter() router.register('', CompanyViewSet, basename='companies') urlpatterns = [ # path('', index), path('', include(router.urls)), path('saveFile/', SaveFile) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here's my views.py file class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer @csrf_exempt def SaveFile(request): if request.method == 'POST': file = request.FILES['file'] file_name = default_storage.save(file.name, file) return JsonResponse(file_name, safe=False) return JsonResponse("Hello") Now I'm trying to hit saveFile method from postman using POST method using URL http://127.0.0.1:8000/company/saveFile/ but it's showing "Method \"POST\" not allowed." Where it's going wrong? What should be my URL so that I could hit that SaveFile function? -
Not hashing password. Unexpected keyword argument 'password2'
I have three different questions. They're all related to each other. 1 - I get an error when I add password2 or confirm_password field. Got a `TypeError` when calling `CustomUser.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `CustomUser.objects.create()`. You may need to make the field read-only, or override the UserCreateSerializer.create() method to handle this correctly. TypeError: CustomUser() got an unexpected keyword argument 'confirm_password' 2 - Without any validate when I only have password field. I am not getting any errors but passwords are not hashed. 3 - When I want to create user using shell. Even if I leave all the fields blank, I can create an empty user without any errors. -
Django + uwsgi = Sqlite: cannot operate on a closed database
I have a Django application that works fine when running it with python manage.py runserver. After I added uwsgi, I frequently started to encounter the error Cannot operate on a closed database. The very same endpoint that raises this error works fine if I call it manually from a browser. The errors occur usually after a few hundreds / thousands call (coming really fast) which are made by another service. Here's my uwsgi settings: [uwsgi] chdir = ./src http = :8000 enable-threads = false master = true module = config.wsgi:application workers = 5 thunder-lock = true vacuum = true workdir = ./src add-header = Connection: Keep-Alive http-keepalive = 65000 max-requests = 50000 max-requests-delta = 10000 max-worker-lifetime = 360000000000 ; Restart workers after this many seconds reload-on-rss = 2048 ; Restart workers after this much resident memory worker-reload-mercy = 60 ; How long to wait before forcefully killing workers lazy-apps = true ignore-sigpipe = true ignore-write-errors = true http-auto-chunked = true disable-write-exception = true -
Python/Django Test: Mock Verification Service
I am attempting to write a test for a service that uses the Twilio Verification service. I am basing my test off of the following article: https://www.twilio.com/blog/testing-twilio-applications-python-pytest However, I cannot seem to properly target the client.services.verify.services method from the TwilioRest module as the request always gets sent to the Twilio server. Has anyone had any success properly mocking this method ? verification/services.py from decouple import config from twilio.rest import Client from twilio.base.exceptions import TwilioRestException from .config import INVALID_PARAMETER, TOO_MANY_REQUESTS account_sid_production = config("TWILIO_ACCOUNT_SID_PRODUCTION") auth_token_production = config("TWILIO_AUTH_TOKEN_PRODUCTION") verify_service_sid = config("TWILIO_VERIFY_SERVICE_SID") client = Client(account_sid_production, auth_token_production) def verification_service_create(phone_number, channel="sms"): try: client.verify.services(verify_service_sid).verifications.create( to=phone_number, channel=channel ) return ( True, "Check your phone for verification code", "Verification Code successfully sent", ) except TwilioRestException as error: if error.code == INVALID_PARAMETER: return ( False, "Phone value is incorrectly formatted or is not a valid phone number.", "Use strict E.164 formatting, including the + sign," "for phone numbers in the To parameter. Example: +15017122661.", ) if error.code == TOO_MANY_REQUESTS: return ( False, "You have sent too many requests to this service. Please try again later.", "You have sent too many requests to this service. Please try again later.", ) return ( False, "Internal Error", "Internal Error", ) verification/tests/services/test_verification_service_create.py from unittest.mock … -
How to fix a faulty decrease product quantity button for a django ecommerce store?
I'm trying to wire up a decrease quantity (minus) button to reduce the number of products in a shopping cart for a django e-commerce store. However, when I click the minus button either A) nothing happens, or B), if I click the minus button after increasing the quantity with the plus button, the minus button performs the same task as the 'update' button, i.e. confirming the quantity change to the newly higher number of products. The relevant views.py function: def adjust_cart_item_qty(request, item_id): # changes number of items in the cart qty = int(request.POST.get('qty')) cart = request.session.get('cart', {}) if qty > 0: cart[item_id] = qty else: cart.pop(item_id) request.session['cart'] = cart return redirect(reverse('cart')) The app-level urls.py: from django.urls import path from .views import CartView from . import views urlpatterns = [ path('', CartView.as_view(), name='cart'), path('add/<item_id>', views.add_cart_item, name='add_cart_item'), path('adjust_cart/<item_id>', views.adjust_cart_item_qty, name='adjust_cart'), path('remove_cart_item/<item_id>', views.remove_cart_item, name='remove_cart_item'), ] The html template: {% extends 'base.html' %} {% load static %} {% block content %} {% if cart_items %} <div class="row"> <div class="col-md-12 text-center mt-3 mb-3"> <h1>Your shopping cart</h1> </div> </div> {% for item in cart_items %} <div class="row"> <div class="col-md-6"> <div class="card card-wide"> <ul class="list-group list-group-flush"> <li class="list-group-item text-center text-uppercase">Course: {{ item.course.title }} </li> <li class="list-group-item">Level: {{ … -
Port doesnt respond
After python manage.py runserver , all goes well,when I use the link http://127.0.0.1:8000/ generated it fails to open the Django project on windows 10 completely, I can't figure out the problem. I've tried disabling proxies and firewalls and antivirus but still unable to open.Also tried restarting the computer and entire procedure,spent hours on this, what could be the problem -
Deploy Sphinx docs on django server
Recently I have been creating docs usign sphinx. Now when the docs are done I want to deploy them on my web app under like /docs/ url. Is here any good tool that is capable of doing that ? So far I found tool that is able to deploy the docs under url but the docs look awful - it takes the json created by make and render the data… https://github.com/carltongibson/django-sphinx-view Thanks for any ideas. -
Need to save all answers from a user on every questions related on a specific Quiz
I want to save after submitting all answers from a user of all questions related on a specific Quiz. The logical is : I've got Quiz, Questions. Question car link to Quiz and when I choose a quiz all questions link to are shown on webpage with javascript (design). After submiting I need to get all checkbox checked and save into UserResponse. Models class Question(models.Model): objects = None question = models.CharField(max_length=200, null=True) description = models.CharField(max_length=255, null=True) question_pic = models.ImageField(upload_to='poll/', storage=fs, null=True) choices = models.ManyToManyField(Answer, related_name='QuestionsChoices') mandatory = models.BooleanField(default=True) multiple = models.BooleanField(default=False) randomize = models.BooleanField(default=False) class Quiz(models.Model): STATUS_CHOICES = ( (1, 'Draft'), (2, 'Public'), (3, 'Close'), ) nom = models.CharField(max_length=200, null=False) theme = models.ForeignKey(Theme, null=False, on_delete=models.CASCADE) questions = models.ManyToManyField(Question, related_name='Quizs') status = models.IntegerField(choices=STATUS_CHOICES, default=1) published = models.DateTimeField(null=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now_add=True) class QuizInstance(models.Model): objects = None """ A combination of user response and a quiz template. """ player = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) start_quiz = models.DateTimeField(auto_now_add=True) score = models.IntegerField(default=0) complete = models.BooleanField(default=False) class UserResponse(models.Model): objects = None """ User response to a single question. """ quiz_instance = models.ForeignKey(QuizInstance, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) response = models.ManyToManyField(Answer, related_name="UserResponses") time_taken = models.DateTimeField(auto_now_add=True) time_taken_delta = models.DateTimeField(blank=True) VIEWS (to show all … -
Django - __init__() missing 1 required positional argument: 'request'
I have the following error: CompareFormTransporterCompany.__init__() missing 1 required positional argument: 'request'. Here is my form in forms.py: class CompareFormTransporterCompany(forms.ModelForm): file = forms.FileField(label="File (CSV, XLSX, XML) ", required=True) name_transporter = forms.ModelChoiceField(label='Choose transporter', required=True, queryset=Transporter.objects.all()) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request def clean(self): super().clean() uploaded = parse_csv(self.request.FILES['file']) In views.py: class ResultFormView(FormView): """ View to show results of comparison between two files. """ template_name = 'tool/upload.html' form_class = CompareFormTransporterCompany success_url = reverse_lazy('tool:result') And my model in models.py if needed: class CheckFile(models.Model): name = models.CharField(max_length=200, blank=True) month = models.DateField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) profile = models.CharField('Choix du profil', blank=False, choices=PROFILE_CHOICES, max_length=100, default="Client") file = models.FileField(blank=True, null=True, upload_to="uploads/", validators=[validate_file_extension]) def __str__(self): return self.name class Meta: verbose_name = "file" verbose_name_plural = "files" I have been trying a lot of different solutions but I don't understand the error. Could you please help me? -
Initialize different field with different parameter in serializer depending on passed variable
I am trying to initialize different field (object with different parameter) by specifying proper parameter and pass it to serializer somehow. Here's what I mean: class ImageSerializer(FlexFieldsModelSerializer): image = VersatileImageFieldSerializer(sizes=custom) class Meta: model = UserImage fields = ['pk', 'image'] In this class I want to pass to the VersatileImageFieldSerializer different sizes (replace 'custom' variable) from the view. I know that I can pass the context and read the value from there, and It works perfectly fine. There is only one problem: I cannot refer to self.context in the moment I define variables. To solve it I tried to override the constructor and create this variable from there. Here is how I did it: def __init__(self, *args, **kwargs): self.image = VersatileImageFieldSerializer(sizes=self.context.get('custom')) super(ImageSerializer, self).__init__(*args, **kwargs) With this approach I got error 'ImageSerializer' object has no attribute 'parent' and I coulnd't find a solution for this, so I tried to implement SerializerMethodField and return this type of object like this: image = serializers.SerializerMethodField() def get_image(self, obj): return VersatileImageFieldSerializer(sizes=self.context.get('custom')) but VersatileImageFieldSerializer is not serializable. I ran out of ideas and solutions and also slowly running out of time. Is there any way I could achieve my goal? -
Integrity error (FOREIGN KEY constraint field) raised when I try to save request.POST from a model form
I am working on a commerce app, (with django but very new to it) where a user can create a listing through a ModelForm called ListingForm that inherits from a Model called Listing.Here is the code for the the Listing model and ListingForm: from django.contrib.auth.models import AbstractUser from django.db import models class Listing(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] import datetime title = models.CharField(max_length= 64) date_made = models.DateField(default= datetime.date.today()) description = models.TextField() user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE, related_name='user_listings', null=True) starting_bid = models.DecimalField(decimal_places=2, max_digits=264, default=10.00) image_url = models.CharField(blank=True, max_length=1000) category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='name', related_name='category_listings', default=NAME_CHOICES[4][0]) listing_category = models.CharField(max_length=12, choices=NAME_CHOICES, null=True, default=NAME_CHOICES[4][0]) is_active = models.BooleanField(default=True) def __str__(self): return f'{self.title}' Here is the code for the ```ListingForm``: from .models import Listing from django.forms import ModelForm class ListingForm(ModelForm): class Meta: model = Listing exclude = [ 'date_made', 'user', 'category', 'is_active', ] The Listingmodel also has foreignkeys to and within the models User,Category and Bid. Here is the code for these models(same imports as those shown for Listing model): class User(AbstractUser): def __str__(self): return f'{self.username} ' class Category(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] name = models.CharField(max_length=12, choices= NAME_CHOICES, unique=True) def __str__(self): … -
Django - Adding a primary key to an existing model with data
This is the existing model in a djnago app: class Task_Master_Data(models.Model): project_id = models.ForeignKey(Project_Master_Data, on_delete=models.CASCADE) task_created_at = models.DateTimeField(auto_now_add=True) task_updated_at = models.DateTimeField(auto_now=True) task_name = models.CharField(max_length=200, null=True) I want to add a new field (which will be a primary key): task_id = models.AutoField(primary_key=True, null=False) When I am making migrations from the terminal, it will provide me with the option of adding a default value, but it will, understandably, bring an error of: UNIQUE constraint failed: new__main_task_master_data.task_id What would be the best way forward for this kind of a scenario without having to delete all the data. -
Django. Object of type Url is not JSON serializable
I am writing parser for website. I have 2 models: Url (id and site url) and News (all the data that will be parsed) I made a form which allows users to eneter the link of website which is automatically saved in db. And also I have a signal which starts to parse data as soon as an Url instanced is saved. But the point is that when I call the function hackernews_rss which parses the data I Get an error kombu.exceptions.EncodeError: Object of type Url is not JSON serializable I don't know how to fix it as in order to save all the parsing result a need to have a Url instance because I have OneToManeRelation models: class Url(models.Model): link = models.CharField( max_length=200, blank=True ) def get_absolute_url(self): return f'/parser/search/' class News(models.Model): domain = models.CharField(max_length=200) link_id = models.ForeignKey(Url, on_delete=models.CASCADE) link = models.CharField(max_length=200, blank=True) create_date = models.DateTimeField() update_date = models.DateTimeField() country = models.CharField(max_length=200, null=True) is_dead = models.BooleanField() a = models.CharField(max_length=200, null=True) ns = models.CharField(max_length=200, null=True) cname = models.CharField(max_length=200, null=True) mx = models.CharField(max_length=200, null=True) txt = models.CharField(max_length=200, null=True) tasks: @shared_task(serializer='json') def save_function(article_list): print('starting') new_count = 0 for article in article_list: try: print(article['link_id']) News.objects.create( link=article['link'], domain=article['domain'], create_date=article['create_date'], update_date=article['update_date'], country=article['country'], is_dead=article['is_dead'], a=article['a'], ns=article['ns'], cname=article['cname'], …