Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot pass variables between javascript function and ajax in django project
This is a proper noob question it would seem, so apologies, but I can't seem to solve it so I'm reaching out for some assistance. I have a function in my .js file that interacts with the Google Places library to autocomplete a field in a form. I then have an ajax function that runs when you click the submit button which creates variables in the django session. The data of interest to me is lat and long. However, for some reason, I can't seem to get the data to pass from one to the other. I know the ajax function is working because if I type in fixed values they propagate through to django, but I can't seem to get it to update dynamically. const csrf = document.getElementsByName('csrfmiddlewaretoken'); var lat; var lng; function autocomplete_location() { let defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(49.6331, -11.7247), new google.maps.LatLng(59.4850, 1.5906)); let input = document.getElementById('id_your_location'); let options = { bounds: defaultBounds, types: ["address"], fields: ["name", "geometry"], }; let autocomplete = new google.maps.places.Autocomplete(input, options); autocomplete.addListener('place_changed', function() { // Get place info let place = autocomplete.getPlace(); // Do whatever with the value! lat = place.geometry.location.lat() lng = place.geometry.location.lng() console.log(lat) console.log(lng) }) } $(document).ready(function (){ $(".btn").click(function (){ … -
Django q update an already scheduled task
I am using Django-q to schedule a task at a specified date in an object (lets call this bell). I am successfully able to do so using schedule_obj = schedule(func_name, arg1, arg2, arg3, schedule_type=Schedule.ONCE, next_run=bell.date) when there is an update to the obj bell that holds the date, I want to modify this schedule obj with the updated date (bell.date). Is there a way to check if there is a schedule pending for this specific func_name with the args and then access it to modify it? -
How can I get userprofile randomly and add condition?
Here i am trying to get 3 random users and adding them in request user followers, But with the following code , That is getting three users useprofiles randomly including those who already following that profile, i just want to replace those users profiles with those users who don't following request.user so i can add them. #return the count of users who is not following request user all_profiles = UserProfile.objects.all() user_followers = request.user.is_following.all() pk_range = 0 for profile in all_profiles: if not profile in user_followers: pk_range +=1 print(pk_range,) if pk_range >= 3: k1, k2 ,k3 = sample(range(pk_range), 3) f1 = UserProfile.objects.all()[k1] f2 = UserProfile.objects.all()[k2] f3 = UserProfile.objects.all()[k3] userprofile = request.user.userprofile user= request.user user.is_following.add(f1, f2, f3) user.save() if more information or code is require than tell me in a comment session. I will update my question with that information. -
Why is my loop terminating before all items are looped through?
So I'm using Django and trying to dynamically add a users gists to the page using githubs embedded gists. this is the loop {% for i in snippets %} <div class="tile is-4"> <div style="height:25vh;"><script src="https://gist.github.com/{{i.owner.login}}/{{i.id}}.js"/></div> </div> {% endfor %} the list im looping through contains two items, however only the first is added. if I do something along these lines however it correctly displays the two different id's {% for i in snippets %} {{i.id}} {% endfor %} I read that the github script calls document.write(), I have a gut feeling this is where my issue lies. would document.write() break my loop? -
how can i fetch data without refresh page with javascript & django?
i am using django to make API and get data with javasctipt. first time i'm using javascript i don't have very good understanding with javasctipt. i want to get data without refreshing page i am using javacript to fetch data form API. my code is getting data from databse only when i refresh the page. is there way to get data without refreshing page? when anybody create new post then page automatically load the post in index page without refresh the page? index.html <script> async function getPosts() { const Url = 'http://localhost:8000/api/' const Story = document.getElementById('stories') await fetch(Url) .then((res) => res.json()) .then((data) => { data.map((post, index) => { document.getElementById('stories').innerHTML += ` <div class="card card-body mb-3"> <h3>${post.title}</h3> </div> `; }); }) .catch((err) => console.log(err)) } getPosts(); </script> -
AssertionError Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
I want to create a comment api but I get this error: AssertionError at /comment/add/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> this is my view: @api_view() def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) return comment and this is url: path('comment/add/', views.AddComent, name='add_comment'), -
Passing varibles from API to template in Django
I am working on building a flight price search website as part of a project and have managed to get most of the functionality I require working. Here's what the front-end looks like so far: When users enter in the details, a POST request is sent to an API. API: https://developers.amadeus.com/self-service/category/air/api-doc/flight-offers-search API Python SDK: https://github.com/amadeus4dev/amadeus-python I'm receiving a response from the API; however, am struggling to understand what I should then do with the information received. The next step is to pass the information from the API into a search results template and split out all of the received flight information, similar to how it is displayed on Sky Scanner: Below is what I have in my views.py so far (currently passing in the whole response, in what I believe is JSON format?) Views.py: def flight_search(request): kwargs = {'originLocationCode': request.POST.get('Origincity'), 'destinationLocationCode': request.POST.get('Destinationcity'), 'departureDate': request.POST.get('Departuredate'), 'returnDate': request.POST.get('Returndate'), 'adults': '1'} try: response = amadeus.shopping.flight_offers_search.get( **kwargs) print(response.data) return render(request, "flightfinder/flight_search.html", { "response": response }) except ResponseError as error: raise error Here is an example response from the API: { "meta": { "count": 2 }, "data": [ { "type": "flight-offer", "id": "1", "source": "GDS", "instantTicketingRequired": false, "nonHomogeneous": false, "oneWay": false, "lastTicketingDate": "2020-11-20", "numberOfBookableSeats": 2, … -
Got AttributeError when attempting to get a value for field `phone` on serializer `UserSerializer`
im trying to create a view to update the extended profile data in one request, using the auth_rest library, but i got this error: Got AttributeError when attempting to get a value for field phone on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'userprofile'. This is my models (UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) phone_whatsapp = models.BooleanField(default=False) def __str__(self): return self.user.username This is the serializer: class UserSerializer(UserDetailsSerializer): phone = serializers.CharField(source="userprofile.phone") phone_whatsapp = serializers.BooleanField(source="userprofile.phone_whatsapp") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('phone','phone_whatsapp',) def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile', {}) phone = profile_data.get('phone') phone_whatsapp = profile_data.get('phone_whatsapp') instance = super(UserSerializer, self).update(instance, validated_data) # get and update user profile profile = instance.userprofile if profile_data and phone and phone_whatsapp: profile.phone = phone profile.phone_whatsapp = phone_whatsapp profile.save() return instance i modified some things, but i dont be able to fix it. anyone can helpme? thanks in advance -
How can I update the email address using the confirmation code in Django?
I use all the functionalities of dj-rest-auth to register, log in, confirm the email address, change the password, reset the password and many more. Unfortunately, the library does not support changing the email address. I would like the authenticated user to first enter the account password and the new email address. After the successful process of authentication, I would like to send the user a specially generated confirmation code. Only when he enters it, the old email address will be changed to the new one. As far as I know, there is no such functionality in dj-rest-auth. Unfortunately, I also have not found any current solutions or libraries for this purpose anywhere. Has anyone had a similar problem and could share solution here? Thank you in advance. -
How to iterate through all foreign keys pointed at an object in Django without using _set notation?
I am fairly new to Django, but I am working on an application that will follow a CPQ flow or Configure, Price, Quote. The user should select the product they would like to configure as well as the options to go with it. Once selected, the program should query an external pricing database to calculate price. From there the program should output the pricing & text data onto a PDF quote. I was able to get the application working using the specific product inheriting from a base product class. The issue is now that I've created a second product child class, I cannot use a singular "related_name". I've omitted the lists associated with the drop down fields to help with readability, but I've posted my models.py file below. Is there a way I can iterate through Product objects that are pointing to a Quote object with a foreign key? A lot of answers I've found on SO relating to this were able to be solved either by specifying the "_set" or "related_name". I've seen other answers use the select_related() method, however, I can't seem to get the query right as the program won't know which set it needs to look … -
Web Client to Display and Read from SFTP Server in Django Admin
What am I trying to do? I want to allow the user to configure an SFTP server and select the folders that should be downloaded. Following is how I the admin form to look like: Allow the user to configure an SFTP server (host, port, user, pass) from the Django admin On the same page, provide a connect button, which when clicked would connect to the SFTP server using the configuration (Step 1) and open up the SFTP server (either as a modal popup or in a new browser tab/window) The user selects the folders that should be included for parsing and save the admin form. Step 1 is fairly straightforward. However, I am unable to figure out if there's a preexisting module that I use to accomplish step 2 and 3. Basically what I am looking for is a Web SFTP client that I can integrate into my Django admin. I am looking for some guidance in order to achieve this setup. -
Rendering MPTT structure with open/close possibility in django template
I need to render my MPTT model as tree with dropdown (open/close every node that contains children) possibility and buttons that will open/close all the nodes in that tree in 1 click. I tried to find some ready-to-use examples, but best that I found is this: <ul class="navbar-nav mr-auto"> {% recursetree thecategories %} {% if node.level == 0 %} {% if not node.is_leaf_node %} <!-- Let op: <li> tag wordt steeds onderaan aangevuld, ander werkt het niet...--> <li class="dropdown nav-item"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="mainBarItem">{{ node.ctg_Title }}<span class="caret"></span> </span></a> {% else %} <li><a href="#" class="mainBarItem">{{ node.ctg_Title }}</a> {% endif %} {% else %} {% if not node.is_leaf_node %} <li class="dropdown-submenu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="nav-label">{{ node.ctg_Title }}<span class="caret"></span></span></a> {% else %} <li><a href="#">{{ node.ctg_Title }}</a> {% endif %} {% endif %} {% if not node.is_leaf_node %} <ul class="children dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> with some CSS and JS, but it is not that I need. Actually I need to render just one tree at a time. I'm passing variable {{ product }} in my template that is just a root node. And for now … -
How to create json response from django orm annotate?
I want to create sales per month report and send it to the frontend. here is my serializers.py: from .models import Sale from rest_framework import serializers class SaleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sale fields = ['url', 'id', 'date', 'sku', 'product', 'quantity', 'price'] Here is the view from views.py: from django.db.models import Sum from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import SaleSerializer from .models import Sale @api_view() def monthly_sales(request): monthly_sales = Sale.objects.values( 'date__month').annotate(Sum('price')) serializer = SaleSerializer( monthly_sales, many=True, context={'request': request}) return Response(serializer.data) When I go to browser I get the Attribute error: 'dict' object has no attribute 'pk' What's the solution? -
adding multiple values in django path
I have the following paths set up: urlpatterns = [ path("", views.index, name="index"), path('entry/<str:title>', views.entry, name='entry'), ] my entry method is: def entry(request,title): entries = [] entry = util.get_entry(title) if entry != None: entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": title, "entries": entries, }) and in my html we have: {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li> a href = "{% url 'entry' title=entry %}" >{{ entry }}</a> </li> {% endfor %} </ul> {% endblock %} two questions: Is this the right way to pass parameters with a link? What would I need to change to pass multiple parameters? -
Create & Return Token in Serializer
Currently having difficulties returning a token in my registration view. How Can I fix this so that UserSerializer's create can return a token and username? View.py @permission_classes([AllowAny]) class UserCreate(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token, _ = Token.objects.get_or_create(user=user) return Response( { 'username': validated_data['username'], 'token': token.key, }, status=HTTP_200_OK ) Error AttributeError: Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Response` instance. Original exception text was: 'Response' object has no attribute 'username'. [13/Nov/2020 20:26:44] "POST /account/register HTTP/1.1" 500 120116 -
Django login error when using incorrect username and password on AWS
I've spent many hours trying to solve this error but I'm stuck. On my local server, when I try to log in with an incorrect email or password, I get the proper error message from the login view on my HTML template. However on my production server, when I try to sign in with an incorrect email and password I get this error in my browser. I feel like this has something to do with uwsgi. ValueError at /login/ invalid method signature Request Method: POST Request URL: http:// My Public IP Address :8000/login/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: invalid method signature Exception Location: /usr/lib/python3.8/inspect.py, line 1808, in _signature_bound_method Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.5 Python Path: ['.', '', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/startup/django/lib/python3.8/site-packages'] Server time: Fri, 13 Nov 2020 19:55:38 +0000 Code Login HTML <div class="login"> <form action="{% url 'login_new' %}" method="post"> {% csrf_token %} <div> <h1 class="heading_login_signup">Login</h1> {{ form.username.errors }} <label class="label_block_bold_colored_red">Email</label> {{ form.password.errors }} <label class="label_block_bold_colored_red">Password</label> </div> <input class="button" type="submit" value="Login"> </form> <div class="login_error"> {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} </div> <div> Login Views.py def login_new(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) … -
Django Insert With UUID Foreign Keys Issue
I've been building a Django model using UUIDs as foreign keys. When I try to perform an insert the foreign key constraint kicks in stating that the key doesn't exist in the table, which is not true. If I take the query that is trying to be executed from the Django logs it runs fine in my SQL client. I'm using Django 3.1 with Postgresql 12.4 and trying to run the insert via mutation thru Graphene-Django. The model I'm inserting into is: class Inventory(models.Model): class Meta: db_table = "inventory" id = models.UUIDField(db_column='inventory_id', primary_key=True, default=uuid.uuid4()) item = models.CharField(db_column="inventory_item", null=False, max_length=750) quantity = models.FloatField(db_column="inventory_quantity", null=False) org_id = models.ForeignKey("org.Organization", db_column="organization_id", null=False, on_delete=models.CASCADE) unit_of_measure = models.ForeignKey("InventoryUnitOfMeasure", db_column="inventory_uom", null=False, on_delete=models.CASCADE) The query that Django is executing is: INSERT INTO "inventory" ("inventory_id", "inventory_item", "inventory_quantity", "organization_id", "inventory_uom") VALUES ('453b5dd5-1a9c-462f-adff-c93274e45cfe'::uuid, 'test string', 2000.0, 'f119b93a-d3e1-4f2a-8187-0d3f0ff8d148'::uuid, 'cec0c6e1-a0cc-4b38-b4d8-2c00367b9a01'::uuid); Running that query via SQL client works fine, but the error I receive is: insert or update on table "inventory" violates foreign key constraint "inventory_organization_id_7514cdb8_fk_organizat"\nDETAIL: Key (organization_id)=(f119b93a-d3e1-4f2a-8187-0d3f0ff8d148) is not present in table "organization" That key is in the organization table. If the query wasn't running in my SQL client I'd suspect that it's something around translating the UUID string value, but I'm out … -
Are there any certifications associated with DJango?
Hello helpful programmers, I am here to ask one question. Is there any certification associated with DJango? I am learning DJango and want to do a certification to strengthen my resume. Any Ideas? Help is much appreciated! TIA -
manage.py makemessages doesn't work for project's urls.py file
I am running manage.py makemessages --ignore=venv/* -l fr which seems to be running correctly. Every gettext() call is present in the generated django.po files except the main urls.py file's, therefore showing only the English versions of the URLs. Other urls.py files' (within apps) gettext() calls are successfully found and present in django.po files. P.S.: I am aware of the fact that gettext does not support Python's new f-strings, however there is no f-string inside any gettext() call. My main urls.py file looks like this: from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(f'{_("admin")}/', admin.site.urls), path(f'{_("narratives")}/', include('notebook.urls', namespace='narrative')), prefix_default_language=False, ) -
Java 3D ERROR : Canvas3D_createNewContext: Failed in SetPixelFormat
I have the following code in java and I run it in eclipse 2020-09 package pkg3dtest; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.j3d.BranchGroup; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import com.sun.j3d.utils.geometry.ColorCube; import com.sun.j3d.utils.universe.SimpleUniverse; public class Cube3D implements Runnable { SimpleUniverse universe = new SimpleUniverse(); BranchGroup group = new BranchGroup(); ColorCube cube = new ColorCube(0.3); TransformGroup GT = new TransformGroup(); Transform3D transform = new Transform3D(); double Y = 0; Thread hilo1 = new Thread(this); //Se declara el hilo public Cube3D() { GT.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); //se setea el grupo de transformación // como un elemento modificable en tiempo de ejecución hilo1.start(); //se inicia el hilo GT.setTransform(transform); GT.addChild(cube); group.addChild(GT); universe.getViewingPlatform().setNominalViewingTransform(); universe.addBranchGraph(group); } public static void main(String[] args) { new Cube3D(); } //@Override public void run() { Thread ct = Thread.currentThread(); while (ct == hilo1) { try { Y = Y + 0.1; //Variable global declarada como double transform.rotY(Y); //Se rota en base al eje Y GT.setTransform(transform); //Se actualiza el gráfico Thread.sleep(100); //Se espera un tiempo antes de seguir la ejecución } catch (InterruptedException ex) { Logger.getLogger(Cube3D.class.getName()).log(Level.SEVERE, null, ex); } } } } When I give save no error appears but when I run in console the following message appears; DefaultRenderingErrorListener.errorOccurred: CONTEXT_CREATION_ERROR: Renderer: Error creating Canvas3D graphics context graphicsDevice … -
Django Form - Why is the django Multiselect widget used in Admin page rendering in the same line as another field?
In my Django project, I have a form that looks like this: class SpecificPriceForm(forms.ModelForm): tanks = forms.ModelMultipleChoiceField(queryset=AutoTank.objects.all(), widget=FilteredSelectMultiple(verbose_name='Tanques', is_stacked=False)) price = forms.FloatField(label='Precio', required=True, min_value=0.0, max_value=100000.0, widget=forms.TextInput(attrs={'type': 'number'})) initial_date = forms.DateField(widget=DateInput( attrs={'class': 'form-control', 'value': datetime.datetime.now().date()}), label="Fecha inicial") final_date = forms.DateField(widget=DateInput( attrs={'class': 'form-control', 'value': datetime.datetime.now().date() + datetime.timedelta(days=7)}), label="Fecha final") class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) class Meta: model = SpecificPrice fields = ('tanks', 'price', 'initial_date', 'final_date',) def __init__(self, *args, **kwargs): warehouse_type = kwargs.pop('warehouse_type', None) super(SpecificPriceForm, self).__init__(*args, **kwargs) if warehouse_type == 1: self.fields['tanks'].queryset = Station.objects.all() The problem is that in my view, such form displays like this: I don't know why that field is displayed there, and not under the MultiSelect field. It happens when I just include the form as {{ form|crispy }}, and it keeps happening now that I tried to render the fields individually and in different divs, ,with this code: {% block form %} <div class="form-group" style="display: block"> {{ form.media }} {{ form.tanks }} </div> <div class="form-group" style="display: block"> {{ form.price }} {{ form.initial_date }} {{ form.final_date }} </div> {# {{ form|crispy }}#} {% endblock %} Do you know why would be making in render like that? -
How can i show post in django homepage based on post owner
i make a blogger website, every user has their own post that the other can't see it. i want to show the user last post in the homepage(index.html). what i have tried is if the user already had a post it work well, but if the user doesnt have any post yet, when go to homepage it show other user's last post. how to prevent it? what i want is if the user doesnt have any post yet the homepage show some text that tell the user he doesnt have any post yet. here is my code index.html {% extends "blogs/base.html" %} {% block content %} <div class="container jumbotron p-3 p-md-5 text-white rounded bg-dark"> <div class="col-md-6 px-0"> {% if user.is_authenticated %} <h1 class="display-4 font-italic">{{ post_title }}</h1> <p class="lead my-3">{{texts|truncatewords:20}}</p> <p class="lead mb-0"><a href="#" class="text-white font-weight-bold">Continue reading...</a></p> <small><a href="{% url 'blogs:posts' %}" class="text-white ">See all your posts &raquo;</a></small> {%else%} <h1 class="display-4 font-italic">Welcome To Bogger</h1> <p class="lead my-3">This site is used to post your daily stories without having to worry about other people reading them.</p> <a class="btn-lg btn-primary" href="{% url 'users:register' %}" role="button">Register &raquo;</a> {% endif %} </div> </div> {% endblock content %} views.py def index(request): """The Home Page""" post = BlogPost.objects.all() … -
Need help in query set
I am asking this question second time because last time I didn't get proper answer of this question. Well I think its hard to explain that what I am actually trying to do but let me try to explain briefly so you guys can understand better. . Here in a picture you can see there is a list of followers and we can also see the list of followers and following of each follower. I want run this kind to query. I am trying with the following code views.py def get_context_data(self, *args, **kwargs): context = super(FollowerView,self).get_context_data(*args, **kwargs) user = context['user'] user_com = User.objects.get(username=user) myfollowers = user_com.is_following.all() followers_Array =[] followerings_Array =[] for target_list in myfollowers: user_obj = User.objects.get(username=target_list) followers_obj = user_obj.is_following.all() print(followers_obj,'name o ki line') followerings_Array.append(followerings_Array) print(followers_obj,user_obj) followerings_obj = user_obj.userprofile.follower.all() followerings_Array.append(followerings_obj) print(followerings_obj,user_obj) print(followerings_Array,'arry one one one ') context['myfollowers_data']= followers_Array context['myfollowerings_data']= followerings_Array return context Well I am using two arrays in the code but i don't want to use them,right now i am not getting right output by returning arrays in context. If arrays are unnecessary than tell me the other way and tell me how can i show data the way i show you in the picture, I am sharing followers … -
Updated the UserCreationForm and now cannot register
I needed the change the language of the user registration form in Django and created my own but now when I try to register a random person I am getting the http://127.0.0.1:8180/register/submit error. forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class ContactForm(forms.Form): Isim = forms.CharField(max_length=100) Email = forms.EmailField() Mesaj = forms.CharField(widget=forms.Textarea) class CustomUserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("Şifreler aynı değil"), } email = forms.EmailField(label="E-Posta Adresi") password1 = forms.CharField(label=_("Şifre"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Tekrar şifre"), widget=forms.PasswordInput, help_text=_("Lütfen aynı şifreyi girin")) class Meta: model = User fields = ['email', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("Vermiş olduğunuz mail adresiyle bir kayıt bulunmaktadır.") return self.cleaned_data['email'] def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') messages.success(request, f'{email} adına hesap oluşturulmuştur! Giriş yapabilirsiniz!') return redirect('login') else: form = CustomUserCreationForm() context = { "footer": Footer.objects.filter(name="Generic").first(), 'form': form } return render(request, 'member/register.html', context) urls. py from django.urls … -
django not adding element to list
here's what I have: from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect from django.urls import reverse class NewTaskForm(forms.Form): task = forms.CharField(label=‘New Task’) priority = forms.IntegerField(label =‘priority’, min_value=1,max_value=5) Create your views here. def index(request): if "tasks" not in request.session: request.session['tasks'] = [] return render(request, "tasks/index.html", { "tasks": request.session['tasks'] }) def add(request): if request.method == “POST”: task = request.POST.get(‘task’) form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data[“task”] request.session['tasks'] += [task] # or we can try doing it this way # request.session['tasks'] += task return HttpResponseRedirect(reverse("tasks:index")) else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) and then in index.html we have: {% extends ‘tasks/layout.html’ %} {% block body %} <h1>Tasks</h1> <ul> {% for task in tasks %} <li>{{task}}</li> {% empty %} <li>No tasks</li> {% endfor %} </ul> <a href="{% url 'tasks:add' %}">Add a new task</a> {% endblock %} HERE’S THE PROBLEM: if we use request.session[‘tasks’] += [task] where task = ‘abc’ we get in the html abc but if we use: request.session[‘tasks’] += ‘abc’ we get in the html : a b c