Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cart matching query does not exist
I'm creating a ecommerce website with python Django. Mean While raised this error " Cart matching query does not exist ". What can I do to solve this error. views.py class AddToCartView(TemplateView): template_name = "add_to_cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) product_id = self.kwargs['pk'] produc_obj = Product.objects.get(id=product_id) cart_id = self.request.session.get("cart_id", None) # Old Cart if cart_id: cart_obj = Cart.objects.get(id=cart_id) prd_in_this_cart = cart_obj.cartitem_set.filter(product=produc_obj) # Item already exist in cart if prd_in_this_cart.exists(): cartproduct = prd_in_this_cart.last() # first() prd_in_this_cart.quantity += 1 cartproduct.total += produc_obj.amazon_rate cartproduct.save() cart_obj.total += produc_obj.amazon_rate cart_obj.save() # Item already exist in cart else: cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() # New Cart else: cart_obj = Cart.objects.create(total=0) self.request.session["cart_id"] = cart_obj.id cartproduct = CartItem.objects.create(cart=cart_obj, product=produc_obj, quantity=1, total=produc_obj.amazon_rate, subtotal=produc_obj.amazon_rate) cart_obj.total += produc_obj.amazon_rate cart_obj.save() return context -
get results from one view to another view in django
I have two views. 1 gets results from search, 2 shows results in html file. I know I can combine 2 views to 1, after getting results and showing it. I need to separate two function because after getting results from 1, I can show it, using it with pagination and using it with next/back function I try to use request.session to get data from view 1 to view 2 but It fails View 1 def list_contract_test(request): results = {} if request.method == 'GET': query1= request.GET.get('search1') query2= request.GET.get('search2') submitbutton= request.GET.get('submit') if query1 is not None: lookups_contract= Q(contract__icontains=query1) lookups_name = (Q(name__icontains=query2.upper())|Q(name__icontains=query2.lower())) results= Contracts.objects.filter(lookups_contract,lookups_name).distinct() #context['contract_posts'] = contract_posts request.session['results'] = results return render(request, "customer2.html",results) else: results= Contracts.objects.all() #context['contract_posts'] = contract_posts self.request.session['results'] = results #global val1 #def val1(): # return results return render(request, 'customer2.html',results) else: return render(request, 'customer2.html') View 2 def get_data(request): contract_posts_test = request.session['results'] #contract_posts_test = val1() context['contract_posts_test'] = contract_posts_test return render(request, 'customer2.html', context) In my template customer2.html {% for contract in contract_posts_test %} <tr> <td><a href="{% url 'contract_detail' contract_id=contract.contract %}">{{contract.contract}}</a></td> <td>{{ contract.name }}</td> <td>{{ contract.debt }}</td> <td>{{ contract.created_at}} </tr> {% endfor %} In my url path("customer2/",get_data,name="get_data"), The error shows: ...\views.py, line 196, in get_data return render(request, 'customer2.html',results) else: return render(request, 'customer2.html') #request.session['list'] … -
How do I make a model fields into a dropdown choice in another model?
I want to create a form which has the fields of another model.The dropdown items will be the fileds not the data in that fields Is it possible? and how? -
Export all list_display fields to csv in django admin
I'm using the recipe at https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected" which works great except it doesn't export all the columns I see in the admin panel. I have added some extra columns like this class MeetingAdmin(admin.ModelAdmin, ExportCsvMixin): actions = ["export_as_csv"] list_display = ( "__str__", "expert_network", ) def expert_network(self, obj): if obj.expert: return obj.expert.network.name else: return "-" is it possible to improve the ExportCsvMixin to also export the callable list_display fields? -
Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$']
I am building a BlogApp AND build a Signup view BUT when i open browser then it shows me :- Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$'] views.py def signup_view(request,user_id): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('mains:profile',user_id=user_id) else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) urls.py path('signup_view/<int:user_id>',views.signup_view, name='signup_view'), login.html <a href="{% url 'users:signup_view' user.id %}">Register Here.</a> Problem When i open browser then it is keep showing me Reverse for 'signup_view' with arguments '(None,)' not found. 1 pattern(s) tried: ['accounts/signup_view/(?P<user_id>[0-9]+)/$']. I don't know what am i missing. Any help would be appreciated. Thank You in Advance -
Django Channels - WebSockets: Cannot find websocket_accept method defined anywhere
Might be a silly one, but I really can't figure this out. I am going through the source code of Django Channels in order to understand which is the best way to manually terminate an open web socket connection from the server. Then I noticed that the accept method of the WebsocketConsumer sends a message of type websocket.accept: https://github.com/django/channels/blob/master/channels/generic/websocket.py#L52 According to Django Channel docs, that means there is somewhere a method named websocket_accept that will be invoked on the consumer: Consumers are structured around a series of named methods corresponding to the type value of the messages they are going to receive, with any . replaced by _. But I cannot find a websocket_accept method anywhere in the repository (I even cloned it and grep'ed to it). So I am wondering how does this work. Have I interpreted wrong or the docs mean something different (eg. some other method should be called instead of the one I think it will)? Thanks -
Invalid Syntax error while installing Django in linux
I am trying to install Django in linux.I have already installed python. Error I am getting when executed "pip install Django" or "pip3 install Django" pip install django Traceback (most recent call last): File "/home/mandar/.local/bin/pip", line 7, in <module> from pip._internal.cli.main import main File "/home/mandar/.local/lib/python3.5/site-packages/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax -
Pagination Based on Queryset
I'm trying to implement pagination on my Django app that is based on the filtered queries, but the pagination shows all the objects even the ones not filtered, any insight on what I'm doing wrong? Any assistance would be appreciated. def searchPropertyListView(request): city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") categories = Category.objects.all() purposes = Purpose.objects.all() featured = list(Property.objects.filter(featured=True)) shuffle(featured) querySet = Property.objects.all() city_or_neighborhood = request.GET.get('city_or_neighborhood') category = request.GET.get('category') purpose = request.GET.get('purpose') if city_or_neighborhood != '' and city_or_neighborhood is not None: querySet = querySet.filter(Q(city__title__icontains=city_or_neighborhood) | Q(neighborhood__title__icontains=city_or_neighborhood) ).distinct() if category != '' and category is not None: querySet = querySet.filter(category__title=category) if purpose != '' and purpose is not None: querySet = querySet.filter(purpose__title=purpose) paginator = Paginator(querySet, 1) page = request.GET.get('page') try: querySet = paginator.page(page) except PageNotAnInteger: querySet = paginator.page(1) except EmptyPage: querySet = paginator.page(paginator.num_pages) -
Vue custom delimiters not working in Firefox
I have a django project and I want to start adding Vue.js elements into it, but there is a big overarching issue before I can really start in that custom delimiters (template tags) do not work in the firefox browser only Chrome, I can change them from curly braces to square brackets, but in firefox it just renders the code not the message. The following code is not part of my django project, it is just example code to demonstrate the issue. <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <title>Learning Vue.js</title> </head> <body> <div id="app"> <input type="text" v-model="name" /> <p>Hello [[ message ]]</p> </div> <script> new Vue({ delimiters: ["[[","]]"], el: '#app', data() { return { message: 'Hello World' }; } }); </script> </body> </html> So this code renders the following in Chrome: Hello World! And in Firefox, it renders the code: [[ message ]] I'm assuming there is a fix for this, as I almost never see rendered code in websites and I'm assuming Vue is popular, how do other developers get around this issue? -
Django Rest Framework: PageNumberPagination doesn't work
I've created an APIView to list all posts of a blog: from ..pagination import BlogPagination class BlogPostAPIView(APIView): pagination_class = BlogPagination permission_classes = [IsAdminOrReadOnly] def get(self, request): objects = BlogPost.objects.filter(draft=False, publishing_date__lte=Now()) serializer = BlogPostSerializer(objects, many=True) return Response(serializer.data) def post(self, request): serializer = BlogPostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I've also created a pagination.py: from rest_framework.pagination import PageNumberPagination class BlogPagination(PageNumberPagination): page_size = 5 With this code I see all posts and not five posts for page. I'm using Django 3.1.5 and DRF 3.12.2 I've the same problem if I use the global pagination in settings.py REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5 } -
<br> tag dosen't work in <p> tag with ajax
br tag does not work when using ajax It's a Django platform, and I used json to get the data. Chrome developers mode does line changes normally, but not on the screen. Is there a way? And can I optimize my ajax code more? I'm kinda new about Ajax and frontend my ajax $(".title_txt").click(function (e) { e.preventDefault(); var txt = $(this); var tr = txt.parent(); var td = tr.children(); var mail = td.eq(0); var pk = td.eq(8).text(); $.ajax({ type: 'GET', url: "{% url 'get_consul' %}", data: {"pk": pk}, dataType: "json", success: function (response) { var title = $(".title_con"); var content = $(".con_con"); var created_by = $(".con_txt_created_by"); var created_at = $(".con_txt_created_at"); var classification = $(".con_txt_classification"); var status = $(".con_txt_status"); /* modal value changed */ title.text(response[0].fields.title) content.html(response[0].fields.content) created_by.text(response[0].fields.created_by) created_at.text(response[0].fields.created_at) classification.text(response[0].fields.classification) status.text(response[0].fields.status) status.removeClass('imp_01 imp_02 imp_03') status.addClass(response[0].fields.status_css) /* list css changed to read */ td.removeClass('on') td.addClass('read') }, error: function (response) { console.log(response) } }) }) my modal in html <div class="title"> <p class="title_tit">제목</p> <p class="title_con"></p> </div> <div class="con"> <p class="con_tit">내용</p> <p class="con_con"></p> </div> -
passing image url to view from html post method
Good evening everyone! I'm a freshly baked Django user and I have little problem. Do you know how to pass img data to my view? <form method="post"> {% csrf_token %} <label for="input-title"></label> <input name="title" type="text" id="input-title" readonly /> <label for="input-authors"></label> <input name="author" type="text" id="input-authors" /> <p id="form-price">{{ form.price }}</p> <img width="100" height="133" id="modal-image" src="" alt="" > </form> as for inputs I'm using name parameter in html but when i use name for <img> its not passed to request.POST forms.py : class BookOffer(ModelForm): class Meta: model = Product fields = ['title', 'author', 'price', 'condition'] -
How to share files between users with username or email
I have a small django app where users can upload files. I want users to be able to send files to others by name or email. How can I do that? Thanks in advance my exist project--> https://github.com/asimancalil/File_Sharing_DjangoApp -
Integer field changed but still prefix zero not displaying
I'm using an existing django project and I have a problem with displaying prefix zero of some numbers the old models was id_number = models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(9999)]) I have changed it to id_number = models.CharField(max_length=5, default="") than migrate it python3 manage.py makemigrations than python3 manage.py migrate but it still removing any prefix zero how can I fix that pleas I'm using postgresql db? -
After submitting form Redirect to home page by using Django, python with vue axiox
When user filled form then after submitting form form needs to redirect to another page. I have tried but I am new to vue so, I am not able to understand how to achieve this please help me to achieve this thank you. html <div id="app"> <form> <input type="text" v-model="username"> <input type="password" v-model="password"> <input v-on:click.prevent="submitForm" type="submit" value="submit"> </form> </div> vue.js <script> const vms = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { username: null, password: null, success_msg: "", err_msg: "", }, /* submiting post Ad form */ methods: { submitForm: function(){ axios({ method : "POST", url:"{% url 'submitform' %}", //django path name headers: {'X-CSRFTOKEN': '{{ csrf_token }}',}, data : {"username":this.username, "password":this.password},//data }).then((response) => { console.log( this.posts.push(response.data); }); }, }, }); Vue.config.productionTip = false </script> This is my view code to save data into databse. views.py from django.shortcuts import render from django.http import JsonResponse from .models import vue_testing import json def submit_form(request): if request.method == "POST": data = json.loads(request.body) username = data['username'] print("username", str(username)) # password = data['password'] # print("password", str(password)) saveform = vue_testing(username=username, ) saveform.save() return redirect("/") # if username and password: # response = f"Welcome {username}" # return JsonResponse({"msg":response}, status=201) # else: # response = "username or password … -
Django UnboundLocalError local variable 'enroll' referenced before assignment
My code is of an enrolment list for a student. It shows subjects a student can enroll and ones the student already has enrolled and can tick as passed, delete or unpass the passed ones. The problem is when I want to add/enroll a new subject I get the following error. If someone can take a look and help, much appreciated. TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/enrolment/ Django Version: 3.1.5 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', 'crispy_forms'] Installed 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'] Traceback (most recent call last): File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\D\Documents\django\project\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\D\Documents\django\project\project\App\decorations.py", line 15, in wrap return function(request, *args, **kwargs) File "C:\Users\D\Documents\django\project\project\App\views.py", line 73, in enrolment_view enroll(request.POST.get('enroll'),student) Exception Type: UnboundLocalError at /enrolment/ Exception Value: local variable 'enroll' referenced before assignment MY VIEW @student_required def enrolment_view(request): if (request.user.is_authenticated): username = request.user.get_username() student = MyUser.objects.get(username=username) if(request.method == 'POST'): if request.POST.get('enroll'): enroll(request.POST.get('enroll'),student) elif request.POST.get('delete'): delete(request.POST.get('delete'),student) elif request.POST.get('passed'): passed(request.POST.get('passed'),student) elif request.POST.get('not_passed'): not_passed(request.POST.get('not_passed'),student) enroll = Enrolment.objects.filter(student_id_id=student.id).order_by('predmet_id') subjects = Subject.objects.exclude(id__in=enroll.values('predmet_id')) subj_all = Subject.objects.all() if student.status == 'REDOVNI': br_sem = 6 else: br_sem = 8 context = { … -
Field 'id' expected a number but got 'Student'
I tried to apply python manage.py migrate I get the error Field 'id' expected a number but got 'Student'. Following are my python files.ValueError: invalid literal for int() with base 10: 'Student' I've set the value of primary key to be id in views.py #----------------------STUDENT OPERATION----------------------------------------------- @login_required() def test_form(request): students = TestModel.objects.all() paginator = Paginator(students,20) page_number = request.GET.get('pages') page_obj = paginator.get_page(page_number) enter code here if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): x = form.instance.student print(x) p = form.save(commit=False) p.save() messages.success(request,'Student "{}" has been succesfully added!'.format(x)) return redirect('testform') else: form = TestForm() return render(request,'testform.html', {'form':form,'students':page_obj}) @login_required() def update_form(request,id): if request.method == 'POST': #defpost obj = TestModel.objects.get(pk = id) form = TestForm(request.POST,instance=obj) if form.is_valid(): form.save() messages.success(request,'Student "{}" was succesfully updated'.format(obj.student)) return redirect('testform') else: #def get() obj = TestModel.objects.get(pk=id) print(obj.student) print('###') form = TestForm(instance=obj) return render(request,'testform_update.html',{'form':form}) @login_required() def del_testform(request,id): if request.method == 'POST': obj = TestModel.objects.get(pk = id) student = obj.student obj.delete() messages.warning(request,'Student "{}" has been deleted succesfully!'.format(student)) return redirect('testform') def home(request): posts = Post.objects.all().order_by('-date_posted')[:8] destinations = Destinations.objects.all().order_by('date_posted')[:6] return render(request,'home.html', {'posts':posts, 'destinations':destinations}) #-------------------STUDENTOPERATION ENDS--------------------------------------------- **in models.py** class TestModel(models.Model): GENDER_CHOICES = (('Male','Male'),('Female','Female')) student = models.CharField(max_length=100,null=True) address = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_CHOICES,max_length=50) email = models.EmailField(null=True) def __str__(self): return self.student **in testform.html** {% extends … -
How can I add an action to the Django User admin page?
I'm using Django 3.0. I want to add an action to the User ChangeList in the admin. The documentation for admin actions indicates that to add an action to an admin page, I need to add either the method or a reference to it to the Model's admin.ModelAdmin subclass in admin.py: # admin.py from django.contrib import admin def make_published(modeladmin, request, queryset): queryset.update(status='p') make_published.short_description = "Mark selected stories as published" class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'status'] ordering = ['title'] actions = [make_published] or # admin.py from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): ... actions = ['make_published'] def make_published(self, request, queryset): queryset.update(status='p') make_published.short_description = "Mark selected stories as published" Since the User Model's admin.ModelAdmin subclass is in the auth system and not in my admin.py, though, I don't know where to put the code for this case. I tried following user Davor Lucic's answer to a much older but similar question from django.contrib.auth.models import User class UserAdmin(admin.ModelAdmin): actions = ['activate_user','deactivate_user'] def activate_user(self, request, queryset): queryset.update(status=True) def deactivate_user(self, request, queryset): queryset.update(status=False) activate_user.short_description = "Activate user(s)" deactivate_user.short_description = "Deactivate user(s)" admin.site.unregister(User) admin.site.register(User, UserAdmin) When I try this, the server halts with the error File "Project/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 144, in unregister raise NotRegistered('The model %s is not … -
Django: Load information from file and edit before saving
I have a bib tex file with a lot of sources, which I want to import within the django admin and edit them before saving. At the moment I have an uploader, where all resources get saved, when I click save. Afterwards I can go to the resources, open each and edit them manually. Does somebody know how to load the information into the admin page from the file, so I can edit them before I save the information? Should look like this. Question would be my file uploader and each Choice (Resource) would be prefilled with information. There should not be a foreign key between the file and the resources.: Thanks in advance. -
Programatically setting a Model's Fields in Django
Say I have a model Food class Food(models.Model): description = models.TextField() toppings = models.TextField() scheme = models.ForeignKey(FoodScheme, models.CASCADE) And I want to have another class, a FoodScheme which describes which of the fields must be set in a specific Food class. class FoodScheme(models.Model): scheme_name = models.TextField() requires_description = models.BooleanField(default=False) requires_toppings = models.BooleanField(default=False) But instead of hard coding this, I want to programmatically set these fields up, so any change in Food will change the FoodScheme class too. An example implementation (that doesn't work, for several reasons, but I think gets my point across): class FoodScheme(models.Model): scheme_name = models.TextField() for f in Food.get_fields(): setattr(self, f"requires_{f.name}", models.BooleanField(default=False)) Any ideas would be greatly appreciated. -
How do i redirect one html to another html page in django, tried that works for other but it is not working for mine. Help Appricated?
I have created views.py and define a function that renders the HTML and also in URL pattern defined. likewise href="{% url 'amrit' %} but failed to get the output and getting error like mention below. Error statement: Error : <a href="{% url 'amrit' %}">Modern Layout</a> NoReverseMatch at / Reverse for 'amrit' not found. 'amrit' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'amrit' not found. 'amrit' is not a valid view function or pattern name. Exception Location: /home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/bin/python3 Python Version: 3.8.5 Python Path: ['/home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/main_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/amrit/Desktop/sajhost.online/themeforest-UjFGKekH-xdata-wmhcs-html-web-hosting-template-file-and-license/sajhost.online/venv/lib/python3.8/site-packages'] Server time: Mon, 25 Jan 2021 13:19:57 +0000 views.py from django.shortcuts import render from .models import * from django.shortcuts import HttpResponse # Create your views here. def homepage(request): return render(request, 'index.html') def page2(request): return render(request, 'modern-layout.html') urls.py from django.urls import path from .views import * from . import views from django.conf import settings from django.conf.urls.static import static from django.urls import include, path from django.template import loader app_name = 'main_project' urlpatterns = [ path('', views.homepage, name='home'), path('page2', views.page2, name='amrit'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
i want to understand how the below question can be achive [closed]
suppose i have one ecomerce website with 6 products in it .i want to track the number of clicks on the perticular product. and i want to store details of the same in a database after viewing in it. please share the solution for this. -
Django ManyToManyField getting Field 'id' expected a number but got b'\x89PNG\r\n
I want to upload multiple files in Django. The code below getting Error Field 'id' expected a number but got b'\x89PNG\r\n'. i want to use ManyToManyField as FileField. please i need the solution. I would be grateful for any help. models.py class FileModel(models.Model): filename = models.FileField(upload_to='files/') class FileUploadModel(models.Model): file = models.ManyToManyField(FileModel) froms.py class FileUploadingForm(forms.ModelForm): file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) def __init__(self, *args, **kwargs): super(FileUploadingForm, self).__init__(*args, **kwargs) class Meta: model = FileUploadModel fields = ['file'] views.py def uploading_view(request): if request.method == "POST": form = FileUploadingForm(request.POST, request.FILES) if form.is_valid(): # post = form.save(commit=False) for files in request.FILES.getlist("filename"): f = FileModel(filename=files) f.save() form.save() return HttpResponse('success') else: form = FileUploadingForm() return render(request, 'uploading.html', {'form': form}) -
'Tribe' object has no attribute 'tribe_id'
I have a view which should redirect the user to the new tribe that he created. but I don't know how to get the tribe_id for it to work. views.py def tribeview(request, tribe_id): tribe = get_object_or_404(Tribe,pk=tribe_id) playlist = tribe.playlist_set.all() context = { 'tribe': tribe, 'playlists':playlist } return render(request, 'app/tribe.html', context) class create_tribe(CreateView): model = Tribe form_class = TribeForm template_name = 'app/create_tribe.html' def form_valid(self, form): tribe = form.save(commit=False) tribe.chieftain = self.request.user tribe.save() return super().form_valid(form) def get_success_url(self): return reverse('app:tribe-view', args={'tribe': self.object.tribe_id}) urls.py app_name = 'app' urlpatterns = [ path('', views.index, name='index'), path('tribe/<int:tribe_id>',views.tribeview,name='tribe-view'), path('tribe/<int:tribe_id>/playlist/<int:playlist_id>',views.playlistview,name='playlist-view'), path('new_tribe', login_required(create_tribe.as_view()), name="new-tribe"), ] models.py class Tribe(TimeStamped): name = models.CharField(max_length=200,unique=True) chieftain = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) tribe_members = models.ManyToManyField(Member) def __str__(self): return self.name[:80] -
my project is based on multi-image. it is not showing images on front-end
My project is basically based on the multi-image there is problem with html file. In this project i can uplaod multiple images at single time and see them together. I am able to upload the images but they are not able to show on the frontend. help me regarding this!! my html files are thus: base.html <!DOCTYPE html> <html lang='en'> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha2/css/bootstrap.min.css" integrity="sha384-DhY6onE6f3zzKbjUPRc2hOzGAdEf4/Dz+WJwBvEYL/lkkIsI3ihufq9hk9K4lVoK" crossorigin="anonymous"> <title>Multi Image Tutorial</title> </head> <body> <div class="container py-4"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> blog.html {% extends 'base.html' %} {% block content %} <div class="row row-cols-1 row-cols-md-2"> {% for post in posts %} <div class="col mb-4"> <div class="card"> <div class="view overlay"> <img class="card-img-top" src="{{post.image.url}}" alt="Card image cap" > <a href="#"> <div class="mask rgba-white-slight"></div> </a> </div> <div class="card-body"> <h4 class="card-title">{{post.title}}</h4> <p class="card-text">{{post.description}}</p> <a href="{% url 'detail' post.id %}" class="btn btn-primary btn-md">Read More</a> </div> </div> </div> {% endfor %} </div> {% endblock %} detail.html {% extends 'base.html' %} {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-mdb-ride="carousel"> <ol class="carousel-indicators"> {% for p in photos %} <li data-mdb-target="#carouselExampleIndicators" data-mdb-slide-to="{{forloop.counter0}}" class="{% if forloop.counter0 == 0 %} …