Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Cannot assign "'2'": "Issues.reporter" must be a "User" instance
I am working on a simple "issue tracking" web application as way to learn more about Django. I am using Django 4.1.4 and Python 3.9.2. I have the following classes in models.py (which may look familiar to people familiar with JIRA): Components Issues IssueStates IssueTypes Priorities Projects Releases Sprints Originally I also had a Users class in models.py but now am trying to switch to using the Django User model. (The User class no longer exists in my models.py) I have been studying the following pages to learn how best to migrate to using the Django Users model. Django Best Practices: Referencing the User Model https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#referencing-the-user-model All of my List/Detail/Create/Delete view classes worked fine with all of the above models until I started working on using the Django User class. -- models.py -- from django.conf import settings class Issues(models.Model): reporter = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.RESTRICT, related_name="reporter_id", ) -- issues.py -- class CreateUpdateIssueForm(forms.ModelForm): ... class IssueCreateView(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView): ... form_class = CreateUpdateIssueForm When I try to create a new Issue, the "new Issue" form is displayed normally, but when I save the form I get a Django error with a stack trace I don't understand because it does not have a reference … -
Trying to apply CRUD functionality to python project
So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published. But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button. Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong. these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing: models.py class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 … -
How to connect css/js files to my Django Project?
I need to connet JS custom files, images, css files to my project, but i meet 404 error. REQ asgiref==3.6.0 Django==4.1.4 sqlparse==0.4.3 tzdata==2022.7 MY DIR enter image description here MY SETTINGS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'car_manage', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MY INDEX.HTML FILE {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all"> <script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script> MY URLS from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.get_acc, name='home'), path('code/', views.get_code, name='code'), path('fa_code/', views.get_code_fa, name='fa_code'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) MY VIEWS def get_acc(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): number = form.cleaned_data['number'] cache.set('number', number) Account.objects.create(**form.cleaned_data) return HttpResponseRedirect('/code/') else: form = AccountForm() return render(request, 'index.html', {'form': form}) I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any. When I try to find static with the command: `python manage.py findstatic car_manage/js/jquery-1.10.2.min.js` I see this: WARNINGS: ?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist. Found 'car_manage/js/jquery-1.10.2.min.js' here: C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js I tried to change my settings … -
Django: How to Join One-to-many relationship? / Show joined query in template
I am new in Django. I am trying to make a clone of craiglist. Currently I have to models: Posts and Media (images). One post can have many Media. I want to show first image that was posted by user when they create a post as well as info about post on the index page. Unfortunately I can't properly join Media when I refer to Posts and vice versa. How to properly show post and media instances in index template? Models: class Post(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=1500) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True) price = models.DecimalField(max_digits=12, decimal_places=2) city = models.CharField(max_length=200) class Media(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) name = models.CharField(max_length=500, null=True, blank=True) photo = models.ImageField(upload_to='photo/%Y/%m/%d/', null=True, blank=True) Views: def index(request): posts = models.Media.objects.all() paginator = Paginator(posts, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'aggregator/index.html', {'page': page_obj}) index.html template: {% for media in page %} <div class="col"> <div> <p>Picture</p> </div> <div> <h4><a href="{% url 'show_post' post_id=media.post.id %}">{{ media.post.title|upper }}</a></h4> </div> <div> <h5>{{media.post.price}}$</h5> </div> <div> <h6>{{media.post.city}}</h6> </div> </div> {% endfor %} So again. How to normally join first media related to the posts? Like in the attached screenshot. I found a … -
Why does Boto3 download a file with another name?
I'm working on a project that works when run manually, but putting the code in a docker container changes my file extension. The code with which I am downloading the file is: def download_file(filename): try: s3 = boto3.client('s3') s3.download_file(os.getenv('BUCKET_NAME'), filename,os.getenv('LOCAL_FILE_NAME')) return True, "File downloaded successfully" except Exception as e: return False, str(e) Within the local variables I define the folder where the file will be stored: LOCAL_FILE_NAME = tmp/file_to_process.pdf When doing the test, download the file with the following extension tmp/file_to_process.pdf.50Cansdf tmp/file_to_process.pdf.B0CnBB1d tmp/file_to_process.pdf.A0CaDB1d -
how to use |safe in Rich Text Field with django to json
how to use |safe in Rich Text Field with django to json enter image description here enter image description here **models **``` class Question(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) # image = models.FileField(upload_to = "files/images", blank=True, null=True) # question = models.CharField(max_length=500) question= RichTextField() answer = models.IntegerField() option_one = models.CharField(max_length=500) option_two = models.CharField(max_length=500) option_three = models.CharField(max_length=500 , blank=True) option_four = models.CharField(max_length=500 , blank=True) is_preview = models.BooleanField(default = False) marks = models.IntegerField(default=1) def __str__(self): return self.question def get_questions(self): questions = list(self.raw_questions.all()) random.shuffle(questions) return questions[:self.number_of_questions] class Meta: verbose_name_plural = 'Quizes' views def api_question(request , id): raw_questions = Question.objects.filter(course =id ,is_preview=True) questions = [] for raw_question in raw_questions: question = {} question['id'] = raw_question.id question['question']= raw_question.question # question['image'] = raw_question.question question['answer'] = raw_question.answer question['marks'] = raw_question.marks options = [] options.append(raw_question.option_one) options.append(raw_question.option_two) # options.append(raw_question.image) if raw_question.option_three != '': options.append(raw_question.option_three) if raw_question.option_four != '': options.append(raw_question.option_four) question['options'] = options questions.append(question) random.shuffle(questions) def take_quiz(request , id): Active = Course.objects.all() context = {'id' : id,'active':Active} return render(request , 'quiz2.html' , context) >! html <form @submit.prevent="handleSubmit()"'> ** [[index + 1 ]].[[ question.question|safe ]] ** <br> <div v-for="(option , i) in question.options" style="font-size:18px;"> [[option]]</h4> <p style="text-align: left; color: var(--primary-color);">Prof. AboRashad<br></p> <!--<h5 style="text-align: right; color: var(--primary-color);">created by : AboRashad<br></h5>--> <!--<h2 style="text-align: center; color: … -
Dynamically adding a form to a Django formset with empty_formset value
I am sorry for my poor English. I'm going to implement it by referring to Dynamically adding a form to a Django formset and Add row dynamically in django formset It works! But I want to duplicate the empty_form value and add it to the form I want to add. I tried: <h3>My Services</h3> {{ serviceFormset.management_form }} <div id="form_set"> {% for form in serviceFormset.forms %} <table class='no_error'> {{ form.as_table }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ serviceFormset.empty_form.as_table }} </table> </div> <script> $('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $newform = $("#empty_form").clone(true,true) $("#form_set").append($newform.html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> But it doesn't work. What can I do? thanks in advance. -
django form return Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance
Am working on school database, when I'm trying to submit my django form using pure html form, it throws me an error like this: ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. How can i solve this error please? Am using this method for the first time: class PrimaryCreativeView(LoginRequiredMixin, CreateView): model = Primary fields = ['profilePicture', 'firstName', 'sureName', 'gender', 'address', 'classOf', 'album', 'hobbies', 'dateOfBirth','year', 'name', 'contact', 'homeAddress', 'emails', 'nationality','occupations', 'officeAddress', 'state', 'localGovernments', 'relationship' ] template_name = 'post_student_primary.html' success_url = reverse_lazy('home') def form_valid(self, form): form.instance.user = self.request.user return super (PrimaryCreativeView, self).form_valid(form) so I changed it to this method down below, but I don't know why it throws me this error:ValueError at /primary Cannot assign "'1'": "Primary.album" must be a "PrimaryAlbum" instance. when I submitted the form. How can I solve? And why this error is shown? my Views: def primary_submit_form(request): albums = PrimaryAlbum.objects.filter(user=request.user) if request.method == 'POST': addmisssion_number = request.POST.get('addmisssion_number') profile_picture = request.POST.get('profile_picture', None) first_name = request.POST.get('first_name') sure_name = request.POST['sure_name'] gender = request.POST['gender'] address_of_student = request.POST['address_of_student'] class_Of_student = request.POST['class_Of_student'] album = request.POST['album'] date_of_birth = request.POST['date_of_birth'] nationality_of_student = request.POST['nationality_of_student'] state_of_student = request.POST['state_of_student'] local_government_of_student = request.POST['local_government_of_student'] certificate_of_birth_photo = request.FILES.get('certificate_of_birth_photo') residential_certificate_photo = request.FILES.get('residential_certificate_photo') name = request.POST['name'] contact = request.POST['contact'] address_2 … -
Import "django.urls" could not be resolved from source
from django.urls import path from . import views urlpatterns = [ path("" , views.index, name="index") ] django.urls part Import "django.urls" could not be resolved from source I tried everything but it didn't work can you help i am beginner at this -
Cannot create an account on Heroku
I've tried to create an account on Heroku. I filled form click on CREATE AN ACCOUNT and got the following message: There's a problem Something went wrong. Try again later. Signup sequence: 94e2ea044221 I've tried several days from different computers and using different browsers but without success. Can somebody give me a hand? -
When editing a model in django, it outputs pk foreignkey and not the desired field?
How to output name field and not pk in form? The pk number of the foreignkey of the model is displayed in the input field. The input field is a ChoiceTxtField. forms class ListTextWidget(forms.Select): template_name = 'include/_forms_orders_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class SimpleOrderEditForm(forms.ModelForm): service = ChoiceTxtField(queryset=Service.objects.order_by('-used')) device = ChoiceTxtField(queryset=Device.objects.order_by('-used')) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(SimpleOrderEditForm, self).__init__(*args, **kwargs) status_excluded = ['','-'] self.fields['service'].choices = [(k, v) for k, v in self.fields['service'].choices if k not in status_excluded] self.fields['device'].choices = [(k, v) for k, v in self.fields['device'].choices if k not in status_excluded] class Meta: model = Orders fields = ['device','service'] widgets = {} include/_forms_orders_datalist.html <input id="ajax_input_{{ widget.name }}" list="{{ widget.name }}" autocomplete="off" {% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %}> {% for group_name, group_choices, group_index in widget.optgroups %} {% for option in group_choices %} <span class="badge rounded-pill bg-warning text-dark" id="list-item-{{ widget.name }}" name="list-item-{{ widget.name }}"> {% include option.template_name with widget=option %}</span> {% endfor %} {% endfor %} <datalist id="{{ widget.name }}"> <optgroup label=""> </optgroup> </datalist> models class Orders(models.Model): service = models.ForeignKey('Service', default=1, on_delete … -
Django ManyToMany .add() doesn't add the elements to the created object
This is in my template: <form hx-post="{% url 'orders:create' %}"> {% csrf_token %} {% for service in venue.services.all %} <input type="checkbox" name="services" value="{{ service.id }}"> {{ service.name }}<br> {% endfor %} <button hx-include="[name='id']" type="submit" class="btn btn-primary btn-lg "> <input type="hidden" value="{{ venue.id }}" name="id"> Submit </button> </form> And this is the view: class OrderCreateView(CreateView): model = Order form_class = OrderForm template_name = "orders/order_page.html" success_url = reverse_lazy("orders:success") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["venues"] = Venue.objects.all() return context def form_valid(self, form): if self.request.htmx: # Get the IDs of the chosen services service_ids = self.request.POST.getlist('services') # Set the venue field of the form form.instance.venue = Venue.objects.get(id=self.request.POST.get("id")) # Save the form self.object = form.save() # Add the chosen services to the Order object for service_id in service_ids: service = Service.objects.get(id=service_id) self.object.chosen_services.add(service) return super().form_valid(form) The problem is that the object is being created but only the line with form.instance.venue works, the part where the chosen_services are being added doesn't work, the object is created without any of them. The service_ids variable is populated with the information from the front end, it has the ids that i need, it just doesn't add them to the object. This is models.py: class Order(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, … -
Want to deploy my License Number Plat Detection project with Django
Want to deploy my License Number Plat Detection project with Django I am trying to deploy my License Number Plate Detection Project with Django. I have build this before in Pycharm simple python and now want to deploy in Django as a Web Based with good functionality. But I am stuck in deployment. Can anybody tell how to do this? what's the process. Should i make separate model? funtion or file to perform this task? Thanks Good anwers to solve my problem -
Django ecommerce view that allows add_cart with same product_id but different product_options
I am writing a django ecommerce app that has multiple product options that can be optionally added to the same productid. I am having issues getting the view to recognize the same product with differing product options as separate cart items. I am getting it to work about half the time but only if a productid comes through with no options at all first then a follow on item with added options isnt an issue. If you attempt to add a bare product with no options into the cart with an existing same product id with options it either throws an error code or adds the options to the existing cart item and increments it up views.py def add_cart(request, product_id, quantity=1): product = Product.objects.get(id = product_id) # get the product product_options= request.POST.getlist('option')#gets selected product options # try: cart = Cart.objects.get(cart_id=_cart_id(request)) # get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save()#saves new cart if needed to be created try: cart = Cart.objects.get(cart_id=_cart_id(request)) # get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save()#saves new cart if needed to be created … -
How to connect WebHook Django
I use cryptocurrency payment service https://0xprocessing.com/ It has a WebHook And I want to connect this WebHook myself but I can't connect it I'm doing everything in Django REST API my code looks like this (Here the WebHook connection service works fine, everything comes) What is wrong here and what can I do? models.py class WebHook(models.Model): WebHook = models.JSONField(verbose_name='WebHook') serializers.py class WebHookInfo(serializers.ModelSerializer): class Meta: fields = "__all__" model = webhook views.py class WebHookList(generics.ListCreateAPIView): queryset = WebHook.objects.all() serializer_class = WebHookInfo permission_classes = [AllowAny] urls.py path('pay/webhook/',WebHookList.as_view(), name='webhook'), -
Could not resolve URL for hyperlinked relationship using view name "user-detail"
Been working on my project and ran into this error Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. urls.py from django.urls import path from . import views from django.views.debug import default_urlconf urlpatterns = [ path('', default_urlconf), path('songs/', views.SongList.as_view(), name='song_list'), path('songs/uuid:pk', views.SongDetail.as_view(), name='song_detail'), path('songs/str:name', views.SongDetail.as_view(), name='song_detail'), path('users/', views.UserList.as_view(), name='user_list'), path('users/uuid:pk', views.UserDetail().as_view(), name='user_detail'), path('users/str:name', views.UserDetail().as_view(), name='user_detail'), path('playlists/', views.PlaylistList.as_view(), name='playlist_list'), path('playlists/uuid:pk', views.PlaylistDetail.as_view(), name="playlist_detail"), path('playlists/str:name', views.PlaylistDetail.as_view(), name="playlist_detail"), ]` views.py `from rest_framework import generics from .serializers import SongSerializer, UserSerializer, PlaylistSerializer from .models import Song,User,playlist create views here class SongList(generics.ListCreateAPIView): queryset = Song.objects.all() serializer_class = SongSerializer class SongDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Song.objects.all() serializer_class = SongSerializer lookup_field = 'name' class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'name' class PlaylistList(generics.ListCreateAPIView): queryset = playlist.objects.all() serializer_class = PlaylistSerializer class PlaylistDetail(generics.RetrieveUpdateDestroyAPIView): queryset = playlist.objects.all() serializer_class = PlaylistSerializer lookup_field = 'name'` serializers.py `from rest_framework import serializers from .models import Song, User, playlist class UserSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField( view_name = 'user_detail', many = True, read_only = True ) class Meta : model = User fields = ('id', 'user', 'name', … -
How can I get my custom user model logged in? AuthenticationForm or my own custom login form won't validate
I've created a custom user model, subclassing AbstractUser. I have a registration view, template, and a CustomUserCreationForm that seems to work fine, and can register users no problem via the front end. My issue is getting the user logged in. I can't seem to pass the form validation to authenticate them with. I'm always returned with a None user object With this line for example, I always get None, this failing verification user = authenticate(request, email=email, password=password) # user = User.objects.get(email=email, password=hashed_pass) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("clientcare:portal/dashboard")) else: return render(request, "clientcare/login.html", { "message": "Invalid email and/or password.", 'login_form':LoginForm, }) Forms class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number','password1', 'password2',) class LoginForm(forms.Form): email = forms.EmailField(max_length=100) password = forms.CharField(widget = forms.PasswordInput()) class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('email', 'first_name','last_name' ,'city', 'province','age','gender','phone_number',) Models # Create your models here. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('Users require an email field') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_patient', False) extra_fields.setdefault('is_provider', True) return self._create_user(email, password, **extra_fields) def … -
Why are all booleans in the database true?
I want to validate certain data and then store it as True in the database after validation. But when I click the button after validation, all the data becomes True. But I just want to check all data individually and set it to true. I'm a beginner, it would be great if someone could help me. views.py def approve(request): form = QuesModel.objects.filter(flaag__exact="False") if request.POST.get("next") == "next": form.update(flaag=True) # here all false become true. What I don't want context = {"form": form} return render(request, 'approve.html', context) approve.html <form method="POST" action=""> {% for event in form %} {% if forloop.counter <= 1 %} {% csrf_token %} ..... model.py class Model(models.Model): ..... ..... flaag = models.BooleanField('Aprroved', default=False) -
change some django settings variables on runtime
I read some old answers but there is no way I understand so I want to learn if a new solution found. I use django-rest-framework backend with react. Some apps like mailgun or django-storages variables configured from settings.py like secretkeys or app-ids. So on production, I want that users can enter the keys from admin panel or a form. I try django-constance and django-extra-settings but I can not re-define variables with them. I try to django.conf.settings but there is a warning about alter variables on runtime So is there anyway to re-define a variable in settings.py -
how to link foreign key with to models
I have Class called Item , and this item some time linked to Category and some time linked to SubCategory , class Category(models.Model): name = models.CharField(max_length=255) rank = models.IntegerField() def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.PROTECT,related_name='sub_category') rank = models.IntegerField() def __str__(self): return self.name class Item(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) category = models.ForeignKey(<<-- Category or subCategory -->>, on_delete=models.PROTECT,) I need to link Item with tow models , so i can use sort_by rank field -
redirecionamento para a pagina payents [closed]
Estou com o seguinte problema. Estou integrando o mercado pago SDK juntamente com Django. Quando faço o pagamento com fazer o redirecionamento para a resultpayment. Para ver o código inteiro CLIQUE AQUI.GITHUB Minha views está assim. import json import os import mercadopago from django.conf import settings from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt sdk = mercadopago.SDK(settings.ACCESS_TOKEN) # Create your views here. def home(request): if request.method == 'GET': template_name = 'payments/pages/home.html' context = { 'public_key': os.environ.get('PUBLIC_KEY'), } return render(request, template_name, context) def processpayment(request): if request.method == 'POST': data_json = request.body data = json.loads(data_json) payment_data = { "transaction_amount": float(data["transaction_amount"]), "installments": 1, "payment_method_id": data["payment_method_id"], "payer": { "email": data["payer"]["email"], "identification": { "type": "CPF", "number": "191191191-00", } } } payment_response = sdk.payment().create(payment_data) payment = payment_response["response"] print("status =>", payment["status"]) print("status_detail =>", payment["status_detail"]) print("id =>", payment["id"]) return redirect(f'/pending/?payment_id={payment["id"]}') def resultpayment(request): template_name = 'payments/pages/resultpayments.html' context = { 'public_key': os.environ.get('PUBLIC_KEY'), } return render(request, template_name, context) No terminal fica assim. enter image description here E no navegador fica assim. enter image description here Tentei back_urls do mercado pago dentro da views do django e do javascripts. tentei redirect. tentei render. tentei HttoResponse. tentei windows.location do javascript. todas elas recebem o get do terminal mais … -
Issue with displaying timer which uses django modle attributes
I'm trying to use django to build a phase timer app for myself. I want a timer to run for each phase, then reset to zero and run for the next phase for n-cycles. I've tried asking 'Friend computer' for help but am still struggling. Here's the model. from django.db import models # Create your models here. class Cycle(models.Model): name = models.CharField(max_length=100) instructions = models.TextField() phase_1_time = models.PositiveIntegerField() phase_1_hold_time = models.PositiveIntegerField() phase_2_time = models.PositiveIntegerField() phase_2_hold_time = models.PositiveIntegerField() recovery_time = models.PositiveIntegerField() max_cycles = models.PositiveIntegerField() def __str__(self): return self.name And here's the view ''' View for the cycle app.''' from django.shortcuts import render from .models import Cycle def exercise_list(request): exercises = Cycle.objects.all() return render(request, 'cycles/exercise_list.html', {'exercises': exercises}) def exercise_detail(request, exercise_id): exercise = Cycle.objects.get(id=exercise_id) phase_1_duration = exercise.phase_1_time phase_1_pause_duration = exercise.phase_1_pause_time phase_2_duration = exercise.phase_2_time phase_2_pause_duration = exercise.phase_2_pause_time recovery = exercise.recovery_time max_cycles = exercise.max_cycles return render(request, 'cycles/exercise_detail.html', { 'exercise': exercise, 'phase_1_duration': phase_1_duration, 'phase_1_pause_duration': phase_1_pause_duration, 'phase_2_duration': phase_2_duration, 'phase_2_pause_duration': phase_2_pause_duration, 'recovery': recovery, 'max_cycles': max_cycles, and the html <html> <head> <title>{{exercise.name}}</title> </head> <body> <h1>{{ exercise.name }}</h1> <p>Instructions: {{ exercise.instructions }}</p> <p>Phase 1 Time: {{ exercise.Phase_1_time }}</p> <p>Phase 1 pause Time: {{ exercise.phase_1_pause_time }}</p> <p>Phase2 Time: {{ exercise.Phase_2_time }}</p> <p>Phase 2 pause Time: {{ exercise.phase_2_pause_time }}</p> <p>Long pause Time: … -
Django_Quill not showing css in Django template
Here is output of my admin panel where the input of django quill field is visible admin image but in my html file no styling is seen html image Here is my model.py from django.db import models from django_quill.fields import QuillField class Blog(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) body = QuillField() def __str__(self): return self.title def summary(self): return self.body[:100] def pub_date_pretty(self): return self.date.strftime('%b %e %Y') Here is my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def detail(request, blog_id): blog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog': blog}) Here is my template html code {% extends 'base.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>{% block title %} Detailed Blog {% endblock %}</title> </head> <body> {% block content %} <h1 class="text-center mt-5" id="blogdetailtitle" style="font-size: 3rem">{{ blog.title }}</h1> <h5 class="text-center text-muted mt-2 mb-5">{{ blog.date|date:'F jS Y' }}</h5> <div class="container">{{ blog.body.html | safe }}</div> {% endblock %} </body> </html> I tried all the solutions given in github and here also about .html | safe This isn't issue here I think. What's wrong here... -
MultiSelectField in django dont show only text data but not numbers its showing None
when i try to show the product size data in my template as a number for example 42 i have None as a return value any ideas about this pleas this is what i get MultiSelectField -
Is there a way to hook into DRF ListAPIView to make additional queries for all instances at once?
I am using the Django REST Framework ListAPIView class to represent a collection of model instances and handle pagination automatically. It's great when you have all the data in the queryset or can grab related data with select_related/prefetch_related to add to the same queryset but when you need to gather more data for each model instance in a different way because there is no direct db relationship, you end up making queries for each instance in the serializer, resulting in a n+1 queries problem. Is there a way to hook into ListAPIView at a point where all the instances of the current page being returned are known so that more processing/queries can be done at once to fetch the additional data for all instances and add it to the response? class Gift(models.Models): ... class SearchList(ListAPIView): serializer_class = SearchGiftSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): return Gift.objects.all()