Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
It is possible to obtain some concrete data using the generic view `ListView`?
It is possible to obtain some concrete data using the generic view ListView? I know how to do it creating my own function, but actually I'm using a ListView to show some data and now, I just simply need to know the value of the last row from one column called data_id. This my actual class: class devData_bbdd_view(LoginRequiredMixin, ListView): template_name = 'data_app/data-bbdd.html' paginate_by = 50 queryset = DevData.objects.order_by('-data_timestamp') context_object_name = 'DevDataList' login_url = reverse_lazy('user_app:login') I thought maybe I can do something like last_row = queryset[-1] And from here obtain the the value of the data_id, but it's totally wrong. I suppose I can seriealize the queryset and then do it, but I suppose too is not the best option. How can I do it? Thank you very much! - 
        
Template not loading and showing a page not found in Django
I have a address form to show in the template but I am getting this error and I can't really find an error with the code. Here is the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/store/shipping_address/ Raised by: store.views.ProductDetailView This is my model class ShippingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) mobile = models.CharField(max_length=12, null=True) def __str__(self): return f'{self.user.username} ShippingAddress' view class ShippingView(CreateView, LoginRequiredMixin): model = ShippingAddress template_name = 'store/product/shipping_form.html' form_class = ShippingForm success_message = 'Added' success_url = reverse_lazy('store:store_home') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) forms class ShippingForm(forms.ModelForm): class Meta: model = ShippingAddress fields = ['address','city','state','zipcode','mobile',] urls path('shipping_address/', ShippingView.as_view(), name='shipping_address'), I can't really find the error with the code. Help would be appreciated. Thanks in advance! - 
        
How to Expand collapse div on page load with link?
actually I'm doing a project in Django. HTML template to load a certain post and as well as comments and replies related to that post. <div> <p>{{post_data}}</p> </div> <br> <div id="add"> {% for i in comments%} <div><p>{{i.message}}</p><br><span>{{i.time}}{{i.user}}</span></div> <a class="btn btn-primary" data-toggle="collapse" href="#collapse{{i.pk}}" role="button" aria-expanded="false" aria-controls="collapse{{i.pk}}">Reply</a> <div class="collapse" id="collapse{{i.pk}}"> <form class="my_form_rep" action="{% url 'b' %}" method="POST"> {% csrf_token %} <input id="rep" required minlength="5" name="message" type="text"><br> <input type="hidden" name="parent" value="{{i.pk}}"><br> <button class="click" title="add your reply" type="submit">Reply Comment</button> </form> </div> <br> <a class="links" role="button" data-toggle="collapse" href="#collapse_rep{{i.pk}}" aria-expanded="false" aria-controls="collapse_rep{{i.pk}}">View {{i.comment.all.count}} Reply Comments</a> <div id="collapse_rep{{i.pk}}" class="rep_comm{{i.pk}} collapse"> {% for j in i.comment.all %} <div id="reply{{j.pk}}" style="margin-left:50px;"><p>{{j.replie_msg}}</p><br><span>{{j.time}}{{j.replie_user}}</span></div> {% endfor %} </div> {% endfor %} </div> <div> <form id="my_form" action="{% url 'a' pk=id %}" method="POST"> {% csrf_token %} <input id="in" required minlength="5" name="message" type="text"><br> <button class="click" title="add your comment" type="submit">Comment</button> </form> </div> when the user gets a notification that has someone replied his/her comment and follow the notification link. e.g http://127.0.0.1:8000/post/2#reply154 I'm unable to add a link in the URL to #reply{ReplyComment_primary_keyValue} div because his parent div is collapsed and not expanding when the user clicks on the notification link. - 
        
How to save the value of one form in two fields of the model?
I want the value from the admission form to be saved in the admission and in_stock fields forms.py class AdmissionForm(forms.ModelForm): class Meta: model = Admission fields = ['date', 'name', 'admission', 'in_stock'] views.py class AdmissionCreate(View): def get (self, request): form = AdmissionForm() return render(request, 'inventory/addAdmissions.html', context={'form': form}) def post(self, request): form = AdmissionForm(request.POST) if form.is_valid(): form.save() return redirect(admission_list) - 
        
Django Form Create Specified number of form (element) instances and Assign Attributes Dynamically
I have a page on which a user can use a checkbox to select various items (imported from database). Upon the form submission, I want to get a list of items the user selected (I have used checkbox value field as item id) I have done that using TemplateView and overriding the post method. class SelectSaleInvoiceItemsFromSo(TemplateView): template_name = 'salesApp/selectsiitemfromso.html' def get_context_data(self,*args,**kwargs): context = super().get_context_data(*args,**kwargs) context['so'] = get_object_or_404(SaleOrder, pk=self.kwargs['pk']) context['object_list'] = SaleOrderItem.objects.filter(so_number=self.kwargs['pk']) return context def post(self, request, *args, **kwargs): selected_items = request.POST.getlist('selected_items') print(selected_items) #just a test context = self.get_context_data(*args,**kwargs) return self.render_to_response(context) #Just a test my model looks like this class SaleOrderItem(models.Model): so_line_number = models.IntegerField(verbose_name='Line') sale_order_item = models.ForeignKey(Items, on_delete=models.PROTECT,verbose_name='Item') so_number = models.ForeignKey(SaleOrder, on_delete=models.CASCADE) so_quantity = models.DecimalField(max_digits=14,decimal_places=2,default=0.00,verbose_name='Quantity') sale_price = models.DecimalField(max_digits=14,decimal_places=2,verbose_name='Sale Price') so_tax_rate = models.ForeignKey(TaxRate, on_delete=models.PROTECT) so_item_tax_amount = models.DecimalField(max_digits=14,decimal_places=2,verbose_name='Tax Amount') total_price = models.DecimalField(max_digits=14,decimal_places=2,default=0.00) variation_number = models.IntegerField(default=0) variation_quantity = models.DecimalField(max_digits=14,decimal_places=2,default=0,verbose_name='Variation Quantity') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) def __str__(self): return str(self.so_line_number) and the HTML part looks like this <table class="table table-striped table-sm"> <thead> <tr> <th>Select</th> <th>Line Number</th> <th>Description</th> <th>UoM</th> <th>Quantity</th> <th>Price</th> </tr> </thead> {% if object_list %} <tbody> {% for item in object_list %} <tr> <td> <input type="checkbox" name="selected_items" value={{item.id}}> </td> <td>{{item}}</td> <td>{{item.sale_order_item.item_description}}</td> <td>{{item.sale_order_item.item_uom}}</td> <td>{{item.so_quantity}}</td> <td>{{item.total_price}}</td> </tr> {% endfor %} </tbody> {% endif %} </table> … - 
        
Django forms resize CharField/Textarea fields
I'm currently developing a web app with django and I have some forms where the users can enter a lot of text (up to 5.000 chars). I'm doing this using a CharField in forms.py: from django import forms class text_form(forms.Form): ... longer_text = forms.CharField( max_length=5000, widget=forms.Textarea( attrs={ 'rows':10, 'cols':2, 'data-length':5000, }), help_text='Some help text', label = 'Label Text', required=True ) The problems I'm facing right now (and I couldn't solve them even though I read a lot of related SO question) are: 1) I want the users to see a larger field (multiple rows) where they can insert text. Right now it's about maybe two rows and doesn't resize regardless of what I insert as rows value in attrs. 2) The users should be able to use the Enter key on their keyboard within those textareas to make a linebreak Any ideas how to achieve this? And another thought: Maybe it already works and this is a browser related thing? Thanks! - 
        
how can I fix ManyToManyDescriptor from a lesson class model - view?
I am trying to build a single course platorm where I will only hold lessons units materials where only people with membership will be able to see it , however when I try to do retrieve Lesson.course_allowed_mem_types.all() I got the following error 'ManyToManyDescriptor' object has no attribute 'all' , how can I fix this simple error? class Lesson(models.Model): content_title = models.CharField(max_length=120) content_text = models.CharField(max_length=200) thumbnail = models.ImageField(upload_to='static/xxx/xxx/xxx/xxx') link = models.CharField(max_length=200, null=True) allowed_memberships = models.ManyToManyField(Membership)  def __str__(self): return self.content_title views def get_context_data(self, **kwargs): context = super(bootCamp, self).get_context_data(**kwargs) context['lessons'] = Lesson.objects.all() user_membership = UserMembership.objects.filter(user=self.request.user).first() user_membership_type = user_membership.membership.membership_type course_allowed_mem_types = Lesson.allowed_memberships.all() context['course_allowed_mem_types'] = course_allowed_mem_types return context - 
        
how to manage django formsets
i am using django formset models with three dropdowns from another tableForeingKeywith extra=3lines so i have form like this form image i need formset management that Automatically chooses first dropdwon for the first formsetline and the second for the second like thisimage i tried this def create_order(request,): orderformset = modelformset_factory(order, form=orderForm,extra=3) queryset = order.objects.none() formset = orderformset(request.POST or None,queryset=queryset) if formset.is_valid(): formset.save() return redirect('home') - 
        
Django, is it possible to have a formset factory with two ForeingKey?
How can I set two ForeignKey in a inline formset factory? I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice_commesse and lavorazione fields and subsequently in the inline formset the other fields. - 
        
Django Form Submission button not working
So, I am following code4startup tutorial on how to create a similar to Ubereats app. Right now, I am trying to register a new Restaurant & restaurant owner to the database. I am using a form from Django to handle all the datafields. Everything works fine until I hit the "sign-up" button. My code is SUPPOSED TO POST all the data from the form into the database, then automatically log-in the newly created restaurant owner into the restaurants page. HOWEVER, when i press the sign-up button, nothing happens and instead the sign-up page is reloaded. How can i solve this issue? The tutorial I'm following is from 2017 i think so the django version the author uses is old. Below are some snippets from my code: SIGN-UP HTML (BUTTON ONLY, FORM WORKS OK): <form method="POST" enctype="multipart/form-data" > {% csrf_token %} {{ user_form }} {{ restaurant_form }} <button type="submit">Sign Up</button> VIEWS.py def restaurant_home(request): return render(request, 'restaurant/home.html', {}) def restaurant_sign_up(request): user_form = UserForm() restaurant_form = RestaurantForm() #when submitting data: if request == "POST": user_form = UserForm(request.POST) restaurant_form = RestaurantForm(request.POST, request.FILES) if user_form.is_valid() and restaurant_form.is_valid(): new_user = User.objects.create_user(**user_form.cleaned_data) new_restaurant = restaurant_form.save(commit=False) new_restaurant.user = new_user new_restaurant.save() login(request, authenticate( username = user.form.cleaned_data["username"], password = user.form.cleaned_data["password"] … - 
        
Django add RunSQL operation after adding ForeignKey constraint in migration
I'm using Django 2.1, Python 3.6 and MySQL 8. The database has quite huge table with plenty of big rows, hence migration applied to this table takes hours to complete. I discovered if I remove fulltext index from this table it enables inplace alghorithm of modyfing table - it's muuuch faster. So I need to take advantage of that in Django. I thought about removing fulltext index as first migration operation and create it again after all other operations. operations = [ migrations.CreateModel( name='NewModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'abstract': False, }, ), migrations.RunSQL( ('DROP INDEX fulltext_idx_content ON summarizer_model',), ('CREATE FULLTEXT INDEX fulltext_idx_content ON summarizer_model(content)',), ), migrations.AddField( model_name='model', name='new_model', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='new_models_objects', to='summarizer.new_model'), ), migrations.RunSQL( ('CREATE FULLTEXT INDEX fulltext_idx_content ON summarizer_model(content)',), ('DROP INDEX fulltext_idx_content ON summarizer_model',), ), ] (I quickly 'anonymized' above code snipper, so if there is some logical error then please excuse me - this is not the case here :) ) The problem is that Django migration always put adding ForeignKey constraint as last operation. So after my last RunSQL which creates index back. It makes it very slow operation (copy whole table with new column). Is there a way to overcome it? It … - 
        
Getting None even after selecting option in Django?
What I want to do is get the option that the user selects from my Html select form and then work with it. I've tried accessing those values like print(request.POST.get('variations', None)) and even after selecting option, it's returning None. I am not really understanding why. Can anyone please help me out with this? Thanks in advance! My html form: <form class="form" method="POST" action="{{ object.get_add_to_cart_url }}"> {% csrf_token %} {% for var in object.variation_set.all %} <h5>Choose {{ var.name }}</h5> <select class="form-control mb-4 col-md-4" title="variations"> {% for item in var.itemvariation_set.all %} <option value="{{ item.value }}">{{ item.value|capfirst }}</option> {% endfor %} </select> {% endfor %} <div class="action"> <button class="btn btn-success">Add to Cart</button> <button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button> </div> </form> I want to get what the user has selected and work with them in this view, i.e while adding a product to the cart. My views.py: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user= request.user, ordered=False, ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() print(request.POST.get('variations', None)) messages.success(request, "Product quantity has been updated.") else: order.items.add(order_item) print(request.POST.get('variations', None)) messages.success(request, "Product added to cart.") return redirect("order-summary") else: ordered_date = timezone.now() order … - 
        
Django set images to every single users
I have some problem with displaying pictures in django, trying to do a form of registration so that everyone who wants to upload their picture, everything works but it happens that only the picture of the person who is logged in is displayed and it is assigned to each user displayed def JudgesRegister(request): registered = False if request.method == "POST": user_form = UserForm(data = request.POST) judges_form = JudgesProfileInfo(data = request.POST) if user_form.is_valid() and judges_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() judges = judges_form.save(commit=False) judges.user = user if 'profile_pic' in request.FILES: judges.profile_pic = request.FILES['profile_pic'] judges.save() registered = True else: print(user_form.errors, judges_form.errors) else: user_form = UserForm() judges_form = JudgesProfileInfo() return render(request, 'ksm_app/register_judges.html', {'user_form':user_form, 'judges_form':judges_form, 'registered':registered}) and in html template it looks like this <img src="{{ request.user.judges.profile_pic.url }}" class="img-responsive img-fluid" alt="..."> I would like to do it so that the person who registers as a judge can add his or her photo but then any other person registered as a judge or user could see that person's photo I would appreciate any hint I'm sorry about the form of the questions asked, but I'm still new to this environment - 
        
Django Rest Framework, importing users
I have seen importing User model in Django project as follows from django.contrib.auth.models import User and from django.conf import settings.AUTH_USER_MODEL as User What difference does these make ? I think in both cases we import same user - 
        
How to pass value from a python list to a chart?
I have to pass two separate value, data and label, from a python list to chartjs. Here my stuff: data = [[title], [identifier], [subject], [type], [preview], [isReferencedBy], [licence], [licenseMetadata]] label =["title", "identifier", "subject", "type", "preview", "isReferencedBy", "licence", "licenseMetadata"] merge_dataLabel = dict(zip(label,data)) print(merge_dataLabel) Values in data are the results from a sum, values in label are the corresponding label of each result. To associate each label to the corresponding result I'm using zip with this result: {'title': [309], 'identifier': [309], 'subject': [1], 'type': [309], 'preview': [0], 'isReferencedBy': [0], 'licence': [0], 'licenseMetadata': [0]} Before wasting time to integrate chartjs I tried then to render the result via a template: return render ( request , 'completeness.html' , {'merge_dataLabel': merge_dataLabel}) Template: <ul> {% for item in merge_dataLabel %} <li>{{ item }}</li> {% endfor %} </ul> However only the label are rendered without the relative values. So I think that there's something wrong in what I did. Suggestions? Regards - 
        
Add or change a related_name argument
Django==3.0.6 Below is my attempt to organize tags and tags for admin staff only (django-taggit is used). class SpecialAdminTaggedPost(TaggedItemBase): content_object = models.ForeignKey('Post', on_delete=models.PROTECT, related_name="admin_tagged_post") class Post(models.Model): tags = TaggableManager() # django-taggit admin_tags = TaggableManager(through=SpecialAdminTaggedPost) # django-taggit. This gives the following error: ERRORS: post.Post.admin_tags: (fields.E304) Reverse accessor for 'Post.admin_tags' clashes with reverse accessor for 'Post.tags'. HINT: Add or change a related_name argument to the definition for 'Post.admin_tags' or 'Post.tags'. post.Post.tags: (fields.E304) Reverse accessor for 'Post.tags' clashes with reverse accessor for 'Post.admin_tags'. HINT: Add or change a related_name argument to the definition for 'Post.tags' or 'Post.admin_tags'. System check identified 2 issues (0 silenced). Docs (not sure if it is of any help here): https://django-taggit.readthedocs.io/en/v0.10/custom_tagging.html Could you help me cope with this problem? - 
        
Failed to activate the autocomplete-snippets package - atom text editor
Arguments to CompositeDisposable.add must have a .dispose() method Hide Stack Trace TypeError: Arguments to CompositeDisposable.add must have a .dispose() method at assertDisposable (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:1212754) at CompositeDisposable.add (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:1213722) at Object.consumeProvider (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:162477) at Object.consumeProvider_2 (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:162175) at Provider.provide (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:14:1126065) at ServiceHub.provide (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3290410) at Package.activateServices (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3298696) at Package.activateNow (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3295672) at measure (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3294996) at Package.measure (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3292606) at activationPromise.activationPromise.Promise (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3294856) at new Promise () at Package.activate (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3294799) at PackageManager.activatePackage (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:382285) at o.forEach.e (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:377451) at Array.forEach () at disabledPackagesSubscription.disabledPackagesSubscription.config.onDidChange (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:377435) at emitter.on (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:334486) at Function.simpleDispatch (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:1209208) at Emitter.emit (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:1210649) at Config.emitChangeEvent (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:336974) at Config.setRawValue (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:334214) at Config.set (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:330008) at Config.removeAtKeyPath (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:332031) at Package.enable (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:3292391) at PackageManager.enablePackage (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:11:375149) at HTMLButtonElement.enablementButtonClickHandler (/private/var/folders/15/4dgnxsnj5k39mn623fd_gyv00000gn/T/AppTranslocation/FF815902-9E94-4DF7-B904-5D42105FC052/d/Atom.app/Contents/Resources/app/static/:14:2602116) - 
        
Django `assertNumQueries` showing duplicate queries on deferred field
I am having a strange behaviour that I cannot find out why it's happening. I have a simple queryset with a deferred field, for example Business.objects.filter(id=4).defer('phone') and then I have a test that asserts this: with self.assertNumberQueries(2): b = Business.objects.filter(id=4).defer('phone').first() # 1 query b.phone # 1 query It fails, because it seems to run three queries on that block: the first one when filtering, and two more duplicate queries that come from the b.phone statement (SELECT name ...). Does anyone have any idea why this is happening? - 
        
Django Admin. How to Change position of field labels
I need to work with Persian language.Persian is right aligned so I want the labels of model fields to appear on the right side of the input box. I tried to change the admin page CSS but it didn't work.(I changed "text-aligned" to "right-aligned"). - 
        
Some Buttons and links not working in bootstrap grid
i am barely a front end developer and using readily availble snippets for my front end. Im currently facing an issue whereby buttons and links do not work in my footer, here is some of my code: base.html <!-- Footer Links --> <div class="container" style="padding-top: 30px;"> <!-- Grid row --> <div class="row"> <!-- Grid column --> <div class="col-md-3 col-lg-4"> <!-- Content --> <h6 class="text-uppercase font-weight-bold" style="color: #AAAAAA;">{{settings.sitesettings.CompanySettings.company_name}}</h6> <p style="color: #fff;">{{settings.sitesettings.CompanySettings.company_subtitle}}</p> <hr style="color: white;"> <div> <h6 style="color: #AAAAAA;">{{settings.sitesettings.CompanySettings.company_social_media_title}} </h6> {%for icon in settings.sitesettings.CompanySettings.company_social_media.all%} {%image icon.social_media_icon fill-30x30 as icon%} <a href="google.com"><img src="{{icon.url}}" alt="{{icon.alt}}" style="width:10% ;height:auto;back"/></a> -->#this is not working. {%endfor%} </div> </div> <!-- Grid column --> {%for loop_cycle in settings.sitesettings.CompanySettings.footer_settings.all%} <div class="col-md-2 col-lg-2 col-xl-2"> <!-- Links --> <h6 class="text-uppercase font-weight-bold" style="color: #AAAAAA;">{{loop_cycle.footer_header}}</h6> {%for link in loop_cycle.footer_links.all%} <p> <a href="{%pageurl link.link%}" style="color: #fff;">{{link.link_display_name}}</a> -->#this is somehow working. </p> {%endfor%} </div> {%endfor%} <!-- Grid column --> <!-- Grid column --> <div class="col-md-4 col-lg-3 col-xl-3"> <!-- Links --> <h6 class="text-uppercase font-weight-bold" style="color: #AAAAAA;">Contact</h6> <p style="color: #fff;"> <i class="fa fa-home mr-3"></i> {{settings.sitesettings.CompanySettings.company_address}}</p> <p style="color: #fff;"> <i class="fa fa-envelope mr-3"></i> {{settings.sitesettings.CompanySettings.company_email}}</p> {%for contact in settings.sitesettings.CompanySettings.company_phone.all%} <p style="color: #fff;"> <i class="fa fa-phone mr-3"></i> {{contact.phone}}</p> <p> {%endfor%} </div> <!-- Grid column --> </div> <!-- Grid row --> <!-- Copyright … - 
        
How to get values from multiple models and filter based on calculation of those values in Django
I have 4 models and i want to make calculation and then filter based on different values from all models: class Profiles(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class Year20(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class Year19(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class Faculty(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) acting=models.DecimalField(decimal_places=2,max_digits=1000) cooking=models.DecimalField(decimal_places=2,max_digits=1000) I applied ManyToManyField as class Profiles relates to all other 3. I am new to Djnago and I do not know how far that is right. If not please let me know- what is the best and effecient way to organise it. score_19=Year19.objects.annotate( final_grade=F('math') / F('english')).filter(final_grade__gt=61,) Is calculation based on values from one tables-model i want to get final score which is : math_avrg=(year19.math+year20.math)/2 eng_avrg=(year19.eng+year20.eng)/2 final_score=(math_avrg+eng_avrg+acting)/3 which is not code but math claculation that works within view in function. I want to filter values based on final_score and then print surname. I previously asked the question but the answer did not work in my case and was quite cumbersome to follow. I would appreciate if you could share some code to asnwer the question. - 
        
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported
I get the following error while running 'python3 manage.py makemigrations': File "/Users/ksina/Documents/src/django/proj/sixerr/sixerr/urls.py", line 27, in url('^auth/', include('django.contrib.auth.urls', namespace='auth')), File "/Users/ksina/Documents/src/django/proj/sixerr/venv/lib/python3.8/site-packages/django/urls/conf.py", line 38, in include raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I'm using django3. My sixerr/urls.py is: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url('', include('sixerrapp.urls')), url(r'^admin/', admin.site.urls), url('^social/', include('social.apps.django_app.urls', namespace='social')), url('^auth/', include('django.contrib.auth.urls', namespace='auth')), # path('auth/', include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my sixerrapp/urls.py is: from sixerrapp import views app_name = 'sixerrapp' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^gigs/(?P<id>[0-9]+)/$', views.gig_detail, name='gig_detail'), url(r'^my_gigs/$', views.my_gigs, name='my_gigs'), url(r'^create_gig/$', views.create_gig, name='create_gig'), url(r'^edit_gig/(?P<id>[0-9]+)/$', views.edit_gig, name='edit_gig'), url(r'^profile/(?P<username>\w+)/$', views.profile, name='profile'), url(r'^checkout/$', views.create_purchase, name='create_purchase'), url(r'^my_sellings/$', views.my_sellings, name='my_sellings'), url(r'^my_buyings/$', views.my_buyings, name='my_buyings'), url(r'^category/(?P<link>[\w|-]+)/$', views.category, name='category'), url(r'^search/$', views.search, name='search'), ] - 
        
Getting values from html select in views.py in Django
I'm newbie in Django and i would like to have a little help please. I want to get the values that users select in the from select options and use that in my views.py. However, I've been unsuccessful. How can I get that values that the users select? Can anyone please help me with this? Thanks in advance! My html: <form class="form" method="POST" action="{{ object.get_add_to_cart_url }}"> {% csrf_token %} {% for var in object.variation_set.all %} <h5>Choose {{ var.name }}</h5> <select class="form-control mb-4 col-md-4" title="variations"> {% for item in var.itemvariation_set.all %} <option value="{{ item.value }}">{{ item.value|capfirst }}</option> {% endfor %} </select> {% endfor %} <div class="action"> <button class="btn btn-success">Add to Cart</button> <!-- <a href="{{ object.get_add_to_cart_url }}" class="btn btn-success">Add to Cart</a> --> <!-- <a href="{{ object.get_remove_from_cart_url }}" class="btn btn-secondary">Remove from Cart</a> --> <button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button> </div> </form> - 
        
Image watermark in model view set in Django RestFrameWork
I am developing a simple django rest framework application using model viewset. First i input image, name and other details and save to postgresql as well as update in google sheets. So i am trying to put watermark of input image in model view set without using any html file. I have gone through watermark package in python but can't grasp it. So can anyone help me in adding watermark of input image using model view set. This is my views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from .models import Article from .serializers import ArticleSerializer from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from rest_framework import generics from rest_framework import mixins from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from django.shortcuts import get_object_or_404 # Create your views here. from PIL import Image from rest_framework.decorators import action from rest_framework.response import Response import gspread from oauth2client.service_account import ServiceAccountCredentials from django.http import HttpResponse, Http404 scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('Review-4016be63eaa5.json', scope) client = gspread.authorize(creds) # Find a workbook by name and open the first sheet # Make … - 
        
Django payments guide
Respected Sir/Mam , I am trying to make my own payment gateway django application.I went through many payment gateway websites like paypal,razorpay.But facing issues like how the proccessing should be and how the workflow should be. I just need to integrate this with my other website , so this is secondary preference.so i need help that how can i create payment gateway django application.Any resources for the same or any online prebuild Github/Gitlab etc repository available. I have some experience in django but i need to do this project within 10 hours.