Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image URL not getting redirect to port 8000 of Django while working with React
I am working on a project where backend is Django Rest Framework and frontend is React. I have a Product Screen where I have Product details listed down. In Product Screen I first fetch product object from Redux store and then use that product to render details and also image of the product from the URL. Fetching product object from Redux store: const productDetails = useSelector((state) => state.productDetails); const { error, loading, product } = productDetails; Image Tag: <Image src={product.image} alt={product.name} fluid /> I have setup a setupProxy.js file where I set the target port 8000. SetupProxy.js const { createProxyMiddleware } = require("http-proxy-middleware"); module.exports = function (app) { app.use( "/api", createProxyMiddleware({ target: "http://127.0.0.1:8000", changeOrigin: true, }) ); }; But when I have image uploaded from Django Admin Panel the image url in Product Screen turns out to be: http://localhost:3000/images/sample.jpg instead of: http://localhost:8000/images/sample.jpg How can I fix this issue? -
Error: 'django.db.utils.IntegrityError: NOT NULL constraint failed: base_user.is_superuser'
Hi, I'm creating a registration form in django and this error occured. Tried many things and just came for help Here's my code RegistrationForm class RegistrationForm(UserCreationForm): full_name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Insira o seu nome completo'})) email = forms.EmailField(max_length=255, help_text="Required email", widget=forms.EmailInput(attrs={'class': 'inpt', 'placeholder': 'Insira o seu email'})) password1 = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'inpt', 'placeholder': 'Insira a sua password'})) password2 = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'inpt', 'placeholder': 'Confirme a sua password'})) class Meta: model = User fields = ('full_name', 'email', 'password1', 'password2') UserManager class UserManager(BaseUserManager): def create_user(self, email, full_name, password=None, is_staff=False, is_admin=False, is_superuser=False): if not email: raise ValueError('User must have an email address') if not password: raise ValueError('Users must have a password') user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.full_name = full_name user_obj.save(using=self.db) return user_obj def create_superuser(self, email, full_name, password=None): user = self.create_user( email, password=password, full_name=full_name, is_staff=True, is_admin=True, is_superuser=True ) return user My register view ... context = {} if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form ... By far thank you for your attention! I think the … -
How to fetche the near point (X,Y) object stored in db by filter
I want to fetch the near data. for example in this case id x y 1 243.242 5124.3242 2 143.242 4724.3242 3 240.242 374.3242 4 243.242 1424.3242 I want to get the point near 240,240 in this case 3 is most close to the point. I can do this after fetch the item row by row. However it takes so much time. I want to do this like filter or Q for django model. How can I do this? -
Django PostgreSQL Heroku works correctly on localhost, works on Heroku until database used
There are many similar questions on here, but the solutions have not helped and I cannot find this exact case listed. My project is made with Django and PostgreSQL and deployed on Heroku. When using localhost, everything works well. Deploying to Heroku works and everything works until I make a POST request. The error I get is Server Error (500). I turned on debug in production and got these messages: "connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?" Why would everything work fine on localhost and deploy fine but not work when I begin to use the database? -
Show multi-selected itens when load a edit view
I'm doing a edit form for some data. I'm having problem to pass information to . As you can see in my view, I pass the data to form using "initial" dictionary. VIEWS.PY @login_required def project_detail(request, project_id): if request.method == 'POST': project = get_object_or_404(Project, pk=project_id) form = ProjectDetailForm(project_id, request.POST, instance = project) if form.is_valid(): instance = form.save(commit=False) instance.client = Project.objects.get(pk=project_id).client form.save() messages.success(request,'Projeto modificado') return redirect('projects') else: messages.error(request,'Ocorreu um erro!') else: project = get_object_or_404(Project, pk=project_id) form = ProjectDetailForm(project_id, initial={'modal':project.modal, 'culture':project.culture, 'owner':project.owner, 'value':project.value, 'final_date':project.final_date, 'text':project.text, 'status':project.status, 'farm':project.farm.values()}) return render(request,'project_detail.html',{'form':form}) But doing this, the data is not displaied in . Thinking here, ManyToManyField saves data in lists. I tried iterate this field but still not working and I guess thats not the best way to do this. MODELS.PY class Project(models.Model): modal_types = [('CUSTEIO AGRÍCOLA','Custeio Agrícola'),('CUSTEIO PECUÁRIO','Custeio Pecuário'),('INVESTIMENTO AGRÍCOLA','Investimento Agrícola'),('INVESTIMENTO PECUÁRIO','Investimento Pecuário'),('FGPP','FGPP')] status_opts = [('Análise','Análise'),('Desenvolvimento','Desenvolvimento'),('Processamento','Processamento'),('Liberação','Liberação'),('Finalizado','Finalizado'),('Cancelado','Cancelado'),('Suspenso','Suspenso')] farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='project_bidder',default=None,null=True, verbose_name='Proponente') warranty = models.ManyToManyField(Farm, related_name='project_warranty',default=None, verbose_name='Propriedade de garantia') modal = models.CharField(max_length=100,default=None,choices=modal_types, null=True, verbose_name='Tipo') culture = models.CharField(max_length=50,null=True, verbose_name='Cultura') status = models.CharField(max_length=50,null=True, verbose_name='Status', choices=status_opts) created_date = models.DateField(null=True, verbose_name='Data de criação') value = models.FloatField(max_length=10,null=True, verbose_name='Valor financiado') final_date = models.DateField(default=None,null=True, verbose_name='Fim do contrato') text = models.TextField(default=None,null=True, verbose_name='Observações') … -
How to filter WHERE , OR on django with serializer,model and view?
I'm making a request via GET with the following query: site.org/mymodel?ordering=-created&state=awaiting_review and I have updated to send with multiple states: site.org/mymodel?ordering=-created&state=awaiting_review,phone_screened,interview_scheduled,interview_completed,offer_made,hired,rejected But I have not found a doc in django that specifies how to treat it. So I'm not sure what to do right now. Maybe there is a vanilla option of how to do it. The following codes are a mock of the current ones. What kind of function of part of django/python should I use to receive a filtered query with multiple values ? the current one complains throwing this as response too. { "state": [ "Select a valid choice. awaiting_review,reviewed,phone_screened,interview_scheduled,interview_completed,offer_made,hired,rejected is not one of the available choices." ] } Should I change the URL too ? Model.py: ` class MyModel(): STATE_OPTIONS = ( ("awaiting_review", "awaiting_review"), ("reviewed", "reviewed"), ("phone_screened", "phone_screened"), ("interview_scheduled", "interview_scheduled"), ("interview_completed", "interview_completed"), ("offer_made", "offer_made"), ("hired", "hired"), ("rejected", "rejected"), ) state = models.CharField( max_length=19, choices=STATE_OPTIONS, default="awaiting_review", null=False ) Serializer.py: class ASerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( state ) ` view.py: ` class MyModelView(generics.ListAPIView, ProtectedResourceView): serializer_class = ASerializer filter_fields = ("state") ordering_fields = ("state") def get_queryset(self): return MyModel.objects.filter(user=self.request.user).filter( something_thats_not_state = self.request.query_params.get("something_thats_not_state") ) ` -
Django - Query by foreign key in views
I am trying to make a button on the post that when a user cliks on it, is requesting to be added to the post as an attendance and then, the author of the post has to approve that request. Models.py class Attending(models.Model): is_approved = models.BooleanField(default=False) attending = models.ManyToManyField(User, related_name='user_event_attending') class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) attending = models.ForeignKey(Attending, on_delete=models.CASCADE, verbose_name='atending', null=True) My problem here is that every time I writte a query for the button is giving me erros and I couldn`t figure it out how to get the reverse of the foreign key. This is my code on my views.py def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: query = Attending.objects.get(pk=pk) request_attending = query.post_set.add(request.user) messages.success(request, f'Request sent!') return redirect(previous) except query.DoesNotExist: return redirect('/') Thank you very much for your help in advance! -
symbol not found in flat namespace '_png_do_expand_palette_rgb8_neon' Mac M1 Pycharm error
I am trying to use face_recognition for python in my django project but it does not seem to work as it is giving error when i write import face-recognition I am using it in pycharm, M1 macbook air, django rest framework. Following is the versions Python 3.8 face_recognition 1.3.0 dlib 19.23.0 here is error: ImportError: dlopen(/venv/lib/python3.8/site-packages/_dlib_pybind11.cpython-38-darwin.so, 0x0002): symbol not found in flat namespace '_png_do_expand_palette_rgb8_neon' If anyone can help me solve this error or know any work around to get it working ? -
How to make domain extension in Django
I am making a website, and i want to add an extension for it, like users.example.com. I have searched a lot and came up with nothing. Would I have to create a whole new website, or is there something else that I could do? -
Error sending mail in shell but not in codebase - Django
I have this code in my codebase, I am using Sendgrid: from django.core.mail import send_mail try: mail_sent = send_mail( 'Header', 'Body', 'sender@email.com', ['reciever@email.com'], fail_silently=False) except SMTPException: raise SMTPException() except Exception as e: print('Error sending mail: {0}'.format(e)) And the mail_sent object is ALWAYS 1, which means that the email was sent. Even if I inject an error by changing the sender address. BUT in shell if I run the same send_mail the error is thrown, a 403 forbidden. I have no idea why this is happening but it is messing with my testing. Any thoughts? I am using Docker and have placed my API KEY in the docker-compose file. It seems tha the shell is functioning but the app isn't. -
Trouble with Django ASGI (DAPHNE) Deployment on HEROKU
i've been trying to deploy for the last couple days and I just can't seem to get it working: on heroku , it says application deployed but then when i go into the logs I see errors. I try opening up the app (for example, admin page) and I get application error. I've tried calling the get_asgi_application prior to importing anything else, that didn't work. Here are the errors i recieve: ERROR File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process exited with status 1 State changed from starting to crashed at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myappname.herokuapp.com request_id=18f76666-adff-40f8-83ae-55df56d78208 fwd="24.150.189.187" dyno= connect= service= status=503 bytes= protocol=https my asgi file: import os from django.core.asgi import get_asgi_application import django #from channels.auth import AuthMiddlewareStack #from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter #from .settings import ALLOWED_HOSTS from myappnameapp.routing import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myappname.settings') django.setup() #from django.urls import path django_asgi_app = get_asgi_application() from myappname.auth_middleware import TokenAuthMiddleware application = ProtocolTypeRouter({ # (http->django views is added by default) "http": django_asgi_app, 'websocket': TokenAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) my procfile: release: python manage.py migrate web: daphne myappname.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 SETTINGS … -
relation " " does not exist in Django
I have a doubt what does it mean: relation "clientes" does not exist LINE 1: select nombre from Clientes where joindate between "2022-02-... It seems strange to me; or that this error appears since my model is called Customers; I just did the migrations on heroku, but I get this error In my views I have this: def list_clientes(request): if request.method == 'POST': fromdate=request.POST.get('fromdate') todate = request.POST.get('todate') searchresult=Clientes.objects.raw('select nombre from Clientes where joindate between "'+fromdate+'" and "'+todate+'"') return render(request,'Clientes/clientes-list.html',{'clientes':searchresult}) else: displaydata = Clientes.objects.all() return render(request, 'Clientes/clientes-list.html', {'clientes': displaydata}) models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) nombre = models.CharField(max_length=200) fecha_registro = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.nombre}' settings.py DATABASES = { 'default': { 'ENGINE':'django.db.backends.postgresql_psycopg2', 'NAME':'sistemacarros_db', 'USER':'postgres', 'PASSWORD':'1234', 'HOST':'localhost', 'PORT':'5432', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'", } } } -
How do I filter a Django Model by month or year from a JSON dict?
I am trying to parse through a JSON database and filter by month or by year using Django and this is driving me up a wall since this should be simple. An example of the dict key value pair in the JSON object is formatted as so: "release_date": "2022-12-25T07:00:00", From my views.py file, I set up this function to filter the model: @api_view(['GET']) def yearList(request,pk): queryset = Character.objects.filter(release_date__year=pk) serializer = CharacterSerializer(queryset, many=True) return Response(serializer.data) And in my urls.py, I have this urlpattern (ignoring every other pattern) urlpatterns = [ path('year/<str:pk>', views.CharacterList.as_view(), name="Character by year" ) ] I followed this link to get the idea to append "__year" to the release_date attribute when filtering the queryset. But it's not filtering the database, I'm still seeing all objects. Where am I going wrong? I can't look to filter by months if I can't even get the years filtered, so I'm focusing on the year first. Thank you in advance. -
Extracting data from Django Queryset and inserting into a Python list
I am trying to get one column of data from a Django model into a python list for further processing the in Django view. I have successfully created a simple Django model and populated the data. The fields are: "id", "x_coord", "y_coord". I have run a few commands to extract data from the model. I want to get the values from the "x_coord" field into a Python list so I can then apply the statistics.mean method to all the values. I have had some success in extracting data, see below the Django commands I have issued in the shell, but I can't get the data into a Python list. Any assistance will be appreciated. set environment (in mysite directory) python manage.py shell from polls.models import CC_pts_to_avg temp_list = CC_pts_to_avg.objects.values_list('x_coord',flat=True) >>> temp_list <QuerySet [Decimal('0.60'), Decimal('0.60'), Decimal('0.45'), Decimal('0.60'), Decimal('0.90'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.65'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.75'), '...(remaining elements truncated)...']> >>> >>> temp_list[0] Decimal('0.60') >>> temp_list[2] Decimal('0.45') >>> type(temp_list[0]) <class 'decimal.Decimal'> >>> type(temp_list) <class 'django.db.models.query.QuerySet'> >>> -
problem with a field that expected a number but got another thing
im using django 4.0.2 and making a cart but when i make the check out, i get this error any suggestion to make it work? i appreciate your help i have in checkout.py this code class Checkout(LoginRequiredMixin, View): def post (self, request): addres = request.POST.get('addres') comment = request.POST.get('comment') cart = request.session.get('cart') user= request.session.get('user') product = Product.get_product_by_id(cart) print(addres, comment, User, cart, product ) for product in product: print(cart.get(str(product.id))) order = Order(user_id=user, product=product, price=product.price, addres=addres, comment=comment, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect ('cart:cart_detail') #i have a cart.py code to that have some values, but i can't see where is the problem i'm following some tutorials to do this code. my cart.py from django.conf import settings from product.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product): if str(product.id) not in self.cart.keys(): self.cart[product.id]={ "product_id": product.id, "title":product.title, 'quantity': 1, 'id': int(product.id), "image":product.image.url, "thumbnail":product.thumbnail.url, "price": str(product.price) } else: for key, value in self.cart.items(): if key== str(product.id): value["quantity"] = value["quantity"]+ 1 break self.save() def save(self): self.session["cart"] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def decrement(self, product): … -
How to access Django models outside of Django?
I am trying to access my Django models from a script that will be run outside of any Django views. It will be a standalone script and not related to any Django views etc, however, I would like to be able to use the Django ORM to update fields in the database. My standalone script is in the data directory: I have tried endless suggestions from SO, such as the code below, but I keep hitting a similar issue - "ModuleNotFoundError: No module named 'nft.settings'" import django import sys import os sys.path.append('/Users/chris/Documents/Python/Django/nft/') # This path being the directory at the top of my screenshot os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nft.settings") django.setup() from nft_app.models import Object Any help would be greatly appreciated -
Django - Too many similar queries
I'm creating a music rating app and I'm making a serializer for albums which has many relations and one aggregation method serializer which I think is causing all the trouble. The method gets average and count of reviews for every album. That's how album serializer looks. "id": 2, "title": "OK Computer", "slug": "ok-computer", "created_at": "2022-02-22T21:51:52.528148Z", "artist": { "id": 13, "name": "Radiohead", "slug": "radiohead", "image": "http://127.0.0.1:8000/media/artist/images/radiohead.jpg", "background_image": "http://127.0.0.1:8000/media/artist/bg_images/radiohead.jpg", "created_at": "2022-02-22T00:00:00Z" }, "art_cover": "http://127.0.0.1:8000/media/album/art_covers/ok-computer_cd5Vv6U.jpg", "genres": [ "Alternative Rock", "Art Rock" ], "reviews": { "overall_score": null, "number_of_ratings": 0 }, "release_date": "1997-05-28", "release_type": "LP", "tracks": [ { "position": 1, "title": "Airbag", "duration": "00:04:47" }, { "position": 2, "title": "Paranoid Android", "duration": "00:06:27" } ], "links": [ { "service_name": "spotify", "url": "https://open.spotify.com/album/6dVIqQ8qmQ5GBnJ9shOYGE?si=L_VNH3HeSMmGBqfiqKiGWA" } ], "aoty": null Here is a queryset in album Viewset class AlbumViewSet(ModelViewSet): queryset = Album.objects.prefetch_related("tracks").prefetch_related("album_genres").prefetch_related( "album_links").prefetch_related("reviews").select_related("aoty").select_related("artist_id").all() Here is a method serializer that I use to get the average and count of reviews of certain album def get_avg_and_count_of_reviews(self, album: Album): reviews = Review.objects.only("rating").filter(album_id=album.id).aggregate( overall_score=Avg(F("rating"), output_field=IntegerField()), number_of_ratings=Count(F("rating"), output_field=IntegerField())) return reviews reviews = serializers.SerializerMethodField( method_name="get_avg_and_count_of_reviews") -
i've got error while downloading video from pytube library
i've got error while downloading youtube video via pytube library pytube version is 12.0.0 RegexMatchError at /144p regex_search: could not find match for (?:v=|/)([0-9A-Za-z_-]{11}).* please help me to solve this error. -
Is it possible to use a related field as a choice field in Django?
In Django, if I have something like this: class Library(models.Model): name = models.CharField(...) address = models.CharField(...) book_of_the_week = ? class Book(models.Model): library = models.ForeignKey(Library, on_delete=models.CASCADE, related_name="books") name = models.CharField(...) This gives me the ability to create multiple libraries, each with a large number of books. For book_of_the_week, I want this to be a reference to a Book instance, so that in Django Admin, the field is represented as a dropdown that lets you select from the books in the current library, and in code, you can use .book_of_the_week to access a specific instance of Book. Is this possible? -
Set default url parameter or ignore the none input when nothing is specified - Django Project
I have a list of dictionaries: mylist= [{'Date': '10/2/2021', 'ID': 11773, 'Receiver': 'Mike'}, {'Date': '10/2/2021', 'ID': 15673, 'Receiver': 'Jane'}, {'Date': '10/3/2021', 'ID': 11773, 'Receiver': 'Mike'}, ... {'Date': '12/25/2021', 'ID': 34653, 'Receiver': 'Jack'}] I want to select the rows based on my input date range. I've successfully done this by appending the URL with ?start=val1&end=val2 and I was able to call the input date values from views.py to template.html : Appending the URL with ?start=val1&end=val2 based on my input dates in my HTML <div class="d-sm-flex align-items-center justify-content-between mb-4"> <form method="get" action="/chart/"> <div class="form-row"> <label for="start">Start Date:</label> <div class="col"> <input type="date" class="form-control" name="start" min="2020-01-03" required> </div> <label for="end">End Date:</label> <div class="col"> <input type="date" class="form-control" name="end" min="2020-01-03" required> </div> <button type="submit" class="btn btn-primary"> Generate Report</button> </div> </form> Define start and end in my views.py: start = request.GET.get('start', None) end = request.GET.get('end', None) Select the rows based on the input date range in my views.py: dfmylist = pd.DataFrame(mylist) dfmylist['Date'] = pd.to_datetime(dfmylist['Date']) # you missed this line dfmylistnew = (dfmylist['Date'] > start) & (dfmylist['Date'] <= end) new = dfmylist.loc[dfmylistnew] And I was able to recall the {{new}} in my HTML. The only thing is, when I open the default URL, it shows the error: `Invalid … -
ManyToManyField and ModelMultipleChoiceField not working
I am trying to create an event staff management tool in Django. One part of the data model is that a staff member (class Staff) is linked to a scheduled shift (ScheduledEventShift) via ManyToManyField through StaffShift. Every member of staff can see the shifts available for him / her and select them via ModelMultipleChoiceField. This works perfectly fine and the relation is correctly written to the StaffShift table depending on whether the shift is ticked or not. (sorry the tool is in German, but it should be clear from context what I mean) What I want to do now is "the opposite" of that, i.e. I as an admin want to look at a single shift, see which staff members have applied for that shift and untick those that are "too much" (i.e. 2 required, 3 applied). When using a ModelMultipleChoiceField in that direction, I am able to show all the relevant staff members as a QuerySet but the choices are always unticked and it has no effect whatsoever on the StaffShift table if I tick something. Here the relevant part of my code: models.py: class Staff(models.Model): <...> shifts = models.ManyToManyField(ScheduledEventShift, through='StaffShift', related_name='applied_staff') forms.py: class ScheduledEventShiftEditForm(forms.ModelForm): class Meta: model = … -
How to stop django from inserting column into MySQL if record already exists
Models.py: class signUpUser(models.Model): username = models.CharField(max_length = 100, unique = True) passwd = models.TextField() passwd2 = models.TextField() email = models.EmailField(unique = True) def save(self, *args, **kwargs): if not self.pk: self.passwd = make_password(self.passwd) self.passwd2 = make_password(self.passwd2) super(signUpUser, self).save(*args, **kwargs) class Meta: db_table = "users" views.py def signUp(request): if request.method == "POST": if request.POST.get('username') and request.POST.get('passwd') and request.POST.get('email'): post = signUpUser() post.username = request.POST.get('username') post.passwd = request.POST.get('passwd') post.passwd2 = request.POST.get('passwd2') post.email = request.POST.get('email') post.save() messages.success(request, "Success.") return render(request, "signup.html") signup.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@200&display=swap" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/css/styles.css' %}"> <body style="background-color: rgb(37, 37, 37);"> <script src="{% static 'js/index.js' %}"></script> <title>Document</title> <body class="bkg_signup"> <div id="particles-js"> <div class="top-nav"> <a href="{% url 'hpage' %}">HOME</a> <a href="{% url 'prodpage' %}">PRODUCTS</a> <a href="{% url 'cpage' %}">CONTACT</a> <a href="{% url 'apage' %}">ABOUT</a> <a style="float: right;" href="{% url 'lpage' %}">LOGIN</a> <a style="float: right;" href="{% url 'spage' %}">SIGN UP</a> </div> <div class="item-box2"> <div class="div-align2" style="font-size: 28px;"> <h1 style="margin-right: 40px; color: rgb(255, 255, 255);">Sign Up</h1> </div> <form class="fontmaker" method="post" action="{% url 'signup' %}"> {% csrf_token %} <input style="border-color: black;" class="input-corners" placeholder="Username" type="text" … -
python django smart-selects is not working properly
I have install django-smart-selects but when i add the url in the urls.py url(r'^chaining/', include('smart_selects.urls')), when i run my application after this i got this error from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' so here in django.utils.encoding I didn't find any import force_text so I change it to force_str. I am using django 4.0 -
Django EmailMessgae() Error: MIMEPart.__init__() takes from 1 to 2 positional arguments but 5 were given
This is my views file and this is the screenshot of the error email = EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently=True email.send_mail() -
Payment gateway Integration in django
I am implementing the payment integration in Django and creating api using Django rest framework. Want print response of the sandbox link with the parameter like fullname,email,phone which is coming from frontend. I am getting the data from front end but can't able to pass the parameter in the link. I am not getting that how to pass the parameter in the sandbox link. I replaced '{}' to '{{}}' but this also didn't work. @api_view(['POST']) def user_payment(request): headers = { 'Content-Type': 'application/json' } successUrl= 'https://****/thank.html?test=*' cancelUrl= 'https://*********' serializer = user_payment_detailSerializer(data=request.data) #print(request.data) print(serializer) data=request.data fullName=data['fullname'] email=data['email'] phone = data['phone_number'] sum = data['total_amount'] reques = requests.get(f"https://sandbox.abcd.co.il/server/createPaymentProcess/?pageCode={pageCode}&sum={sum}&successUrl={successUrl}&cancelUrl={cancelUrl}&pageField[fullName]={fullName}&pageField[phone]={phone}&pageField[email]={email}", headers=headers) response_body = reques.text print(response_body) if serializer.is_valid(): pass # serializer.save() return render(request,'home.html')