Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The context processor that will pass the variable to the template year
I'm trying to write a context processor that will pass a variable year to the template, the value of which will be the current year as a number: © {{ year }} Copyright from datetime import datetime, date def year(request): return { request, datetime.now().date() } -
How to provide data to react with drf without extra requests?
I build a single page application with react and django rest framework. I want to have an ability to change "static" info through django admin interface to avoid unnecessary extra deploy every time. Such info like background image and text from about section. To edit it I create cms django app and register models in admin. To serve frontend in production I use TemplateView from django.views.generic package. It serves html file from bundled react app directory. here's part of root urls.py: urlpatterns = [ path('admin/', admin.site.urls), # ... # api endpoints here # ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] to serve it in development I use react-scripts start from create-react-app How can I pass information like the current url of the background image, text for about section, etc. there? Simple option is to create bunch of views to get this info and request all the data from react app, but I don't really like this approach. another option is to redefine TemplateView like this from django.views import generic class TemplateView(generic.TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context_data = dict() # get all data from db here return context_data But how then I use this in react app? … -
MultipleObjectsReturned at /profile/ get() returned more than one CustomUser -- it returned 2
What I am trying to achieve CustomUser model is storing user account detail. After logging in, the particular user profile must be fetched using the token generated during signup. Issue I have made phone_number as the primary key and unique attribute is set to True. MY code behaves properly when there is only one user but >1 user, data of all existing users are fetched which is why this error is showing up! Here is the model structure class CustomUser(AbstractUser): first_name = models.CharField(null=True, blank=True, max_length= 50) last_name = models.CharField(null=True, blank=True, max_length= 50) username = models.CharField(null=True, blank=True, max_length= 12) phone_number = models.CharField(primary_key=True, max_length= 10,unique=True) dob = models.CharField(max_length=12, null=True, blank=True) email = models.EmailField(null=True, blank=True) address = models.CharField(max_length= 500,null=True, blank=True) pincode = models.CharField(max_length=10, blank=True,null=True) state = models.CharField(max_length= 256,null=True, blank=True) district = models.CharField(max_length= 56,null=True, blank=True) otp_verified = models.BooleanField(null=True,blank=True, default=False) date_joined = models.DateTimeField(null=True,blank=True) last_login = models.DateTimeField(null=True,blank=True) loyality_level = models.IntegerField(null=True,blank=True) loyality_points = models.IntegerField(null=True,blank=True) gender = models.CharField(max_length= 2,null=True, blank=True) user_type = models.CharField(max_length= 2,null=True, blank=True) objects = MyUserManager() search_fields = ("",) USERNAME_FIELD = 'phone_number' def __str__(self): return self.phone_number @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): return str(AccessToken.for_user(self)) Here is my view for fetching Profile using APIView class ProfileView(APIView): authentication_class = [JWTAuthentication] permission_classes = [IsAuthenticated] try: def get(self, request): … -
Reading django_settings from Google Cloud Platform's Secret Manager does not work
When running the command python manage.py makemigrations locally on my laptop, I get the following error on my console: (mywebsite) C:\Users\Sander\PycharmProjects\mywebsite>python manage.py makemigrations Invalid line: echo DATABASE_URL=postgres://myuser:mypassword@//cloudsql/mywebsite:europe-west6:mywebsite-db/mydb > .env Invalid line: echo GS_BUCKET_NAME=mybucket >> .env Invalid line: echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n Note that the echo [... etc. ...] > .env instructions are actually the content of a secret I configured on Google Cloud Platform's Secret Manager, when following Google Cloud Platform's instructions for deploying my Django website on Google Cloud Run. Now I do know these echo [... etc. ...] > .env instructions are supposed to create a file .env with the variables DATABASE_URL, GS_BUCKET_NAME and SECRET_KEY in it, but it doesn't, of course, since it reports the error "Invalid line: ..." instead. I found this StackOverflow answer, stating that these bash instructions (echo [... etc. ...] > .env) simply can't be executed by python and that I can simply execute them locally by running them from a shell script instead, so executing this create-env-file.sh works: DATABASE_URL=postgres://myuser:mypassword@//cloudsql/mywebsite:europe-we st6:mywebsite-db/mydb > .env GS_BUCKET_NAME=mybucket >> .env echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n However, this generates … -
How to add custom field in manytomany through table in Django
I have a model which has manytomany relation with another model. This creates a hidden through table with two foreign key field of previous two tables. Now I want to add custom field in addition to the existing two foreign key field in the through table. Model One: class ModelOne(models.Model): field_one = models.CharField(max_length=264) Model Two: class ModelTwo(models.Model): many_field = models.ManyToManyField(ModelOne, related_name='some_name') field_one = models.CharField(max_length=264) Auto created hidden through table: class appname_modeltwo_modelone(models.Model): model_one_id= models.ForeignKey(ModelOne) model_two_id= models.ForeignKey(ModelTwo) custom_field= models.CharField(max_length=264) # New Custom Field I want to add How can I add new custom field here? -
Not able to run the command "wfastcgi-enable"
So I am trying to deploy a python Django project on windows server 2012R2. But when trying to run the command I get this error. When trying to open the link in IIS manager it show error 500. I am running command prompt as administrator so that did not solve the problem. Python version:3.8.8 IIS 8 If you need to know version of any other library to answer please comment. -
Django Rest Framework. added new list element to request.data, but getting the new element as a double list
I am building a small Django Rest Framework API with APIView. It generates a post with tags which are gotten from the DB, but if there are no tags or I want to add a new tag, a list of tag names is passed into the payload and creates them along the post, then the new tag IDs are added to the request.data['tags']. This is the payload I am passing for new tags: { 'title': 'Test Creating with new tags', 'new_tags': ['newest', 'newer'] } This is the post method: def post(self, request, format=None): """ Creates a Post instance """ if isinstance(request.data, QueryDict): request.data._mutable = True tmp_new_tags = request.data.get('new_tags', None) if tmp_new_tags: new_tags = request.data.pop('new_tags') request.data.update({'tags': []}) for new_tag in new_tags: tag = Tag.objects.create(name=new_tag, user=self.request.user) request.data['tags'].append(str(tag.id)) serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) this is the request.data with existing tags that I am expecting for new tags: <QueryDict: {'title': ['Test Creating'], 'tags': ['1', '2']}> But I got the tags with double [] <QueryDict: {'title': ['Test Creating with new tags'], 'tags': [['3', '4']]}> This is the response.data: {'tags': [ErrorDetail(string="“['3', '4']” is not a valid UUID.", code='invalid')]} How can I append a single List instead of a double … -
Enable post of HTML form to Django database backend
I'm trying to write the code to enable form data to be sent to the backend database. The form is just a few fields, name, website, and portfolio address created in html <div class="card-body"> <form class="needs-validation" form action="/elements/forms/add_investor/" novalidate method="post"> <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom01">Investor Name</label> <input type="text" class="form-control" id="validationCustom01" placeholder="InvestorName" value="MyInvestor" required> <div class="valid-feedback"> Looks good! </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label for="example-url-input" class="form-label">Investor Website</label> <input class="form-control" type="url" value="https://example.com" id="example-url-input" requried> <div class="valid-feedback"> Looks good! </div> <div class="invalid-feedback"> Please provide a valid web address. </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="mb-3"> <label for="example-url-input" class="form-label">Investor Portfolio</label> <input class="form-control" type="url" value="https://example.com/portfolio" id="example-url-input" requried> <div class="invalid-feedback"> Please provide a valid web address. </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="mb-3"> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <div class="card"> <div class="card-header"> <h4 class="card-title">Comments</h4> <p class="card-title-desc">Please add any comments or notes</p> </div> <div class="card-body"> <div id="ckeditor-classic"></div><br> <button class="btn btn-primary" type="submit">Submit form</button> </div> </div> </div> </form> <!-- end col --> </div> I'm struggling to get understand how I map the fields to the database and then get the submit button posted to the database. I've gone through the Django forms section, but can't … -
Clean way to work with Django UpdateView from preventing it to override and do append to existing data?
I have a modelform that I am rendering on the frontend. One of the field is a select2 dropdown and the user selects an option and adds in relevant detail in the other field e.g class MyForm(forms.ModelForm): name = models.ModelChoiceField(queryset=Test.objects.all(),required=False) data = models.CharField(required = False) ..... Now, the url responsible for handling the POST is as follows /example/<str:name/ Here is my issue, I already have existing data value in the DB for a specific name . What I want is that when the user selects a name in the frontend and adds in some value in the data, the data gets appended to the existing value in the db for that name. I am inheriting from UpdateView and so when I do something like this, it simply overrides the existing data. def form_valid(self,form): obj = form.save(commit=False) #here is where I would like to do something with the existing data for that instance obj.save() One approach that I had in my mind, is actually doing something like this in form save() #modelform save() def save(self,commit=True): #do a fetch from the db about the existing data obj = MyModel.objects.get(id=instance.id) self.data = obj.append_data(obj.data,self.data) #can be a model method return super().save(commit) Is this a … -
Filtering between two datetime in django
How to filter out records that lie in between two datetimes inclusively in django? I have an example code below, however it does not return expected results. # based on the Developer's Tool in Chrome, # request.POST['startDate'] == '2021-10-22T16:00:00.000Z' # request.POST['endDate'] == '2021-10-22T16:00:00.000Z' startDate = timezone.now().strptime(request.POST['startDate'], '%Y-%m-%dT%H:%M:%S.%fZ') endDate = timezone.now().strptime(request.POST['endDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=1, microseconds=-1) statistics = models.MemberCard.objects.filter(createDate__gte=startDate, createDate__lte=endDate).order_by("-createDate") if len(statistics) > 0: for item in statistics: dateFound.append(item.createDate) Would like to know any issues with the code above that I have written? or any better solutions for this problem are more than welcomed -
Form is saving multiple instances at once
I am building a simple question answer site and I am trying to build comment system in question's answer. But when I add a comment then comment is saving multiple times, For Example :- There are 5 answers and if i comment on one then same five instances are saving and if a question has 3 answers then 3 same comments are saving. models.py Class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() class Answer(models.Model): answered_by = models.ForeignKey(User, on_delete=models.CASCADE) question_of = models.ForeignKey(Question, on_delete=models.CASCADE) body = models.TextField() class Comment(models.Model): commented_by = models.ForeignKey(User, on_delete=models.CASCADE) commented_on = models.ForeignKey(Answer, on_delete=models.CASCADE) text = models.TextField() views.py def save_comment(request, answer_id): if request.method == 'POST': comment = request.POST['comment'] answer = Answer.objects.get(pk=answer_id) commented_by = request.user if comment != "": Comment.objects.create(commented_on=answer, text=comment, commented_by=commented_by) return JsonResponse({'bool':True}) else: return JsonResponse({'bool':False}) template.html {% for answer in answers %} <div class="card my-3"> <h6 class="card-header">Add Comment</h6> <div class="card-body"> <textarea class="form-control comment-answer-text-{{answer.id}}"></textarea> <div class="contain"></div> <button type="button" data-data="{{answer.id}}" class="btn btn-dark my-3 save-answer-comment">Submit</button> </div> </div> <script> $(document).ready(function(){ $(".save-answer-comment").on('click',function(){ var _answerid=$(this).data('data'); var commented=$(".comment-answer-text-"+_answerid).val(); var by = $(".uncommen-text-"+_questionid).val(); // Ajax $.ajax({ url:"{% url 'save_comment' answer.id %}", type:"post", data:{ comment:commented, answerid:_answerid, by : by, csrfmiddlewaretoken:"{{csrf_token}}" }, dataType:'json', }); }); }); </script> {% endfor %} I have tried many times but it … -
Django connect two unrelated models using has_many_through
I have 3 Django models: Company, Category, Country. a Company has many-to-many relations with Category and belongs to a Country a Country has many Company below is my code for the 3 models class Company(models.Model): name = models.CharField(max_length = 255, unique = True) country = models.ForeignKey(Country, on_delete = models.CASCADE, related_name = 'companies') categories = models.ManyToManyField(Category, related_name = 'companies') class Country(models.Model): name = models.CharField(max_length = 255, unique = True) class Category(models.Model): name = models.CharField(max_length = 255, unique = True) # show method in the country view def show(request, slug): country = get_object_or_404(Country.objects.prefetch_related('companies'), slug = slug) context = { 'country': country } return render(request, 'countries/show.html', context) # show.html template for country {% for company in country.companies.all %} <a href="{{ company.get_absolute_url }}">{{ company.name|title }}</a><br> {% empty %} <p>no companies yet</p> {% endfor %} How do I get the categories in a country through the companies and also the number of companies in that category in the country in the country view -
Django Tabular Inline has no foreign key issue
In Django I am setting up two models one for product and one for image. One product can have multiple images associated with it and therefore I am using a one to many model. In my models.py I have from django.db import models from django.db.models.fields import CharField # Create your models here. class Image(models.Model): image = models.ImageField() imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255, help_text = "Comma delimited words for SEO") imageMetaDescription = models.CharField("Meta description", max_length = 255, help_text = "Content for image meta tag description") defaultImage = models.BooleanField(default= False) class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) productAvailable = models.BooleanField(default = True) productCreated_at = models.DateTimeField(auto_now_add = True) productUpdated_at = models.DateTimeField(auto_now = True) productSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from product name") productMetaKeywords = models.CharField("Meta keywords for SEO", max_length = 255, help_text ="Comma delimited words for SEO") productMetaDescription = models.CharField("Meta description", max_length = 255, help_text="Content for meta tag description") productImages = models.ForeignKey(Image, on_delete=models.CASCADE) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName In admin.py from django.contrib import admin from .models import Product, Image from .forms import ProductAdminForm # Register your models … -
how to use django authentication
views.py from django.contrib.auth import authenticate def loginf(request): username = "ph" password = "mypassword" user = authenticate(username=username, password=password) if user is not None: print(user) else: print("not found") return render(request,'myapp/login.html',) urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include from . import views urlpatterns = [ path('',views.Home.as_view(),name='index'), path('signup/',views.SignUpView.as_view(),name='signup'), path('login/',views.loginf, name ='login') ] it always return "not found". my username and password are valid, i have double checked username and password, and tried with many users, what i am doing wrong. password saved in database in pbkdf2_sha256 algorithm, how do i authenticate. -
I am using tiny mce in django and in react.js . Tiny mce text editor gives html in front-end
I am using django and react.js in our project. I use tiny mce to write the blog the blog is save in backend and I fecth the blog in front-end It gives me html in the front-end like this Why Jammu and Kashmir Is The Perfect Location For Pre Wedding Shoots In India BY SHIVANGI GOEL MAY 2, 2019 Searching for the perfect location for your pre wedding shoot? Well, they say you get married only once, so why not make it memorable and larger than life? The most important thing on every soon to be hitched couple’s bucket list – a pre wedding shoot, requires some good planning. The most important aspect of planning a pre-wedding shoot is searching for the most romantic and picturesque locations. Jammu and Kashmir is the perfect location for a unique experience and a gorgeous pre wedding shoot. Only because if there’s paradise on earth- it’s here! From the very beautiful Dal Lake, Shalimar Bagh, Chashma Shahi and Mughal Gardens to the marvelous hill stations like Gulmarg, Pahalgam & Sonamarg; Kashmir has it all. Leh Ladakh or the Biker’s heaven is yet another feast for the eyes in Kashmir which is gaining popularity as one of the … -
How to save Foreign Key in table and get populated data in Django rest framework?
I'm trying to save advisor id in advisor_id field in Booking table but it is storing null value in booking table when ever I use advisor = AdvisorSerializer(read_only=True) which I'm using to populate data from Advisor Model serializer.py from django.db import models from django.db.models import fields from rest_framework import serializers from .models import Advisor, Booking class AdvisorSerializer(serializers.ModelSerializer): class Meta: model = Advisor fields = '__all__' class BookingSerializer(serializers.ModelSerializer): advisor = AdvisorSerializer(read_only=True) class Meta: model = Booking fields = '__all__' models.py from django.db import models from users.models import User # Create your models here. class Advisor(models.Model): name=models.CharField(max_length=255) photo=models.URLField() class Booking(models.Model): user=models.ForeignKey(User, related_name='users', blank=True, null=True, on_delete=models.CASCADE) advisor=models.ForeignKey(Advisor, related_name='advisors', blank=True, null=True, on_delete=models.CASCADE) booking_time=models.DateField() views.py - post method to store data in booking table class bookAdvisorMeetingDate(APIView): def post(self, request, user_id, advisor_id): token = request.COOKIES.get('jwt') if not token: return Response({"success": False, "message": "UnAuthorized"}, status=status.HTTP_401_UNAUTHORIZED) try: payload = jwt.decode(token, 'secret', alogrithm=['HS256']) except jwt.ExpiredSignatureError: return Response({"success": False, "message": "UnAuthorized"}, status=status.HTTP_401_UNAUTHORIZED) if not str(payload['id']) == user_id: return Response({"success": False, "message": "UnAuthorized | You have no access to this route"}, status=status.HTTP_401_UNAUTHORIZED) # print(user_id, advisor_id) user = User.objects.filter(id=user_id).first() advisor = Advisor.objects.filter(id=advisor_id).first() print('user adn advisor', user.id, advisor.id) data = {**request.data, 'user': user_id, 'advisor': advisor_id} serializer = BookingSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"success": True}, … -
Django images not found in page view but was save after post request
I was trying to save an image but it can't be displayed through the browser. It was successfully saved in the exact location but when I pasted the link it says, "Page not found". Could someone help me with what's going on? See output: Browser View Code: Code Snippet Settings configuration: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_LOCATION = "static" MEDIA_LOCATION = "media" -
Termux django requirements.txt pip install error
WARNING: Discarding https://files.pythonhosted.org/packages/fa/aa/025a3ab62469b5167bc397837c9ffc486c42a97ef12ceaa6699d8f5a5416/bcrypt-3.1.7.tar.gz#sha256=0b0069c752ec14172c5f78208f1863d7ad6755a6fae6fe76ec2c80d13be41e42 (from https://pypi.org/simple/bcrypt/) (requires-python:>=2.7, !=3.0., !=3.1., !=3.2., !=3.3.). Command errored out with exit status 1: /data/data/com.termux/files/home/qforum/bin/python3 /data/data/com.termux/files/usr/tmp/pip-standalone-pip-bgwdkmi6/env_pip.zip/pip install --ignore-installed --no-user --prefix /data/data/com.termux/files/usr/tmp/pip-build-env-g9xko9te/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel 'cffi>=1.1; python_implementation != '"'"'PyPy'"'"'' Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement bcrypt==3.1.7 (from versions: 1.0.0, 1.0.1, 1.0.2, 1.1.0, 1.1.1, 2.0.0, 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, 3.1.7, 3.2.0) ERROR: No matching distribution found for bcrypt==3.1.7 WARNING: You are using pip version 21.2; however, version 21.3.1 is available. You should consider upgrading via the '/data/data/com.termux/files/home/qforum/bin/python3 -m pip install --upgrade pip' command. -
git push -u origin username password
I have a problem with git push -u origin when I enter my github username and password it gives this error: git push -u origin master remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead. remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information. fatal: Authentication failed for 'https://github.com/Ahmadmohseni/Concert_ticketsales_system_project.git/' -
Django Error admin.E202 'stamm.Workplan' has no ForeignKey to 'enquiry.Costing'
I'm struggling with the following Problem: I have created two apps, "stamm" and "enquiry". In the first app "stamm" I have the model Workplan. In the second app "enquiry" I have the model "Costing". I use a M2M relationship via a through-model called "CostingWorkplan" below my Costing model. Then I want to add a TabularInline from the Workplan to my CostingAdmin. When I do this, I get the Error "<class 'enquiry.admin.WorkplanInline'>: (admin.E202) 'stamm.Workplan' has no ForeignKey to 'enquiry.Costing'.". I checked a couple of threads with a similar Problem, but can't get rid of it. Did I overlook something? Here is my Python Code: # stamm.models.py class Workplan(model.Model): some_fields = ... # enquiry.models.py from stamm.models import Workplan class Costing(model.Model): some_fields = ... costing_workplan = models.ManyToManyField(Workplan, through='CostingWorkplan') class CostingWorkplan(models.Model): workplan = models.ForeignKey(Workplan, on_delete=models.RESTRICT) costing = models.ForeignKey(Costing, on_delete=models.RESTRICT) # enquiry.admin.py from .models import Costing from stamm.models import Workplan class WorkplanInline(admin.TabularInline): model = Workplan @admin.register(Costing) class CostingAdmin(admin.ModelAdmin): inlines = (WorkplanInline, ) -
Django reverse_lazy to a URL with a related field id
I have created 2 related models, Applicant and ApplicantStatus. After creating an ApplicantStatus, I would like to reverse_lazy to the applicant detail page based on the applicant status create view entry. class Applicant(models.Model): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) class ApplicantStatus(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.PROTECT, related_name='applicant') Here is the applicant status create view class ApplicantStatusCreateView(LoginRequiredMixin, CreateView): model = ApplicantStatus form_class = ApplicantStatusCreateForm template_name = 'recruitment/applicant_status_create.html' def get_success_url(self): return reverse_lazy('recruitment:applicant_detail', kwargs={'pk': self.object.pk}) I already know that this will redirect to the non-exisiting page as that applicant doesn't exist yet. This is where I would like to get the id of the applicant from the form and use that in the kwargs, so i will see the applicant detail page with the list of applicant statuses. Here is the applicant detail view: @login_required() def applicant_detail_view(request, pk): applicant_detail = Applicant.objects.get(id=pk) form = ApplicantStatusCreateForm applicant_status_detail = ApplicantStatus.objects.filter(applicant__id=applicant_detail.id) context = { 'applicant_detail': applicant_detail, 'form': form, 'applicant_status_detail': applicant_status_detail, } return render(request, 'recruitment/applicant_detail.html', context) The applicant status create form appears in the detail view too as I'm using a modal to display the form in the detail view. -
Django ORM for intermediate images table gives error "The QuerySet value for an exact lookup must be limited to one result"
I have multiple Images associated with a Spots using the intermediate table ImageSpots, and I am trying to render each image for each spot but keep getting the error "The QuerySet value for an exact lookup must be limited to one result using slicing.". Can someone help me figure out what I'm doing wrong? models.py class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) author = models.ForeignKey(Authors, models.DO_NOTHING) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') summary = models.TextField(blank=True, null=True) content1 = models.TextField(blank=True, null=True) content2 = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'spots' verbose_name_plural = 'Spots' def __str__(self): return str(self.id) + ": " + str(self.title) class Images(models.Model): note = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(upload_to="images", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'images' verbose_name_plural = 'Images' def __str__(self): return str(self.id) + ": " + str(self.note) class ImageSpots(models.Model): images = models.ForeignKey('Images', models.DO_NOTHING) spots = models.ForeignKey('Spots', models.DO_NOTHING) class Meta: managed = True db_table = 'image_spots' verbose_name_plural = 'ImageSpots' def __str__(self): return str(self.spots) + ": " + str(self.images) views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() images = Images.objects.filter(imagespots__spots=spots) context = {'spots': spots, 'article': article, … -
I need to connect my Django app to a live Mysql server
I made an integration app for clickup with webhooks that sends data to my Django api whenever an action is performed. So far I've been saving the data in my local postgres database. But I need to send the data to a Mysql live server that is the database for a sap B1 app. I looked into how to hook the live database into my Django app and found something called pymssql but I need to write the queries myself instead of using the Django ORM. So I was thinking of if there's any type of synchronisation that can be done between my Django database that I will deploy on heroku and the live Mysql server. Any tips on how to do that would be appreciated. -
Adding the quantity of a product and updating it in cart using django
I am going through a django e-commerce video tutorial in which I can add product to cart using Ajax perfectly but am unable to update the quantity of the product to the cart. I have gone through many video tutorial as well as many stack overflow questions and many blogs but couldn't find a solution. please help me out Product/models.py class Product(models.Model): title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField(default=1) cart/models.py class CartManager(models.Manager): def new_or_get(self,request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count()==1: new_obj = False; cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj=user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action =='post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: … -
Django: Many to many field MultiSelect Into DropdownList
I have one manytomany field in one of my model which is currently coming as Multiselect but I need a dropdown where user can select multiple values as I have huge data to show. I am trying this in forms.py but it is not showing dropdown field. model.py: class Chain(models.Model): chain_id = models.AutoField(primary_key=True) chain_name = models.CharField(max_length=255, unique=True) chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE) history = HistoricalRecords() class Meta: ordering = ('chain_name') def __str__(self): return self.chain_name class Brg(models.Model): brg_campaign_id = models.AutoField(primary_key=True) campaign_tracking = models.ForeignKey(CampaignTracking, on_delete=models.CASCADE) brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE, related_name="primary_brg", help_text='Add Brgs/chain names for these above campaign has run') brg_benchmark = models.ManyToManyField(Chain, related_name="competitor_brg", null=True, blank=True, help_text='Add max.5 other benchmarks brgs to check overall impact') history = HistoricalRecords() class Meta: verbose_name = 'Brg Campaign Tracking' def __str__(self): return "Brg names list" forms.py: class ChainForm(forms.ModelForm): class Meta: model: Chain # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',) widgets = {'chain_name': Select()}