Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to map nested json data in react js
how to map one nested json data in react js example i want to display the product images that i recived from api export class Planview extends Component{ constructor() { super(); this.state = { package: [], }; } componentDidMount() { const ProdID = this.props.match.params.ProductID fetch(`http://127.0.0.1:8000/api/plan/${ProdID}/`) .then(response => response.json()) .then(responseData => { this.setState({ package: responseData }); }) .catch(error => { console.log('Error fetching and parsing data', error); }); } render(){ return(<> <div className="container mar" > <h1 className="my-4">{this.state.package.title}</h1> <div className="row"> <div className="col-md-offset-2"> <div className="row" id="gradient"> <div className="col-md-6 img-responsive"> <img className ="img-main img" src={"http://127.0.0.1:8000"+this.state.package.thumbnail} alt="main" fluid ="True"/> </div> <div className="col-md-6" id="overview"> <h4>{this.state.package.code}</h4> <h5><small> {this.state.package.created_at}</small></h5 </div> <div className="row mt-4"> <h3><small></small></h3> <div className="row"> { this.state.package.image.map(function (person, index) { return ( <div className="col" key={index}> <img className={person.image} src="" alt="1"/> </div> )})} </div> </div> </div> <div className="row"> <h3 className="my-4">{this.state.package.description}</h3> </div> </div> </div> </div> </> ); } } export default Planview; and my json is like {id: 1, image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…], title: "sample",…} code: "MAG0001" created_at: "2020-11-23" description: "college book" details: {age: 31, city: "New York", name: "John"} id: 1 image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…] slug: "sample" thumbnail: "/media/plan_images/900-square-feet-home-plan.jpg" title: "sample" from the above json i want to display the image from the field image array it contains multiple images and also … -
Python Django heroku error “! [remote rejected] master -> master (pre-receive hook declined)” [closed]
Please help me....... Whenever I type command: git push heroku master $ git push heroku master Enumerating objects: 10320, done. Counting objects: 100% (10320/10320), done. Delta compression using up to 4 threads Compressing objects: 100% (6444/6444), done. Writing objects: 100% (10320/10320), 15.12 MiB | 4.10 MiB/s, done. Total 10320 (delta 2785), reused 10299 (delta 2778) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python-3.8.2) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! remote: ! We have detected that you have triggered a build from source code with version bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: … -
AttributeError at /upload_to_vimeo/ 'TypeError' object has no attribute 'message'
while uploading videos to vimeo it throws this error following are codes views def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': form = VideoUploadForm(request.POST, request.FILES) if form.is_valid(): v = vimeo.VimeoClient( token=token, ) v.upload(request.FILES['video_file']) return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: form = VideoUploadForm() return render(request, 'forms/video_upload_form.html', {'form': form}) template <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="video_file"> <input type="submit" class="button inline-block bg-theme-1 text-white mt-5" value="Upload"> </form> Traceback: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 143. with io.open(filename, 'rb') as fs: During handling of the above exception (expected str, bytes or os.PathLike object, not TemporaryUploadedFile), another exception occurred: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/biju/Documents/mtenant/client_admin/views.py" in upload_to_vimeo 787. v.upload(request.FILES['video_file']) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in upload 71. return self.__perform_tus_upload(filename, attempt, chunk_size=chunk_size) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 152. raise exceptions.VideoUploadFailure( File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 93. super().init(response, message) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 30. self.message = self.__get_message(response) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in __get_message 23. message = getattr(response, 'message') Exception Type: AttributeError at /upload_to_vimeo/ Exception Value: 'TypeError' object has no attribute 'message' -
Saving dynamically added text box to database
First here is my view: def price_save(request): remarks = request.POST.get("remarks") current_user = request.user pah = PAH(remarks=remarks, created_by=current_user) pah.save() item1 = request.POST.getlist("item_code[]") item2 = request.POST.getlist("item_description[]") item3 = request.POST.getlist("uom[]") for item in item1: item_price = PAR(transaction_id=pah, item_code=item, item_description=item2, uom=item3) item_price.save() return HttpResponse("Saved!") with this I can save multiple rows with different values on item_code and same transaction id, but I dont know how to add item_description and uom in the for loop. -
How to foreign key to a foreign key
In class Model, brand is foreign key from Brand. In class Car, how do I foreign key the brand in class Brand? class Brand(models.Model): brand = models.CharField(max_length=200) def __str__(self): return self.brand class Color(models.Model): color= models.CharField(max_length=200) def __str__(self): return self.color class Model(models.Model): brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) model = models.CharField(max_length=200) def __str__(self): return self.model class Car(models.Model): brand=models.ForeignKey(Brand,null=True,on_delete=models.CASCADE)#it is wrong here, how do i fix it? model=models.ForeignKey(Model,on_delete=models.CASCADE) plate_number=models.CharField(max_length=200) -
Need help using placeholders for auth_views in django
I created a forgot password functionality using django.contrib.auth.views which is working fine. However the styling does not go with the rest of the site. I want to use only placeholders for the form fields. But since I am using the mentioned view, i don't know how. I want to remove the Email label here and write that as a placeholder This is the general theme of the site: For the login and register pages, I am mentioning the fields separately as shown in the figure: If i try do that for my forgot-password page, I get this result with no visible fields. If I try using form.password1 and form.password2, it doesn't work and I don't get the form fields at all. Here i use only the form option. I want to have the labels as placeholders(no labels). And the other stuff removed. Here are the views used in the urls.py file: Is the view using the second form? Also is there an option for a redirect here so I can just redirect my users to login page instead of a separate page? please help -
how to set djang logger to send email and save in file on AWS lightsail
Based on this SO question, I'm trying to implement error logging for my django project which is deployed on aws lightsail. my settings.py: DEBUG = False ALLOWED_HOSTS = ['XX.XXX.XXX.XXX'] # Email config EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ADMINS = ( ('myname', 'my email'), ) MANAGERS = ADMINS LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, } I user the logger in one of my apps' views.py as following: import logging def register(request): logger = logging.getLogger(__name__) ... if some_condition: logger.error('Something went wrong!') def mylogin(request): logger = logging.getLogger(__name__) if some_condition: logger.error('Something went wrong!') but I get no email at all. In addition to this, when I set file handler, my site gives internal error and don't come up at all. any idea how to do it? I need error logs to check the source of … -
Django returns only default image URL
I am new to Django and building a simple social media type app for adding and viewing posts. I am using admin side to upload profile images for users and it works well. I am yet to create a frontend to upload profile images. I am using PostgreSQL and I can query to see the correct URLs being saved in the table for profile images. But when I try to fetch these images and render, the default image (set in models.py) always renders. I am able to open the right images from admin side but Django only returns the default image. My frontend has Javascript in which I am using fetch API to get URLs of profile images. It works well except it returns only the default image. Please help me find out where I am going wrong or why only 'defaultpp.jpg' always shows up. I have tried using print statements in models.py and views.py and only see the URL for 'defaultpp.jpg' being returned. models.py def user_directory_path(instance, filename): return f'{instance.profile_user.id}/{filename}' class User(AbstractUser): def __str__(self): return f"User ID: {self.id} Username: {self.username}" class UserProfile(models.Model): profile_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) profile_picture = models.ImageField(upload_to = user_directory_path, blank=True, null=True, default='defaultpp.jpg') def __str__(self): return f"User: {self.profile_user} … -
Need a documentation for using sslcommerz api in django
Can someone help me out to build a payment gateway in django. I want to use sslcommerz. They dont have any documentation for django.Here is their documentation sslcommerz I badly need this or any documentation which i can follow.Because of some mobile banking i have to use their service. -
Django wagtail login required not working
I'm working on wagtailcms.I just want to display a page only if the user is logged in. I have tried LoginRequiredMixin,@method_decorator(login_required, name='dispatch') but nothing works from django.contrib.auth.decorators import login_required @login_required(login_url='/login/') class LessonListPage(RoutablePageMixin, Page): """ Lists all the lessons on one page """ template = "lesson/lesson_list_page.html" custom_title = models.CharField( max_length=100, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context""" context = super().get_context(request, *args, **kwargs) context["posts"] = LessonDetailPage.objects.live( ).public().order_by('-first_published_at')[:10] #Change 'public' to adjust which posts are displayed context["postcategories"] = Category.objects.all() return context -
html select tag not working in django template
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag and I want to select the default option from database <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
How do I proceed after authenticating the user through python social auth?
Hello so I'm very new to Django and I have successfully authenticated a user through twitter using python-social-auth. However, now I need to make a call to Twitters API and I am very lost in how I should retrieve and process the necessary data after authentication such as the user_id and access token in order to be able to do that. Thank you. -
Django ValueError: Field 'id' expected a number but got 'S'
Below is my models that are used in view where errors occur and error occurs in StockQuantity model particularly, when i try to filter or use get to retreive query it says expected number but got 'stringvalue' models.py # StockQuantity class StockQuantity(models.Model): item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True) color = models.ForeignKey( 'ItemColor', on_delete=models.CASCADE) cloth_size = models.ForeignKey( 'ClothSize', on_delete=models.CASCADE, blank=True, null=True) footwear_size = models.ForeignKey( 'FootwearSize', on_delete=models.CASCADE, blank=True, null=True) stock_quantity = models.IntegerField(null=True, default=10) #OrderItem class OrderItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) footwear_size = models.CharField(max_length=50, null=True) cloth_size = models.CharField(max_length=50, null=True) color = models.CharField(max_length=50, null=True) ordered = models.BooleanField(default=False) #Order class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) requested_refund = models.BooleanField(default=False) refund_status = models.BooleanField(default=False) #Payment class Payment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) paypal_transaction_id = models.CharField(max_length=50) amount = models.FloatField() timestamp = models.DateTimeField(default=timezone.now) Below is my views.py and specifically the view where the error is thrown, I have … -
app.js:6 Uncaught TypeError: Cannot read property 'addEventListener' of null
Here is my app.js const navBtn = document.getElementById("nav-btn"); const navbar = document.getElementById("navbar"); const navClose = document.getElementById("nav-close"); navBtn.addEventListener("click", () => { navbar.classList.add("showNav"); }); navClose.addEventListener("click", () => { navbar.classList.remove("showNav"); }); I have placed the script tag at the end of the body tag in my html. I am using django as my backend and the javascript files have been loaded properly as I am not getting a 404 error. Need some help to resolve the issue -
I want to show customers phone_number and coin in home page
I am trying to fetch customers phone_number & Coin from the DB to my home page But I am stuck here and got really confused about this topic.I tried request.session.customer but it only shows the customers ID. Here is my Customer Models: class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) Here is views.py class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.get_all_products() cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() # balance = Customer.objects.get(user=request.user) # balance = get_object_or_404(Customer, coin = request.coin) categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: # products = Product.get_products_by_category(categoryID) products = products.filter(category__id = categoryID) # else: # products = Product.get_all_products() if brandID: # proucts = Product.get_brands_by_products(brandID) products = products.filter(brand__id = brandID) # else: # products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands, 'sliders':sliders, 'offers':offers, # 'balance':balance } return render(request, 'Home/index.html', args) I commented somelines to show only coin in homepage but its not showing :( -
Django, Permissions other than'view' do not work
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. No answer was posted, so I ask again. -
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)/$']
I am currently using django 3.1.3 on Windows 10. I was following Dennis Ivy's tutorials for creating a django app, and I reached part 11: Inline Formsets. I am 100% sure I have everything Dennis has but for some reason I am getting the error I mentioned in the title. It was able to access the dashboard once, when I went to update orders it crashed, and after that I was never even able to access dashboard (http://127.0.0.1:8000/dashboard/) again! Here are my files: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from .models import Customer, Address, Credit_Card, Order, Grocery_Store, Product, Supplier, Warehouse, Staff_Member, Price from .forms import OrderForm #Create your views here. def index(request): return render(request, 'index.html', {}) def dashboard(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers,'total_orders':total_orders,'delivered':delivered,'pending':pending } return render(request, 'dashboard.html', context) def customer(request, pk_test): customer = Customer.objects.get(Customer_ID=pk_test) orders = customer.order_set.all() order_count = orders.count() context = {'customer':customer, 'orders':orders, 'order_count':order_count} return render(request, 'customer.html', context) def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('Product_Name', 'status'), extra=10 ) customer = Customer.objects.get(Customer_ID=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) … -
The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead
Request Method: GET Request URL: http://localhost:8000/activate/MTA/adw60x-512068e272684badad26f51a29e1412f/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead. Exception Location: E:\python\soalnesia\venv\lib\site-packages\django\core\handlers\base.py, line 307, in check_response Python Executable: E:\python\soalnesia\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\python\soalnesia\soalnesia', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\uec\AppData\Local\Programs\Python\Python39', 'E:\python\soalnesia\venv', 'E:\python\soalnesia\venv\lib\site-packages'] Server time: Wed, 25 Nov 2020 04:46:31 +0000 class ActivateAccountView(View): def get(self,request,uidb64,token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.Objects.get(pk=uid) except Exception as identifier: user=None if user is not None and generate_token.check_token(user,token): user.is_active=True user.save() messages.success(request, 'ACCOUNT IS ACTIVATE') return redirect('login') else: return render(request,'auth/activate_failed.html', status=401) path('activate///',views.ActivateAccountView.as_view(), name='activate'), Hi, {{user.username}} Please click this link below to verify your account http://{{domain}}{% url 'activate' uidb64=uid token=token %} -
update the choice list of django model using django Admin panel
my model is currently as follows : class Food(model.Model): CUISINE_CHOICES = ( ('1', 'Chinese'), ('2', 'French'), ('3', 'Italian'), ('4', 'Indian'), ('5', 'Japanese'), ('6', 'Moroccan'), ('7', 'Spanish'), ('8', 'Thai'), ) Cuisine = models.CharField(max_length = 20,choices = CUISINE_CHOICES,default = '1') Dish = models.CharField(max_length=200, blank=True) Is there a way by which I can update the CUISINE_CHOICES list in future from the admin panel. Say I need to add Arabian as the 9th cuisine. I know that manually updating the cuisine_choices list will resolve it, I want to know if i can do the same from Admin Panel. If yes, How ? I've searched for similar questions/ solutions but could not find one that matches my requirement. TIA. -
Inlineformset_factory saving parent without child and not displaying validation errors if child is none
I am having 2 issues, one if you submit and click back and then submit again it duplicates the instance in the database - in this case Household. In addition it is saving the parent 'Household' without the child 'Applicants' despite me setting min_num=1 can someone point me in the right direction to resolve this issue. Many thanks in advance class Application(models.Model): name = models.CharField(max_length=100, blank=True, null=True) application_no = models.CharField(max_length=100, unique=True, default=create_application_no) created_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class HouseHold(models.Model): name = models.CharField(max_length=100) application = models.ForeignKey(Application, on_delete=models.CASCADE) no_of_dependents = models.PositiveIntegerField(default=0) class Applicant(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) household = models.ForeignKey("HouseHold", on_delete=models.CASCADE) forms.py class ApplicationForm(ModelForm): class Meta: model = Application fields = ( "name", ) class ApplicantForm(ModelForm): class Meta: model = Applicant fields = [ "household", "first_name", "last_name" ] class HouseHoldForm(ModelForm): class Meta: model = HouseHold fields = [ 'name', 'application', 'no_of_dependents' ] def __init__(self, application_id=None, *args, **kwargs): super(HouseHoldForm, self).__init__(*args, **kwargs) self.fields['name'].label = 'House Hold Name' if application_id: self.fields['application'].initial = application_id self.fields['application'].widget = HiddenInput() ApplicantFormset = inlineformset_factory( HouseHold, Applicant, fields=('household', 'first_name', 'last_name'), can_delete=False, extra=1, validate_min=True, min_num=1) views.py class HouseHoldCreateView(LoginRequiredMixin, generic.CreateView): model = models.HouseHold template_name = "households/household_create.html" form_class = HouseHoldForm def get_parent_model(self): application = self.kwargs.get('application_pk') return application def … -
Querying Many To Many relationship in Django
I'm experimenting with Django and I'm trying to figure out Many to Many Relationships. Let's say I have certain model named "Facility", similarly I created another model named "Hotels" which contains fields 'facility' and 'featured_facility' both are in Many To Many relationship with "Facility". I want to add featured_facility only if it is available in 'facility' fields how can I do that? Here is my models code. class Facility(models.Model): name = models.CharField( max_length=100, validators=[validate_facility_name], unique=True, ) description = models.CharField(max_length=100, validators=[validate_facility_description]) can_be_featured = models.BooleanField(default=False) similarly Hotel model is class Hotels(models.Model): hotel_name = models.CharField( max_length=20, unique=True, validators=[validate_hotel_name] facility = models.ManyToManyField( Facility, related_name='hotel_facility', blank=True, ) featured_facility = models.ManyToManyField( Facility, related_name='featured_hotel_facility', blank=True, ) class Meta: default_permissions = () verbose_name = 'Hotel' verbose_name_plural = 'Hotels' def __str__(self): return self.hotel_name Now I want to add 'featured_facility' only if it is available in 'facility' no new featured facility from Facility can be added in 'featured_facility' I am stucked on querying many to many relationship part? -
Django, Only the view permission works, the rest of the permissions do not
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. -
File upload with Django form
I am trying to upload video files to vimeo, this is my code views.py def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': video_file = request.POST.get("video_file") v = vimeo.VimeoClient( token=token, ) video_uri = v.upload(video_file) print(video_uri) return redirect('home') return render(request, 'forms/video_upload_form.html', {}) template <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file"> <input type="submit" class="button" value="Upload"> </form> but it throws error AttributeError at /upload_to_vimeo/ 'NoneType' object has no attribute 'read' but I can directly upload without a form as follows v = vimeo.VimeoClient( token=token, ) video_uri = v.upload('client_admin/test1.mp4') How I can do it with a form, any help -
Getting all the users name who liked a post in django
I am trying to show the List of Users who Liked a Particular Post. Here is what I have tried but nothing is showing. I have created the post_likes in the views.py and tried to loop through its users in the post-details.html: Here is the post_detail.html template: {% for user in post_likes %} <p>{{ user.username }}f</p> {% endfor %} but nothing is showing. Here is the Post Models.py: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here are the like model.py: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) Here are the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) --------Comment Related Lines-------------------------------- else: comment_form = CommentForm() context["comments"] = comments context["comment_form"] = comment_form context["total_likes"] = total_likes context["liked"] = liked return context def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() if self.request.is_ajax(): context = self.get_context_data(self, *args, **kwargs) html = render_to_string('blog/comments.html', context, request=self.request) return JsonResponse({'form': … -
horizontal multiselect checkboxes in django admin
Hopefully this is a simple fix, although I haven't found anything through searching. I am using this code in admin.py to make my manytomany field appear as checkboxes in admin. class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { models.ManyToManyField: {'widget': CheckboxSelectMultiple}, } But, I have about 10 choices, which is annoying as a vertical list. Is there a way to get the checkboxes to display horizontally or even more flexibly as 2 columns of five choices (or some other arbitrary look)?