Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please enter a valid date/time django error
i suddenly got an error. Please enter a valid date/time. It used to work just fine but I don't know what's going on now LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = False USE_TZ = False DATE_INPUT_FORMATS = ['%d-%m-%Y %H:%M'] class JobForm(forms.ModelForm): class Meta: model = ShiftPlace fields = ['add','medewerker','job_type','firmaName','date','dateTo','adress','postcode','HouseNumber','city','comment'] widgets = { 'date': DateTimePickerInput(), 'dateTo': DateTimePickerInput(), 'comment':forms.Textarea, class DateTimePickerInput(forms.DateTimeInput): input_type = 'datetime-local' date_format=['%d-%m-%Y %H:%M'] -
Django localization - translating models cross apps
I'm translating model choices in a django APP but the local APPs do not use the localized string. I have an APP named base_app with the following model: class User(AbstractUser): LIVING_AREA_CHOICES = ( ('urban', _('Urban')), ('rural', _('Rural')), ) name = models.CharField( _('Option Name'), null=True, max_length=255, blank=True ) def __str__(self): return self.name or '' living_area = models.CharField( _('Living Area'), choices=LIVING_AREA_CHOICES, max_length=255, null=True, blank=True ) ... other stuff... This model is used in a modelform of forms.py from courses_app (added as external app through requirements.txt of base_app): model = get_user_model() fields = ('username', 'email', 'name', 'first_name', 'last_name', 'image', 'occupation', 'city', 'site', 'biography', 'phone_number','social_facebook', 'social_twitter', 'social_instagram', 'preferred_language', 'neighborhood', 'living_area', 'race', 'birth_date','city', 'gender') and rendered in profile-edit.html, template of a third app (client_app configured in .env): {% with errors=form.living_area.errors %} <div class="form-group{{ errors|yesno:" has-error,"}}"> <label class="col-xs-12 col-sm-3 col-lg-2 control-label" translate>Living area </label> <div class="col-xs-12 col-sm-9 col-lg-10"> {{ form.living_area }} {% for error in errors %}<small class="warning-mark">{{error}}</small>{% endfor %} </div> </div> {% endwith %} I've already tried to use localized_fields = ('living_area',) in forms.py with no success. The only way I've got it working is adding the strings of LIVING_AREA_CHOICES inside client_app's po/mo files. Is there a way for the client_app template to retrieve the … -
How do I create a unique number for Django model objects?
I am working on a project where a user can create a card under their company. Unfortunately, the databases indexes all the cards, regardless of the company. I would like to create a unique number for all the cards but serialised according to the company, e.g like creating an invoice number that will always be unique. The two models are here: class Company(Organization): name = models.Charfield(max_length=256, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(null=True) date_created = models.DateField(default=timezone.now, null=True) class Card (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='card_user', null=True) thecompany = models.ForeignKey(Company, related_name = "company_card", on_delete=models.CASCADE, null=True) date_created = models.DateField(default=timezone.now) card_number = models.PositiveIntegerField(default=1, null=True, editable=False) def save(self, *args, **kwargs): if self.card_number == 1: try: last = Card.objects.filter(thecompany=self.thecompany).latest('card_number') self.card_number = last.card_number + 1 except: self.card_number = 1 super(Card, self).save(*args, **kwargs) I can sequence the objects created according to the company, using the card_number field on Card. Below is the model: The save method works well and maintains Card_Number sequence even when you delete cards, up until you delete the card object with the largest number. Then if you create a card object after you have deleted the card with the largest card_number, it repeats. I thought of creating a list with … -
How to hit a json database index in Django query?
I created an index on a models.JSONField in my postgres db. class Meta: indexes=[ models.Index(KeyTextTransform('id', 'my_json_field'), name='my_json_id_idx') ] i wrote some sql on pg_indexes to verify and it is there CREATE INDEX my_json_id_idx on my_model USING btree (((my_json_field ->> 'id'::text))) One thing to note is it uses ->> which means it casts to text im pretty sure. So then if i try to query like this my_query = MyModel.objects.filter(my_json_field__id=1234) If i analyze with my_query.explain(analyze=True) it shows a sequential Scan. It does NOT hit my index at all. When i look at the SQL of the query i think im noticing the difference is it uses Filter: (my_model.my_json_field -> 'id'::text) = '1234'::jsonb Or if i just look at the SQL of the query it basically is: select * from my_model where (my_json_field -> id) = 1234 I think the -> in the query vs --> in the index is what makes the discrepancy. What is the proper way to write the query so it hits the index, or should i rewrite the index so it uses -> ? Does anyone know how to rewrite the statement in the indexes so that it creates it with -> ? P.S I can write … -
How to use sync_to_async() in Django template?
I am trying to make the Django tutorial codes polls into async with uvicorn async view. ORM query works with async view by wrapping in sync_to_async() as such. question = await sync_to_async(Question.objects.get, thread_sensitive=True)(pk=question_id) But I have no idea how to apply sync_to_async or thread inside Django templates. This code fails saying 'You cannot call this from an async context - use a thread or sync_to_async.' Or any other way to work around this? {% for choice in question.choice_set.all %} I use Python 3.10, Django 4.0.4 and uvicorn 0.17.6 -
Django runserver not worked after login
I used this command: python manage.py runserver 0:8080 After I logined the system I can reach rest API pages, but can't reach other pages. Although I send a request, the command output does not log. Quit the server with CONTROL-C. -
Django and Celery: unable to pickle task kombu.exceptions.EncodeError
I have this async Celery task recalculate_emissions_task.delay(assessment, answers,reseller, user) where the parameters supplied are all Django objects, my task function is defined like this @app.task @transaction.atomic def recalculate_emissions_task(assessment, answers, reseller, requesting_user=None): for ans in answers: approver = None if ans.is_approved: approver = ans.approver auto_approved = ans.auto_approved auto_approval_notes = ans.auto_approval_notes ans.unapprove() ans.report_upstream_emissions = ans.scope in assessment.scopes_for_upstream ans.report_transmission_and_distribution = assessment.report_transmission_and_distribution ans.for_mbi_assessment = assessment.uses_mbi if approver: ans.approve( approver, auto_approved=auto_approved, auto_approval_notes=auto_approval_notes ) else: ans.save() and the error I am receiving is : Traceback (most recent call last): File "dir/bin/django-python.py", line 18, in <module> runpy.run_path(path, run_name='__main__') File "/usr/lib/python3.8/runpy.py", line 265, in run_path return _run_module_code(code, init_globals, run_name, File "/usr/lib/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "test.py", line 15, in <module> recalculate_emissions_task.delay(assessment, answers,reseller, user) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 427, in delay return self.apply_async(args, kwargs) File "dir/lib/python3.8/site-packages/celery/app/task.py", line 566, in apply_async return app.send_task( File "dir/lib/python3.8/site-packages/celery/app/base.py", line 756, in send_task amqp.send_task_message(P, name, message, **options) File "dir/lib/python3.8/site-packages/celery/app/amqp.py", line 543, in send_task_message ret = producer.publish( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 167, in publish body, content_type, content_encoding = self._prepare( File "dir/lib/python3.8/site-packages/kombu/messaging.py", line 252, in _prepare body) = dumps(body, serializer=serializer) File "dir/lib/python3.8/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/usr/lib/python3.8/contextlib.py", line 131, in __exit__ self.gen.throw(type, … -
HttpResponse object. It returned None instead
The view main.views.add_venue didn't return an HttpResponse object. It returned None instead. -- Value Error error error appeared after creating views.py views.py def add_venue(request): if request.method == "POST": form = VenueForm(request.POST) if form.is_valid(): form.save() return redirect('/add_venue?submitted=True') else: form = VenueForm() if 'submitted' in request.GET: submitted = True else: return HttpResponseRedirect('/add_venue?submitted=True') return render(request, 'main/add_venue.html', {'form': form, 'submitted':submitted}) models.py, HTML, admin.py and forms.py works correctly. If I delete return HttpResponseRedirect(/add_venue?submitted=True) error won't (when going to the page) appear until I fill out the form -
zappa : Failed to manage IAM roles
Im trying to deploy a django app with zappa. I have set the region and everything in the zappa init. Now when i try to do zappa deploy I have this error: "Error: Failed to manage IAM roles!" Exception reported by AWS:An error occurred (InvalidClientTokenId) when calling the CreateRole operation: The security token included in the request is invalid. I've created a user under Iam in aws console and I have attached IAMFullAccess and PowerUserAccess Iam predefined policies/strategies. I dont know what to do Thank you Best, -
ImportError: cannot import name 'FieldDoesNotExist' from 'django.db.models.fields'
Can anyone please help me? I am getting this error from a week. I really need HELP THE Django Server is not working and i am getting this error when I enter Previously i was using python another version and now I installed python v10 so what should i do now? py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management_init_.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\ateyu\AppData\Local\Programs\Python\Python310\lib\site-packages\django_filters_init_.py", line 7, in from .filterset import FilterSet … -
I'm getting a TemplateSyntaxError in my local django server at my template html file regarding the block tag that I used
"Invalid block tag on line 2: 'endblock'. Did you forget to register or load this tag?" This is the error I'm getting and the following is my code in my index.html file in vs code which for some reason keeps getting aligned into one line after saving despite saving each block as a different line after one another: {% extends 'base.html' %} {% block body %} This is body block {% endblock body %} -
Django "NoReverseMatch: Reverse for 'ads.views.AdListView' not found" while doing Test
I implemented some tests to check the status code of some pages, but this one with the reverse function throws me the error: django.urls.exceptions.NoReverseMatch: Reverse for 'ads.views.AdListView' not found. 'ads.views.AdListView' is not a valid view function or pattern name. Reading the documentation and some answers on stackoverflow I'm supposed to use either the view function name or the pattern name inside the parenthesis of the reverse function, but none of them seems to work. Here's my code: ads/tests/test_urls.py from django.test import TestCase from django.urls import reverse class SimpleTests(TestCase): def test_detail_view_url_by_name(self): resp = self.client.get(reverse('ad_detail')) # I've also tried: resp = self.client.get(reverse('ads/ad_detail')) self.assertEqual(resp.status_code, 200) ... ads\urls.py from django.urls import path, reverse_lazy from . import views app_name='ads' urlpatterns = [ path('', views.AdListView.as_view(), name='all'), path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'), ... ] mysite/urls.py from django.urls import path, include urlpatterns = [ path('', include('home.urls')), # Change to ads.urls path('ads/', include('ads.urls')), ... ] ads/views.py class AdDetailView(OwnerDetailView): model = Ad template_name = 'ads/ad_detail.html' def get(self, request, pk) : retrieved_ad = Ad.objects.get(id=pk) comments = Comment.objects.filter(ad=retrieved_ad).order_by('-updated_at') comment_form = CommentForm() context = { 'ad' : retrieved_ad, 'comments': comments, 'comment_form': comment_form } return render(request, self.template_name, context) I'm a newbie with Django, so I don't really understand what's going on. Any idea of what is … -
How to configure a server on raspian with django, apache2, mariasql, vhosts, pipenv
I am trying to set up a webserver, and have made some steps towards setting it up but I have hit a hurdle that maybe some one can help me with. I am getting the following error "This site can't be reached". Checking the connection Checking the proxy and the firewall. I have only done this setup once before and it was ages ago, but have exhausted my documentation at the time that I did it. And any scraps for information would be most helpful. Heres my setup and steps so far, some steps are for later e.g. certbot etc. What I am currently trying to do is show domain.co.uk in the browser after setting the /etc/hosts file. So nothing over the internet for now, just everything on the local machine. Equipment: Raspberry Pi 3 Model B V1.2 16 GB MICRO SD CARD Keyboard Mouse 4K HDMI Monitor Power Cable HDMI Cable WIFI Access Power Supply Software: SD Memory Card Formatter Raspberry Pi OS with desktop (bullseye) MD5 & SHA Checksum Utility Raspberry Pi Imager PassMark ImageUSB Chromium apache2 libapache2-mod-php Process: Download “SD Memory Card Formatter”. Format “16 GB MICRO SD CARD” with “SD Memory Card Formatter”. Download “Raspberry Pi … -
Setting up VS Code for use with Django, Apache, virtualenv on a remote server
we have a django project on a development server which is running within a virtual environment. I was hoping to be able to use VS Code for development from my local PC, but I am not sure if I am able to or not. It seems like something that would make sense to do! I think I have managed to set the interpreter as the virtualenv on the server using UNC paths and have activated it, but when I try to run manage.py to create a new app, I get No module named 'django' which perhaps suggested the virtualenv hasn't activate properly? Is it possible to use VS Code in this way? thanks, Phil -
ajax request in django
My ajax code $.ajax({ type: "get", url: "", statusCode: { 500: function() { alert("error"); }}, data: { "map":JSON.stringify(jsonmap), "road":JSON.stringify(sourceGoal), "line":JSON.stringify(straightLineToDestination) }, success: function(response){ alert("success") } }); my views.py code : import json from telnetlib import STATUS from urllib import request from django.shortcuts import render from django.http import HttpResponse import os from django.views.generic import View from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt,csrf_protect from .algocode import a_star import pprint @csrf_exempt def home_view(request): if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': if request.method == 'Get': straight_line=json.loads(request.Get.get('line')) SourceandGoal=json.loads(request.Get.get('road')) Graph=json.loads(request.Get.get('map')) heuristic, cost, optimal_path = a_star(SourceandGoal["start"], SourceandGoal["end"],Graph,straight_line) result=' -> '.join(city for city in optimal_path) print(result) print(heuristic) print(cost) return JsonResponse({"heuristic":heuristic,"cost":cost,"result":result}) return render(request,'index.html') My URLS.py : urlpatterns = [ path('admin/', admin.site.urls), path('',home_view), ] my problems are : When ajax type was "post" I had a "500 eternal server error" but the data is passed and I can access it and use it as I want in my views.py I changed ajax type to "get " there was no errors put now I get the data in a wrong format and I cant use it in my project "GET /?map=%22%7B%5C%22City1%5C%22%3A%7B%5C%22City2%5C%22%3A123%7D%2C%5C%22City2%5C%22%3A%7B%5C%22City1%5C%22%3A12%7D%7D%22&road=%7B%22start%22%3A%22City1%22%2C%22end%22%3A%22City2%22%7D&line=%7B%22City2%22%3A32%2C%22City1%22%3A222%7D HTTP/1.1" 200 1247 when ajax type was "post" the data I receive comes like this even with the server Erorr : { … -
Django:TypeError: serve() got an unexpected keyword argument 'Document_root'
hello I am facing some issues with my code. this is the error that I am getting TypeError: serve() got an unexpected keyword argument 'Document_root' this is my settings.py STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto- field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' here is my url.py from xml.dom.minidom import Document from django.conf import settings from django.contrib import admin from django.urls import path from django.conf.urls.static import static from customer.views import Index, About, Order urlpatterns = [ path('admin/', admin.site.urls), path('', Index.as_view(), name='index'), path('about/', About.as_view(), name='about'), path('order/', Order.as_view(), name='order'), ] + static(settings.MEDIA_URL, Document_root=settings.MEDIA_ROOT) and here is my Html file <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#submitModal" > Submit Order! </button> <!-- <button class="btn btn-dark mt-5">Place Order!</button> --> <!-- Modal --> <div class="modal fade" id="submitModal" tabindex="-1" role="dialog" aria-labelledby="submitModalLabel" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="submitModalLabel"> Submit Your Order! </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" data-dismiss="modal" > Go Back </button> <button type="submit" class="btn btn-dark">Place Order! </button> </div> </div> </div> </div> </form> What should I do to stop getting this error. I have been struggling from 2 days. and yes the app … -
Django multiple update Task at once
I have my Django website where i can have tasks created and subtasks under tasks i have mark complete option which is working fine i need them to be completed in batch like selecting multiple tasks at once and complete them. serializers.py: class TaskCompleteSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ( 'is_done', ) def update(self, instance, validated_data): person = self.context['request'].user.person task_is_done = validated_data.get('is_done', False) if task_is_done: instance.subtasks.update(is_done=True) instance.is_done = task_is_done instance.done_by.set([person]) instance.save() return instance views.py: class TaskUpdateAPIView(UpdateAPIView): permission_classes = " " serializer_class = TaskCompleteSerializer queryset = Task.objects.all() model = Task lookup_url_kwarg = 'task_id' urls.py path('<int:task_id>/complete/',views.TaskUpdateAPIView.as_view(), name='task_update'), models.py class Task(BaseModel): name = models.CharField(max_length=255) done_by = models.ManyToManyField( User, related_name='tasks_completed', blank=True, ) is_done = models.BooleanField(default=False) class Subtask(models.Model): name = models.CharField(max_length=255) subtask_of = models.ForeignKey( Task, related_name='subtasks', blank=True, null=True, on_delete=models.CASCADE, ) -
Min distance of one point to set of points Django ORM
I am trying to calculate minimum distances of one point to set of points. For example if there are 3 places A, B, C in the set and the wanted place is D, I want min(dist(A, D), dist(B, D), dist(C, D). Here is my place model: class Place(models.Model): latitude = models.FloatField(blank=False) longitude = models.FloatField(blank=False) Here is my query which seems not to work: places_with_distance = Place.objects.annotate( distance=( Subquery(places_set.annotate( distance_to_place_in_set=( Min( (F('latitude') - OuterRef('latitude')) * (F('latitude') - OuterRef('latitude')) + (F('longitude') - OuterRef('longitude')) * (F('longitude') - OuterRef('longitude')) ) ) ).values('distance_to_place_in_set')))).order_by('distance') The problem is that the distance gets calculated only for the first item of the places_set(e.g. only dist(A, D) but not dist(B, D), ...). Thanks! -
Using urls path with slug returns Page not found (404) No profile found matching the query
I'm trying to create user Profile for my django project, I'm using UpdateView to allow user to edit Profile model when they want to create profile for their account but it return an error every time I click on create profile url in the profile template. Profile Template: <div class="container"> <div class="row justify-content-center"> {% for profile in profiles %} <div class="col"> <a href="{{profile.website}}">{{profile.website}}</a> <a href="{{profile.twitter}}">{{profile.website}}</a> </div> {% endfor %} </div> </div> <br> <div class="container"> <div class="row"> <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a> </div> </div> My model: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_image = models.ImageField(upload_to="avatars/") stories = models.TextField(max_length=500,blank=True, null=True) website = models.URLField(max_length=250, blank=True, null=True) twitter = models.URLField(max_length=250, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) slug = models.SlugField(blank=True, null=True) my urls: path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'), my views: @login_required(login_url='login') def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = {'questions':questions, 'profiles':profiles} return render(request, 'profile.html', context) class EditProfileView(UpdateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'edit_profile.html' success_url = reverse_lazy('index') def save(self, *args, **kwargs): self.slug = slugify(self.user) super(Creator, self).save(*args, **kwargs) -
Django filter logic
I am trying to filter based on a parent having assigned user_roles or not and cant quite work out how to achieve the below in the most efficient way. What i need to do is, if the parent has no user_roles assigned then i want all parent objects (essentially ignore the filter). But if it has some user_roles I want to filter based the Child object user_role also being in the Parent user_roles. class UserRole(models.Model): name = charfield() class Parent(models.Model): ... user_roles = m2m(UserRole) ... class Child(models.Model): user_role = FK(UserRole) Something like: filter = Q(Q(parent__user_roles=Child.user_role) | Q(Ignore if parent__user_roles==None)) -
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.CustomUser' that has not been installed I am getting this error .. My settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+k2v!nn#f*qirqz1&4=de+eb&(f0hgvjd2)&^rg3i(w9z2=9dc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'users.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Assign view's method result to view's variable - Django Rest Framework
In the view I've defined method do() which returns list class LessonsViewSet(ModelViewSet): def do(self): lst = [] lessons = self.filter_queryset(self.get_queryset()) for l in lessons: /* do something */ lst.append(l) return lst result_list = do() I want to assign do() method result to result_list variable. Tried different versions but none of them worked. How can I do this? thank you in advance -
get() returned more than one OrderProduct -- it returned 3
My error: MultipleObjectsReturned at /process/ get() returned more than one OrderProduct -- it returned 3! Request Method: POST Request URL: http://127.0.0.1:8000/process/ Django Version: 4.0.4 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one OrderProduct -- it returned 3! Exception Location: C:\Users\User\AppData\Roaming\Python\Python310\site-packages\django\db\models\query.py, line 499, in get Python Executable: C:\Program Files\Python310\python.exe Python Version: 3.10.4 Python Path: ['D:\Online_Shop_Django', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'C:\Users\User\AppData\Roaming\Python\Python310\site-packages', 'C:\Program Files\Python310\lib\site-packages'] Server time: Thu, 26 May 2022 16:57:38 +0500 My views: if not request.user.is_authenticated: session = request.session cart = session.get(settings.CART_SESSION_ID) del session['cart'] else: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) order_product, created = OrderProduct.objects.get_or_create( order=order, ) order.save() messages.success(request, 'Заказ успешно оформлен. Проверьте свою электронную почту!!!') return redirect('product_list') how can I solve that problem? pls help meee -
Django - include another html file from different location
I have two htmls a.html and b.html. a.html is located in the template folder by default. b.html is located in appname/static/images/b.html, because it's a model calculation result in html format. In a.html, I am trying to include b.html but it's not working, unless b.html is in the same template folder. <body> {% include 'appname/static/images/b.html' %} </body> questions: how to include b.html? how to include b.html dynamically if it's in different folder, e.g. images/username/b.html where username is different. -
Changes are not reflecting in django
I am having some issues like I made a site but when ever i upload a new post, post gets uploaded but I it doesn't show in the page. I need to signout and signin again then only it show me that post.Any body can help me with this issue...