Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django - HTML Template get month name from number
I have a number represented month and i want to replace it with month name, date filter not working, as it works with datetime, and i have the field as integer. For sure the value will be between 1 and 12. {{ monthnumber|date:"M" }} Please help. -
Django can start normally, but an error is reported after entering the page [closed]
Pass a class to the template. If there is "models. Imagefield" in the class, an error will be reported.In Django, I used fastdfs to store pictures and database to store hash value of fastdfs Traceback (most recent call last): File "/home/cy/桌面/dailyfresh-master/venv/lib/python3.7/site-packages/django/template/base.py", line 828, in _resolve_lookup current = current[bit] TypeError: 'ImageFieldFile' object is not subscriptable During handling of the above exception, another exception occurred: -
API Design Best Practice: Is it good idea to structure an SQL SELECT query as json-like using json_build_object
I am developing a web-based application that implements the following: serializer to handle data serialization in the backend API view to design and handle API requests in the backend for GET methods, design the SQL SELECT query to have a json-like structure using json_build_object IN DATABASE person(personid, fullname, cityid) city(cityid, cityname, countryid) country(countryid, countryname) IN SERIALIZER personSerializer(id=integerField(), person=charField(), city=integerField()) citySerializer(id=integerField(), name=charField(), country=integerField()) countrySerializer(id=integerField(), name=charField()) IN API VIEW def get(self): query=(""" SELECT p.personid as id, p.fullname as person, json_build_object( 'id',ct.cityid, 'name',ct.cityname, 'country',json_build_object( 'id',cntry.countryid, 'name',cntry.countryname ) ) AS city FROM persons p JOIN city ct ON ct.cityid=p.cityid JOIN country cntry ON cntry.countryid=ct.countryid """) IN FRONTEND const [state, setState] = useState({ personList: [] }) useEffect(()=>{ fetch('/api/persons/', {method: 'GET', headers:{'Content-Type':'application/json'}}) .then(res=>res.json()) .then(rows=>setState(states=>({...states,personList:rows}))) }, []) return( <> <Typography variant="body1" component="p">{state.person}</Typography> <Typography variant="caption" component="p" color="textSecondary">{state.city}, {state.city.country} </Typography> </> ) This is how my API is currently designed. 1. Is this a good, acceptable approach? 2. Will such design pose a future problem in terms of maintainability in case a database structure was changed? -
Tests not running when using django-role-permissions
I am struggling with the following issue for a few days now. The application uses django-role-permissions. Unit tests do not work correctly. Here is the example code: from django.contrib.auth.models import User from django.test import TestCase from rolepermissions.roles import AbstractUserRole class FooRole(AbstractUserRole): available_permissions = { "foo": "bar" } class FooTest(TestCase): def test_bar(self): user = User.objects.create(username="abc") role = FooRole.assign_role_to_user(user) When running the test, the following happens when trying to assign role to user: django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. During handling of the above exception, another exception occurred: MySQLdb._exceptions.OperationalError: (1305, 'SAVEPOINT s4598857152_x2 does not exist') The interesting part is that changing the test to inherit from TransactionTestCase instead of regular TestCast causes the test to work. That's not a great solution for me, as doing this increases the time needed to run all the tests of the system by a factor or 10. Debugging into the database, I see that there is no SAVEPOINT defined since Django does not start a transaction in the database (seen by logging database queries). Any suggestion would be highly appreciated -
Copy and paste the Excel table data into the application and register it in the database
want to do I want to make Web application by Django. I want to use django-funky-sheets for copy and paste the Excel table data into the application and register it in the database. https://github.com/trco/django-funky-sheets About the OrderDetail model described below, I want to paste the Excel data using django-funky-sheets. I can simply paste the Excel data. About ForeignKey, I want to register it as default data, not by django-funky-sheets. What should I do? code # models.py class Order(models.Model): customer = models.CharField(max_length=100) date = models.DateField() class OrderDetail(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) # ←not by django-funky-sheets item = models.CharField(max_length=40) quantity = models.FloatField() unit = models.CharField(max_length=20) unit_price = models.FloatField() amount = models.IntegerField() # views.py class CreateDetailView(HotView): model = Detail checkbox_checked = 'no' checkbox_unchecked = 'yes' action = 'create' template_name = 'sites/detail.html' prefix = 'table' success_url = reverse_lazy('sites:index') fields = ( 'item', 'quantity', 'unit', 'unit_price', 'amount', ) hot_settings = { 'contextMenu': 'true', 'language': 'ja-JP', 'licenseKey':'non-commercial-and-evaluation', 'autoWrapRow': 'true', 'rowHeaders': 'true', 'search': 'true', 'headerTooltips': { 'rows': 'true', 'columns': 'true' }, 'dropdownMenu': [ 'remove_col', '---------', 'make_read_only', '---------', 'alignment' ] }