Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Replace Django Radio Buttons with PayPal Radio Buttons
Helloo, I am trying to replace my Django Radio buttons for the payment options to be Payal Radio options found in the below link https://developer.paypal.com/demo/checkout/#/pattern/radio I have set my payment options in the forms.py and I am stuck and don't know how to proceed The stripe payment method is working perfectly fine I just want to add the PayPal payment option. This is how my project is arranged: Forms.py PAYMENT_CHOICES = ( ('S', 'Stripe'), ('P', 'Paypal') ) class CheckoutForm(forms.Form): ----address related forms----------------------------------- payment_option = forms.ChoiceField( widget=forms.RadioSelect, choices=PAYMENT_CHOICES) Here is the checokout template <h3>Payment option</h3> <div class="d-block my-3"> {% for value, name in form.fields.payment_option.choices %} <div class="custom-control custom-radio"> <input id="{{ name }}" name="payment_option" value="{{ value }}" type="radio" class="custom-control-input" required> <label class="custom-control-label" for="{{ name }}">{{ name }}</label> </div> {% endfor %} </div> here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } -----------------Shipping address codes----------------------------- payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') else: messages.warning( self.request, "Invalid payment option selected") return redirect('core:checkout') except ObjectDoesNotExist: messages.warning(self.request, "You do not have an active order") return … -
ALTER COLUMN "active" TYPE boolean USING "active"::boolean
I am currently working through "Django 3 By Example" by Antonio Mele. Chapter 3 has me working through creating a blog application. In the chapter it has me change my database from MySQL to PostgreSQL and then migrate the data. When I migrate the data I get this error: **django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to boolean LINE 1: ..." ALTER COLUMN "active" TYPE boolean USING "active"::boolean** I have gone through some PostgreSQL documentation and back through my code but I am unable to complete the migrate due to this error. I have been stuck at this same place for quite some time and can not seem to isolate the correction for the error. Any help is appreciated. -
Django, problem with the comment form below the post
I just can't figure it out for a very long time, I made a conclusion of comments to posts from the admin panel. But I just can't figure out how to make a comment form right under the post for users to comment. Thanks to all! models.py class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) enter code here def __str__(self): return '%s - %s' % (self.post, self.name) form.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('name', 'body') views.py class HomePage(ListView): model = Post template_name = 'main/index.html' context_object_name = 'posts1' class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' -
How to send large post request in flutter
I'm trying to upload my users' contacts to my server (running django-rest-framework) from flutter, but am having a hard time due to the size of the request. The contacts are sent from a screen within a bottom navigation bar, so I would like to request to continue even when the user switches pages (we're using bloc and flutter clean architecture to organize logic). I looked into https://pub.dev/packages/flutter_uploader and multipart uploads but it seems that most are geared towards files rather than json in the post body. The size of the contacts request is partly due to the included avatar images, encoded in base64. I have them as base64 encoded strings because that is easier to parse and deserialize on the server, and I'm not sure how to parse files in django-rest-framework ModelSerializers. Is there any way to upload a large json (List<Map<String, dynamic>>) request to my server so that: The request continues even when the bloc that called the usecase->repository->remotedatasource.dart is recycled when user selects different window in bottom navigation bar. The request contains the images in a way I can process without too much django-rest-framework code and allows me to automatically save the images to s3 as happens automatically … -
issue with public key stripe in Django
Hey I did all good what I could can't find any error or a miss displaced the keys has anybody ever had this issue ? enter image description here -
Filter ForeignKey choices in an Admin Form based on selections in same models ManytoMany Field?
I am making a "matches" model that currently has these fields in them: event = models.ForeignKey(Event, on_delete=models.RESTRICT) match_participants = models.ManyToManyField(Wrestler, on_delete=models.RESTRICT, null=True, blank=True,) match_type = models.CharField(max_length=25, choices=match_choices, default=BLOCK) match_result = models.CharField(max_length=25, choices=result_choices, default=NOT_OC) winner = models.ForeignKey(Wrestler, on_delete=models.RESTRICT, null=True, blank=True, related_name="winner") In my scenario the "winner" can only be one of the foreignkeys chosen in "match_participants", I would really like to filter the winner field to only those chosen foreignkeys. Is this possible? I know you can filter foreign key selections based on entries into other models, but not too sure about same table entry. Here's a UML example of what my database structure currently is: -
Django - Why is my form invalid when a non-required field is not filled?
My form triggers form_invalid when the field "category" is empty. The weird thing is, when the view displays, the "description" field does not have the asterisk indicating it's required, unlike "name" or "enabled", for instance. Also, when I try to send the form with an empty name, it correctly displays a little yellow mark and says "This field is required", but it doesn't say that when the category is empty. So, it seems to correctly recognize that the category is not required, it just says it's invalid after I send the form. My form looks like this: class ProductForm(forms.Form): name = forms.CharField(max_length=80, required=True) category = forms.ModelChoiceField(queryset=None, required=False, label='Categoría') description = forms.CharField(max_length=150, required=False) price = forms.FloatField(required=True) image = forms.ImageField(allow_empty_file=True, required=False) extras = forms.FileField(allow_empty_file=True, required=False) enabled = forms.BooleanField(required=False, initial=True) def __init__(self, user, *args, **kwargs): self.user = user super(ProductForm, self).__init__(*args, **kwargs) self.fields['name'].label = 'Nombre' self.fields['description'].label = 'Descripción' self.fields['price'].label = 'Precio' self.fields['image'].label = 'Imagen' self.fields['extras'].label = 'Extras' categories = Category.objects.filter(store=Profile.objects.get(user=user).store) if categories.count() == 0: self.fields['category'].required = False self.fields['category'].queryset = categories self.fields['enabled'].label = 'Habilitado' It is included to my view in this way: class ProductCreateView(LoginRequiredMixin, CreateView): template_name = 'products/product_form.html' model = Product fields = ["name", "category", "description", "price", "image", "enabled", "extra"] success_url = reverse_lazy("orders:products") And … -
How can i filter a Product by price in DRF
I have a model class Products in which I simple specify product-URL, product-title and product-price as attributes. and make Serializer.py file use ModelSerializer and pass data to Reactjs Now I can't understand that how can i filter products by there price so if I fetch API in react all High price are sorted first or low after according to user need or our option...thanks -
django Pycharm 2020.2.2 not resolving static files when using "pathlib.Path" to address BASE_DIR
I'm using the latest version of Pycharm, 2020.2.2 and django 3.1. In my project, I removed the default settings.py and created a directory named settings, so the whole project root looks like: tsetmc ├── asgi.py ├── celery.py ├── context_processors.py ├── __init__.py ├── settings │ ├── base.py │ ├── __init__.py │ ├── local.py ├── urls.py ├── views.py └── wsgi.py and in the base.py, I defined the static files setting as: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent ... STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'assets/' ] STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' Everything works fine in the browser and the static files are successfully loaded using the {% static %} tag; However, Pycharm can not resolve any of the static files in the templates. I enabled Django Support, set Django project root and settings in the Pycharm settings accordingly and also set the Template Language as Django; but it didn't solve the issue. After some trial-and-error, I found an odd solution; If I use import os and os.path.join() to locate the static paths, instead of from pathlib import Path and /, Pycharm can resolve the static files without any problem. So when … -
How to show files after clicking on certain category on html/django?
I have an html file that outputs a multilevel list. I'm able already able to get the id of that list with an onClick. What I want to do is that once I've clicked on the list element, a table appears with the files from that category. I don't mind if it reloads the page, but it would be better if it's not needed to. This is what my list looks like: <body> <nav id="navigation"> <ul class="parent"> <li class="big-section">Commissions <ul class="child"> <li class="area" id="Pays">Pays</li> <li class="area" id="Quotas">Quotas</li> </ul> </li> <li class="big-section">Store Rank <ul class="child"> <li class="area" id="Store Rank">Store Rank</li> </ul> </li> <li class="big-section">Ranker <ul class="child"> <li class="area" id="Ranker">Ranker</li> </ul> </li> </ul> </div> </body> This is what my table looks like: <table class="documentTable"> <thead> <tr class="headers"> <th>Document</th> <th>Upload Date</th> <th>Summary</th> </tr> <tbody> {% for f in upload %} <tr class="data"> <td> <a href="{{f.file.url}}" download="{{f.file.url}}">{{ f.title }}</a> </td> <td>{{ f.department }}</td> <td> {{ f.date }}</th> <td> {{ f.summary }}</th> </tr> {% endfor %} </tbody> </thead> </table> This is the javascript I'm using to animate the table and get the id of the clicked list item <script> $("li.area").click(function () { console.log($(this).attr('id')); // jQuery's .attr() method, same but more verbose }); $(function () { … -
Javascript Fetch : Error Unexpected token < in JSON at position 0
I am sending a POST request to my Django view. When I run the code in local it works but when I run it on my apache server it gives me a 500 error. Could you help me, please !! This is my code: form.addEventListener('submit', e=>{ e.preventDefault() const baseInput = document.querySelector('#inputbaseform0') if(baseInput.value !== null){ $('#loadMe').modal('show'); let data = {} data['base'] = baseInput.value data['tiempo'] =tiempo.value data['otros'] =otros.value let url = "{% url 'cal' %}"; fetch(url, { method: "POST", credentials: "same-origin", headers: { "X-CSRFToken": document.querySelector('#form0 input').value, "Accept": "application/json", "Content-Type": "application/json" }, body: JSON.stringify(data) }).then(function(response){ return response.json(); }).then(function(data){ console.log('ERROR: ', data.error) baseData = parseFloat(data.base).toFixed(2) deducir.value = data.porciento//porciento $('#loadMe').modal('hide'); }).catch(function (e){ console.log('Error', e); $('#loadMe').modal('hide'); }) } }) }) -
Reverse for 'user-post' not found. 'user-post' is not a valid view function or pattern name
i have created a blog app. when i try to create new posts is shows the following error. i have double check everything. Now i really don't know what to do. urls patterns are urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register,name='register'), path('profile/', user_views.profile,name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('', include('Bblog.urls')), ] [here is my code] https://github.com/coderbang1/Blog/tree/master -
Writing .create() & .update() for multi-level nested serializer in Django
I have Models.py class Zorg(models.Model): name = models.CharField(max_length=100) owner_first_name = models.CharField(max_length=20) owner_last_name = models.CharField(max_length=20) zorg_email_id = models.EmailField(max_length=100) owner_email_id = models.EmailField(max_length=100) open_year_of_zorg = models.CharField(max_length=4) website = models.URLField(max_length=100) base_rating = models.IntegerField(default=2) joined = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.name class Categories(models.Model): zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE, null=True, related_name='categories') category_name = models.CharField(max_length=100) def __str__(self): return self.category_name + ' - ' + str(self.zorg) class Service(models.Model): category = models.ForeignKey(Categories, on_delete=models.CASCADE,null=True, related_name="services") zorg = models.ForeignKey(Zorg, on_delete=models.CASCADE,null=True, related_name="zorg") service_name = models.CharField(max_length=100) time = models.PositiveIntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=False) def __str__(self): return self.service_name + ' in ' + str(self.category) Here's my serializer.py class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service exclude = ['id', 'category', 'zorg'] class CategorySerializer(serializers.ModelSerializer): services = ServiceSerializer(many=True) class Meta: model = Categories fields = ['category_name', 'services'] class ZorgSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True) class Meta: model = Zorg fields = [ 'id', 'name', 'owner_first_name', 'owner_last_name', 'zorg_email_id', 'owner_email_id', 'open_year_of_zorg', 'website', 'base_rating', 'categories', ] I am trying to write .create function for it but I am unable to write the proper create function for the zorg serializer. GET is working just fine and I am getting expected results but POST and PUT is where I am having trouble with multi level depth. This is how I want to pass … -
How to check if there is any yet not executed tasks in Celery
I need to check whether Celery has any yet not executed tasks. I'm writing tests and need to make sure a Celery task is already finished. I don't want to query the broker or do any system calls.. I just want to achieve this using Celery API. My application is Django-based and containerized using Docker. -
How to obtain content_type from a Django Model Class?
I am trying to obtain the ContentType for a django models.Model. Not trying to get the model from a ContentType, which is all I can find in the docs. For example: model_name = 'FooBar' MyModel = apps.get_model('app_xyz', model_name) MyModel <class 'apps.app_xyz.models.FooBar'> How do I get the ContentType of MyModel? The only thing I can figure out to do is set the model_name string to lower and directly query ContentTypes: ct = ContentType.objects.get(model=model_name.lower()) That seems really fragile, and using lower() has a code smell I don't like. I've looked through FooBar's methods, _methods, and __methods to no avail. Thanks! -
i want to make an app that wright and send pdf to my email
I want to make a form that clients can entre they info and I will receive the information in my email in pdf format . -
js function won't run after an uploading process
i know this is a silly question but i cant seems to figure it out, im new in js and i have been trying to implement a tutorial on my website to program a upload progress bar using js and bootstrap the progress bar is working fine but after the process completed the browser supposed to refresh but its not doing anything this is my form <form method="POST" action="." class="needs-validation" enctype='multipart/form-data'> {% csrf_token %} <div class="c_details_img"> <img class="img-fluid" src="{% static 'img/courses/course-details.jpg'%}" alt=""> </div> <div class="shadow-sm p-3 mb-5 mt-4 bg-white rounded"> <div id="videoinput" class=""> {{form.video}} </div> <div id="progressdiv" class="progress d-none" style="height: 2rem;"> <div id="progressbar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">0%</div> </div> </div> </div> <div class="col-lg-4"> <div class="c_details_list shadow-sm p-3 mb-5 bg-white rounded"> <div class="form-group"> <label for="exampleInputEmail1">Title:</label> {{ form.title}} <small id="emailHelp" class="form-text text-muted">(Enter a title that covers the course content comprehensively)</small> </div> <div class="form-group"> <label for="exampleInputEmail1">Description:</label> {{ form.description}} <small id="emailHelp" class="form-text text-muted"> (Be sure to describe the course content briefly)</small> </div> <button id="save_btn" style="width: 100%;height: 3rem;" class="main_btn" type="submit">Save the Course</button> <button id="loading_btn" style="width: 100%;height: 3rem;" class="btn btn-success d-none" type="button" disabled>Uploading...</button> </form> and this is my uploader.js : $(document).ready(function () { $("form").on("submit", function (event) { event.preventDefault(); var formData = new … -
ERROR: No matching distribution found for ipython==7.18.1
I uploaded a Python app to Heroku. In my requirements.txt file I have a line for ipython==7.18.1 but Heroku seems unable to retrieve it, I don't understand whether the problem is with the versions of python and ipython and which version i should use,so they match The complete error thrown is: ERROR: Could not find a version that satisfies the requirement ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1) ERROR: No matching distribution found for ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) -
search field in Django returning blank page?
I'm doing an encyclopedia project with different entries linked on the homepage. I'm also trying to add a search bar to the homepage so if someone searches up an entry that has already been created then they are taken directly to that entry page. Alternatively, if they partially enter the entry name then they will be taken to a search page with a list of close results. views.py def search(request): value = request.GET.get('q','') if(util.get_entry(value) is not None): return HttpResponseRedirect(reverse("entry", kwargs={'entry': value })) else: subStringEntries = [] for entry in util.list_entries(): if value.upper() in entry.upper(): subStringEntries.append(entry) return render(request, "encyclopedia/index.html", { "entries": subStringEntries, "search": True, "value": value }) urls.py path("search/", views.search, name="search") layout.html <form action = "{% url 'search' %}" method="GET"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia" autocomplete="off"> </form><br> For some reason, anytime I enter anything in the search bar it takes me to a blank page and I do not understand why? The annoying thing is, it was working yesterday. When I entered the name of an entry that was already part of the encyclopedia then it would take me to the already existing entry page but it wasn't doing exactly what I wanted it to so I was trying to … -
Can't find .po file after running django-admin.py makemessages -l de command
I ran django-admin.py makemessages -l de but I can't find any .po file in my project directory. I want to translate the registration form to Persian so I went step by step from django book chapter 19 (https://django-book.readthedocs.io/en/latest/chapter19.html). but I got stuck at this step!! this is my models.py from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as __ class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True) def __str__(self): return self.user.username this is my forms.py from django import forms from django.contrib.auth.models import User from .models import UserProfileInfo from django.utils.translation import ugettext_lazy as __ class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = (__('username'),__('email'),__('password')) class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') and this is my template {% extends "basic_app/base.html" %} {% load staticfiles %} {% block body_block %} <div class="container"> <div class="jumbotron"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here</h1> <h3>Just fill out the form.</h3> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ trans user_form.as_p }} {{ trans profile_form.as_p }} <input type="submit" name="" value="Register"> </form> {% endif %} </div> </div> {% endblock %} what should I do?? -
How to get the difference of two values of same column in django
So I have table T in the Postgres database which has day to day values of the users. From that table, I need to find the difference between yesterday's value and today's value of an attribute C of all the users and return the IDs of the users' for which the difference is greater than 10. Can this whole thing be done in one or two queries? The solutions I have in my mind are naive and will need separate queries for each user. -
Django form-wizard: What happens when i omit required template tag
Django Form Wizard docs state that Note that {{ wizard.management_form }} must be used for the wizard to work properly. I know that if i omit it, the request.POST will be missing something along the lines of 'domain-current_step': [0]. Is there anything else that will be missing? -
No data is being returned when I use an inherited Django Rest Framework serializer? It just returns an empty dictionary
I have a serializer that is meant to act as a template for other ModelSerializers. class CountryBasedModelSerializer(ModelSerializer): def __init__(self, data, context): assert 'country' in self.Meta.fields class Meta: model = Country fields = () I want to use it with this, which is the actual serializer which will be called. class CountryBasedProjectSerializer(CountryBasedModelSerializer): class Meta: model = Project fields = ('id', 'country', 'name') I want to use it with this inherited viewset: class CountryBasedViewset(viewsets.ModelViewSet): queryset = None serializer_class = CountryBasedModelSerializer def get_queryset(self): return self.queryset.filter(country_pk=self.request.data["country"]) And this is the actual viewset that will be called: class CountryProjectBasedViewset(CountryBasedViewset): queryset = Project.objects.all() Is there anything that I am clearly doing incorrectly? -
provide large responses to python requests_mock
I am using python requests to to access some apis, recently I learned requests_mock for mocking http responses for testing. The responses from api that I am using are quire large adapter.register_uri('GET', 'http://api.gateway/payment/, text='VERY LARGE TEXT') What is the proper way of passing large response text? -
Passing static path to included template
Is it possible to pass a static path as a variable to an included template? I need to repeatedly include a template on my page but its always with different logos. For example: {% with img={% static 'img/dashboards/belgium_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} {% with img={% static 'img/dashboards/netherlands_flag.svg' %} %} {% include 'dashboards/charts/country_block.html' %} {% endwith %} This doesn't work.. Is there any workaround to this besides creating a model to support an image attribute to each Country instance?