Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF token is null in debug mode - Django 1.6
Note: this is for Django 1.6 I'm trying to figure out why CSRF tokens don't generate in on our site when the Django DEBUG setting is set to true. Some background: the way CSRF tokens are not done the way as suggested on the Django documentation (however, I have tried that as well). They are done as follows, inside of the init function of the form: from django.middleware import csrf self.fields['csrfmiddlewaretoken'].initial = csrf.get_token(self.request) After stepping through the order of execution, I have found that When DEBUG is True: this initialisation happens before the csrf middleware runs. In this scenario, when the above code runs, csrf.get_token(self.request) returns None. when DEBUG is False: this initialisation happens after the csrf middleware runs. In this scenario, when the above code runs, csrf.get_token(self.request) returns the correct CSRF token. I have also tried removing the above way of adding in the csrf token, and instead doing it the way Django requests, i.e. by adding {% csrf_token %} into the form, however this does not either. What could be the issue here? What determines the order in which the middleware runs compared to the initialisation of the application itself? Feel free to ask for more info. -
how to fix django Model instance
error messages ValueError: Cannot assign "<User: user0@example.com>": "Diagnoses.owner" must be a "Patient" instance i get the above error when i try to create either a new card or diagnoses. Models.py class Patient(models.Model): name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) state = models.CharField(max_length=255, null=True) phone = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, null=True) card_number = models.CharField(max_length=255, null=True) owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return (self.patient.name)+"'s card" class Diagnoses(models.Model): sickness = models.CharField(max_length=255, null=True) note = models.TextField(max_length=255, null=True) owner = models.ForeignKey(Patient, null=True, on_delete=models.SET_NULL) def __str__(self): return (self.patient.name)+"'s diagnoses" -
ValueError at /add_coupon/ Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/checkout/">"
i want to add coupon but when i enter wrong code it shows that error don't throw the expect part ValueError at /add_coupon/ Cannot assign "<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/checkout/">": "Order.coupon" must be a "Coupon" instance. views def get_coupon(request, code): try: coupon = Coupon.objects.get(code=code) return coupon except ObjectDoesNotExist: messages.info(request, "This coupon does not exist") return redirect("core:checkout") class AddCouponView(View): def post(self, *args, **kwargs): form = CouponForm(self.request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = Order.objects.get( user=self.request.user, ordered=False) order.coupon = get_coupon(self.request, code) order.save() messages.success(self.request, "Successfully added coupon") return redirect("core:checkout") except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") models class Coupon(models.Model): code = models.CharField(max_length=15) amount = models.FloatField() def __str__(self): return self.code -
Django - ValueError when trying to update a model object
I am working on a Django program for a class. I know the error has to do with foreign key assignment but I cannot understand where my flaw in logic is. Here are the two pertinent models: class listing(models.Model): title = models.CharField(max_length=100) description = models.TextField() url = models.URLField(default="", null=True, max_length=100) category = models.CharField(default="", max_length=50) user_name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) min_bid = models.DecimalField(max_digits=8, decimal_places=2) class watchlist(models.Model): item_id = models.IntegerField(null=False) user_id = models.IntegerField(null=False) #item_id = models.ForeignKey("auctions.listing", on_delete=models.CASCADE, related_name="item_watchlist") #user_id = models.ForeignKey("auctions.User", on_delete=models.CASCADE, related_name="user_watchlist") The last two lines in the watchlist class were commented out, allowing the code to work. However, I would like to understand how to make this work as I originally intended. Which is as follows: (the below code fails at the object create section, with a ValueError, cannot assign : item_id must be an instance of listings.) @login_required def item_listing(request, id): itemID = id # GET call coming in from clicking a title link if request.method == "GET": item = listing.objects.filter(id=id) # Check if the item is on the user's watchlist if watchlist.objects.filter(item_id=id, user_id=request.user.id).exists(): watch = True else: watch = False return render(request, "auctions/ItemPage.html", { "item": item, "name": item[0].title, "url": item[0].url, "description": item[0].description, "user_name": item[0].user_name, … -
Trouble raising ValidationError when using Form.add_error()
As a form is passed data, I'm testing for a ValidationError when the Form.clean() method is invoked. The clean() method evaluates a conditional to see if two fields have the same value. If evaluated to true, I want to invoke Form.add_error() and add a Validation Error to one of the fields. As it stands now, the test does not pass and I'm getting this error: AssertionError: ValidationError not raised I'm not clear on what needs to be refactored in order for the test to pass and a Validation Error to be raised? forms.py from django import forms from django.core.exceptions import ValidationError from .validators import validate_name class NewUserForm(forms.Form): email = forms.EmailField() password = forms.CharField(min_length=6) last_name = forms.CharField( max_length=20, error_messages={'required': "You must provide your last name"}, validators=[validate_name] ) first_name = forms.CharField( max_length=20, error_messages={'required': "You must provide your first name"}, validators=[validate_name] ) reminders = forms.BooleanField(required=True) def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email", None) password = cleaned_data.get('password', None) if email == password: msg = "The password provided cannot be the same as your email" self.add_error('password', ValidationError(msg)) test_forms.py from django.test import TestCase from django.core.exceptions import ValidationError from ..forms import NewUserForm class TestNewUserPassword(TestCase): @classmethod def setUpTestData(cls): user_data = { "email": "user@email.com", "password": "user@email.com", "first_name": "firstName", … -
Django best practices - ensuring atomicity while executing business logic
I am refactoring some legacy code on a Python/Django application and I'm looking for a styling/best practices recommendation about performing actions on a SQL Database. Right now I am trying to rework the following code: def fun(): try: with transaction.atomic(): # query DB # do business logic # update DB entries with new values except: # handle exception The thing is, there is a fair amount of business logic between my query and my update. However I feel like it doesn't make sense to throw additional code under another indentation/i.e defining as part of a DB transaction. Ideally I'd like to clean this up and only perform certain things as atomic. I suppose it wouldn't actually cut down on my lines of code, but I'm curious what transaction.atomic() is actually accomplishing? From my understanding of atomicity, reads don't actually affect the state of a datastore, so I'm not entirely sure the initial read belongs under the atomic() anyway. thanks in advance. -
Porgress bar/loading icon while running python scrip for Django project
I have a django project where I am running a python script to process some data and then present the result. That part is not an issue and work perfectly. However, I am wondering how I can show a progress bar or something like that while the script runs. I can most likely render an intermediate page with that bar but even still how will I continuously update the progress? Just looking for information about the concept. Do I have to have an intermediate page or do I have to use a responsive front end such as Vue? -
Changed from 3 different settings files (base, dev, prod) to 1 settings.py file, and now templates are not recognized?
Trying to use django-dotenv, I went from 3 different files for settings to 1: settings.py. However, server runs but templates are not recognized, why? settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import dotenv import sys import os from decouple import config dotenv.read_dotenv() PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) #SECRET_KEY = config('SECRET_KEY') SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') from dj_database_url import parse as dburl default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'home', 'search', 'flex', 'streams', 'menus', 'site_settings', 'subscribers', 'blog', 'doctrina', 'storages', 'registration', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'crispy_forms' ] SITE_ID = 1 #django-allauth setting MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), … -
Can't set up virtual environment or see if Anaconda is installed, can't access bash folder, 'command not found'
I'm just starting out learning web programming and am trying to set up a virtual environment in atom. I am on a mac. the terminal window doesn't seem to be able to access my bin or bash folder anymore, I'm not sure. In the terminal window I am typing 'conda --version' to determine which version of Anaconda I have installed but I get the message "-bash: conda: command not found" - Also when I am in Atom, and am using the python text editor and I'm trying to create a virtual environment, I type 'sudo conda create --name myDjangoEnv django' and I get the same message, 'sudo: conda: command not found'. I used sudo because otherwise it would not let me set up a virtual environment. I thought I had to enter a password to set up a virtual environment on a mac, and it worked yesterday. I think I edited the bash profile when I set up the virtual environment. I was able to do all of this yesterday, when I typed 'conda --version' in my terminal I got the version of anaconda I installed, and I was able to update the version of anaconda. And in the python … -
How should Structure of url in Django? Css not working on some url
When I want to make a blog / slug page, css doesn't work in Django. Simple structure is working. What can i do? url.py url(r'^(?P<cats>[\w-]+)/$', category_detail, name='cats'), #css is working url(r'^blog/(?P<slug>[\w-]+)/$', blog_detail , name= 'detay'),#css is not working ] urlpatterns += static(settings.STATIC_URL,document_root = settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') -
django.utils.datastructures.MultiValueDictKeyError: 'email'
I am trying to make a simple login form and this is the error it is popping every time I try to run the code. views.py function def login2(request): email1 = request.POST.get('email1') password1 = request.POST.get('password1') if email1 is "tuhin" & password1 is "tuhin": return render(request, 'welcome.html') else: messages.info(request, "Wrong credentials") return render(request, 'login2.html') login2.html code <html> <head> <title> </title> </head> <body> <form method="post" action="login2"> <input type="text" placeholder="Enter your email" name="email2"> <input type="password" placeholder="Enter your password" name="password2"> <input type="submit" value="Login"> {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} </form> </body> </html> Error in the brwser is attached in the picture.[enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/a3JfN.png [2]: https://i.stack.imgur.com/fB96x.png -
Prevent over-written converted plot images or Seperate two images in Django template
With the code, given below, I get two images but they seem also written on the top of each other. I don't know how to prevent this behavior, because I don't know how this bytecode conversion works with buffers in python. in the view in view: def data_stats(request): cate_table_name_and_num_prj= list( Category.objects.filter(project__is_mini=False).annotate(num_prjs=Count('project')).values_list('name', 'num_prjs') ) cate_table_name_and_num_ski= list( Category.objects.annotate(num_prjs=Count('project')).values_list('name', 'num_prjs') ) prj_wedge_sizes=[row[1] for row in cate_table_name_and_num_prj] ski_wedge_sizes=[row[1] for row in cate_table_name_and_num_ski] def func(pct, allvalues): absolute = int(pct / 100.*np.sum(allvalues)) return "{:.1f}%".format(pct, absolute) pie_fig_cate_by_skis = plt.pie( x=ski_wedge_sizes, autopct=lambda pct: func(pct, ski_wedge_sizes), labels=[row[0] for row in cate_table_name_and_num_ski], ) fig_ski = plt.gcf() buf_ski = io.BytesIO() fig_ski.savefig(buf_ski, format = 'png') buf_ski.seek(0) string_ski = base64.b64encode(buf_ski.read()) uri_ski = urllib.parse.quote(string_ski) pie_fig_obj_cate_by_prjs = plt.pie( x=prj_wedge_sizes, autopct=lambda pct: func(pct, prj_wedge_sizes), labels=[row[0] for row in cate_table_name_and_num_prj], ) fig_prj = plt.gcf() buf_prj = io.BytesIO() fig_prj.savefig(buf_prj, format = 'png') buf_prj.seek(0) string_prj = base64.b64encode(buf_prj.read()) uri_prj = urllib.parse.quote(string_prj) return render(request, 'data_stats.html', { 'uri_ski':uri_ski, 'uri_prj':uri_prj, }) the snippets from the template: <img src = "data:image/png;base64,{{ uri_prj }}"> <img src = "data:image/png;base64,{{ uri_ski }}"> screen-shots of the two browser-displayed images: -
django model relationship with rest api
Description the hospital is the user, a patient belongs to an hospital and a patient as an object has a card and diagnoses. I dont know whats wrong maybe its the relationship, i dont known. i need help Error message TypeError at /patient/diagnoses Got a TypeError when calling Diagnoses.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Diagnoses.objects.create(). You may need to make the field read-only, or override the PatientsDiagnosesSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/rest_framework/serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "/usr/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.8/site-packages/django/db/models/query.py", line 431, in create obj = self.model(**kwargs) File "/usr/lib/python3.8/site-packages/django/db/models/base.py", line 500, in init raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Diagnoses() got an unexpected keyword argument 'owner' urls.py of patient app urlpatterns = [ path('', views.PatientListAPIView.as_view(), name="patient"), path('<int:id>', views.PatientDetailAPIView.as_view(), name="patient"), path('card', views.PatientCardListAPIView.as_view(), name="card"), path('card/<int:id>', views.PatientCardDetailAPIView.as_view(), name="card"), path('diagnoses', views.PatientDiagnosesListAPIView.as_view(), name="diagnoses"), path('diagnoses/<int:id>', views.PatientDiagnosesDetailAPIView.as_view(), name="diagnoses") ] serializers.py from rest_framework import serializers from .models import Patient, Card, Diagnoses class PatientsSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = ['id', 'name', 'phone', 'email', 'state','country'] class … -
Pass crispy-form in ajax post request
I'm trying to pass crispy form in through ajax POST request in JS within the HTML page. $.ajax({ type: "POST", url: "confirmed", data: {form : {{form}}, accessCode : '{{code}}' }, csrfmiddlewaretoken: '{{ csrf_token }}', success: function (data) { } }); whenever this function is triggered. I get 'Uncaught SyntaxError: Invalid or unexpected token'. The source looks like this ... $.ajax({ type: "POST", url: "confirmed", data: {form : '<tr><th><label for="id_submit_name">Requested For:</label></th><td><input type="text" name="submit_name" value="sa" class="textinput textInput form-control" id="id_submit_name"></td></tr> <tr><th><label for="id_email">Email:</label> ... I'm guessing it becomes multi-line, which causes the issue. I have also tried to pass it direct, instead of string which gives "Uncaught SyntaxError: Unexpected token '<' " error (as the form start with table row element) Ps. I'm new to web-development, feel free to correct me if i'm doing anything wrong. -
S3 media files for my django-heroku app are not displaying in the browser, but S3 static files are
I currently have a website (Django app) deployed on Heroku. On the site have static file images displayed, as well as user uploaded media file images. I am using AWS S3 to store and serve my static and media files. When I visit my website, the static file images are always shown. However the media files are not displayed. Instead if I click on the blank icon where the media file image is supposed to be, I receive the Privacy Error message below. If I tell the browser to proceed anyways, then it will show the media file image. What I am confused by is why the static images are shown (without a warning) but not the media images? In my S3 bucket I have both a static folder and a media folder. The static folder holds the css, js and images that I used to construct my website. The media folder only holds files that are user uploaded. I suspect this is happening because I have no SSL set up for my website yet. However it confuses me why certain files in my bucket are shown, while others are hidden because they are not secure. All of these files … -
Django switch from sqlite to postgres error
(virtual) user@user-HP-Pavilion-dv6-Notebook-PC:~/user/hobby$ python manage.py runserver (virtual) user@user-HP-Pavilion-dv6-Notebook-PC:~/user/hobby$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 06, 2020 - 23:05:26 Django version 3.0.9, using settings 'hobby.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/home/user/user/virtual/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "shop_product" does not exist LINE 1: ...hop_product"."price", "shop_product"."image" FROM "shop_prod... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/user/hobby/shop/views.py", line 14, in home_view return render(request, "product_detail.html", context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, … -
I can't see the version of python in cmd
When i type 'python −−version' on CMD; it does not show me the version of python i am using instead it displays:python: can't open file 'ΓêÆΓêÆversion': [Errno 2] No such file or directory -
django-dotenv tries reading .env from project folder before root?
I'm chaching my settings to use django-dotenv. I've manage to have my site running again, but seeing this warning: $ python manage.py runserver D:\web_proyects\ministerios_elim\mysite\settings.py:19: UserWarning: Not reading D:\web_proyects\ministerios_elim\mysite\.env - it doesn't exist. Why does it try to read from mysite (name of project)? manage.py: #!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": dotenv.read_dotenv(override=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) wsig.py: import os import dotenv from django.core.wsgi import get_wsgi_application dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() -
Django Rest Framework Nonetype object has no attribute user while calling authenticate
I am working on a custom ObtainAuthTokenView which is as follows: class ObtainAuthTokenView(APIView): throttle_classes = () permission_classes = () parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) renderer_classes = (renderers.JSONRenderer,) def post(self, request): serializer = serializers.AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) content = { 'token': unicode(token.key), } return Response(content) Serializer Class from rest_framework.authentication import authenticate class AuthCustomTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): email_or_username = attrs.get('username') password = attrs.get('password') if email_or_username and password: # Check if user sent email user_request = get_object_or_404( User, email=email_or_username, ) email_or_username = user_request.username user = authenticate(username=email_or_username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) else: msg = _('Must include "email or username" and "password"') raise exceptions.ValidationError(msg) attrs['user'] = user return attrs When authenticate function in the serializer is called it shows the following error: 'NoneType' object has no attribute 'user' Stuck here since a while Any help would be appreciated -
Django prompt the user for login in class based view
I have a class based view which lets a user to add a product to the cart, but the user should be logged in. I have used LoginRequiredMixin to restrict the access to AddToCart CBV, but the product page can be viewed by everyone. I would like to prompt the user asking them to login in whenever they click Add To Cart button and when they are logged in then only they can add product to their respective cart. class AddToCart(LoginRequiredMixin, TemplateView): """ Add an item to the cart """ def get(self, *args, **kwargs): slug = self.kwargs['slug'] print(slug) item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=self.request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) print(order_qs) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug): pass # message : Item already in cart else: order.items.add(order_item) # message : Item was added to cart return redirect("products:product") else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) # message : Item was added to cart return redirect("products:product") A possible solution; I can remove LoginRequiredMixin and check for request.user and if it says AnonymousUser I can return a message via Django Message Framework and display the message to user. But this doesn't sound like a good solution. … -
Get "this field is required" in django-auth-registration
What I want to do Make a user to register to django Authentication Version django : 3.1 djangorestframework:3.11.1 python : 3.7.6 django-allauth : 0.42.0 django-rest-auth : 0.9.5 Situation I entered a registration page that django provides by accessing to localhost:8000/rest-auth/registration/. In order to register to the site, I entered username, password1 and password2 in fields. However, every time I sent POST request, I got an error and that says it below. { "password1": [ "This field is required" ], "password2": [ "This field is required" ] } I absolutely typed exact same passwords in these fields. And, I do really not know why I get this error although I surely entered passwords. How could I fix it out? I would like you to teach me how to do that. Thank you very much. -
How to serialize correctly? Ajax updates all instances of a django upvote button in a object forloop when pressed
OK so I have an index page with items that can be up or downvoted. The issue is that when I upvote/downvote one item, all items on the page are upvoted/downvoted and the appearance of all buttons on the page all change instead of just the one object that was upvoted/downvoted. Can anyone help me serialize each for loop object correctly? my index page: {% for post in posts %} <span id="post_{{forloop.counter}}" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes_{{forloop.counter}}">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> {% endfor %} ... <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ {% for post in posts %} $('.vote_action').click(function(e) { var postid = document.getElementById('post_{{forloop.counter}}').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" %}', data: { postid: postid, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'postvote', button: button, }, success: function(json){ if (json.length < 1 || json == undefined) { //empty } document.getElementById("votes_{{forloop.counter}}").innerHTML = json['result'] //change button looks $("#uvb_{{forloop.counter}}").addClass("disabled"); $("#dvb_{{forloop.counter}}").addClass("disabled"); }, error: function(xhr, errmsg, err) {} }) }) {% endfor %} }) </script> My views function: @login_required def post_vote(request): if request.POST.get('action') == 'postvote': # get information from request about what item id it is id = int(request.POST.get('postid')) # And also which button … -
Heroku application error: unicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I am trying to deploy my Django app on Heroku however, whenever I go to my app I am getting an error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> I have now two settings file so in my projects folder which contains the wsgi.py I have a a folder called settings which is: settings --common.py --development.py --productions.py In my production.py I have: from register.settings.common import * import os import django_heroku DEBUG = False ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1','appname.heroku.com'] SECRET_KEY = os.environ.get('SECRET_KEY') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) And in my wsgi.py and manage.py I have: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'register.settings.production') Now I have added the Postgres add-on from the dashboard and can check that I also have it using the Heroku CLI . I have also added a custom domain name of www.myapp.com as well which I do not know if this is causing the issue. For pushing to master i did: heroku config:set DISABLE_COLLECTSTATIC=1 and then: git push heroku master What is causing this issue? When I do python manage.py run server I also get the error: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django DateField not saving the selected date from picker
I have a django model with some models.DateField and a default value. The forms.py looks like this: class DateInput(forms.DateInput): input_type = 'date' class AddNewCar(forms.ModelForm): image = forms.ImageField(label ="Imagine Masina", required=False) vigneta = forms.DateField(label ="Valabilitate Rovinieta", widget=DateInput()) class Meta: model = Car fields = ('image',) The models.py class Car(models.Model): owner = models.ForeignKey(Users, null = True, on_delete = models.CASCADE) vigneta = models.DateField(default=datetime.date.today, blank = False) And in views.py def post(self, request, *args, **kwargs): form = AddNewCar(request.POST) if form.is_valid(): m = form.save() m.owner = request.user m.save() return redirect("home") The problem is when I submit the form, don't give any errors but the date that's saved is not the selected one, is the default date. -
Django Serializer defining initial object
I can't seem to figure out how to pass in an initial value to a serializer. I have a multitenant django site and I am trying to now get APIs setup. The client field exists but needs to be hidden and read only. I thought this worked like a form and a view in traditional django. I would normally pass in the get_initial in the view. I tried that first but it doesn't work. I think I need to get the value directly in the serializer but I can't seem to get it to work. model: class Location(ClientAwareModel): client = models.ForeignKey(Client, on_delete=models.PROTECT) name = models.CharField(max_length=64, blank=True) address = models.CharField(max_length=64) address2 = models.CharField(max_length=64, blank=True) city = models.CharField(max_length=64) state = USStateField() zip_code = USZipCodeField() serializer (you can see all my failed attempts commented out: class LocationSerializer(serializers.ModelSerializer): def get_client(self, obj): # return client_from_request(self.request) return client_from_request(self.context['request']) # client = serializers.SerializerMethodField('get_client') # client = serializers.SerializerMethodField() # client = serializers.Field(source='get_client', read_only=True) # client = serializers.ReadOnlyField(source='get_client') # client = serializers.PrimaryKeyRelatedField(read_only=True, default='get_client') client = serializers.PrimaryKeyRelatedField(read_only=True, source='get_client') # client = serializers.HiddenField(default=get_client(self)) class Meta: model = Location fields = ['name', 'address', 'address2', 'city', 'state', 'zip_code', 'client'] viewset: class LocationViewSet(viewsets.ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): …