Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how i can use kwargs in django redirect, i have one error
i want create a redirect django with kwargs for my detail page! i have a comment system and i want redirect to The page where the user is inside. my urls: enter code here from django.urls import path, re_path from .views import blog, detail, posts_by_tag app_name = "blog" urlpatterns = [ re_path('^$',blog, name="blog"), re_path('^(?P<year>[\d+]{1,4})/(?P<month>[\d+]{1,2})/(?P<day>[\d+] {1,2})/(?P<slug>[\w-]+)/$', detail, name= "detail"), re_path('^(?P<tag>[\w-]+)/$',posts_by_tag, name="tag"), ] my detail : def detail(request, slug, year, month, day): post = get_object_or_404(Post,slug=slug, created__year = year, created__month = month, created__day = day) comments = post.comments.filter(active=True) new_comment = None if request.method == "POST": comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() return redirect('blog:detail', kwargs= {'slug':slug,'created__year':year,'created__month' : month, 'created__day' : day,}) else: comment_form = CommentForm() context = { 'post':post, 'comments':comments, 'new_comment':new_comment, 'comment_form':comment_form, } return render(request, 'blog/detail.html', context) my error is : Reverse for 'detail' with keyword arguments '{'slug': 'django-python', 'created__year': '2019', 'created__month': '7', 'created__day': '1'}' not found. 1 pattern(s) tried: ['blog/(?P[\d+]{1,4})/(?P[\d+]{1,2})/(?P[\d+]{1,2})/(?P[\w-]+)/$'] -
issue with passing in params to viewset create method django rest framework: create() argument after ** must be a mapping, not Request
I have a django rest framework viewset with a custom create view that I have created. I want to take in params that are passed into the view with the request and set them as the values for a new object that will be saved. I am getting an error with the parameters that I am passing. this is what my current method looks like: @permission_classes((IsAuthenticated)) def create(self, validated_data): pref = Preference.objects.create(**validated_data) pref.save() return pref and this is the error that I am getting: TypeError at /api/v2/preferences/ create() argument after ** must be a mapping, not Request -
Version conflict when using the delete method of elasticsearch-dsl
So, we're using elasticsearch in our Django project, and we're using the elasticsearch-dsl python library. We got the following error in production: ConflictError(409, '{"took":7,"timed_out":false,"total":1,"deleted":0,"batches":1,"version_conflicts":1,"noops":0,"retries":{"bulk":0,"search":0},"throttled_millis":0,"requests_per_second":-1.0,"throttled_until_millis":0,"failures":[{"index":"events","type":"_doc","id":"KJ7SpWsBZnen1jNBRWWM","cause":{"type":"version_conflict_engine_exception","reason":"[KJ7SpWsBZnen1jNBRWWM]: version conflict, required seqNo [1418], primary term [1]. current document has seqNo [1419] and primary term [1]","index_uuid":"2-fSZILVQzuJE8KVmpLFXQ","shard":"0","index":"events"},"status":409}]}') And with better formatting: { "took": 7, "timed_out": false, "total": 1, "deleted": 0, "batches": 1, "version_conflicts": 1, "noops": 0, "retries": { "bulk": 0, "search": 0 }, "throttled_millis": 0, "requests_per_second": -1.0, "throttled_until_millis": 0, "failures": [ { "index": "events", "type": "_doc", "id": "KJ7SpWsBZnen1jNBRWWM", "cause": { "type": "version_conflict_engine_exception", "reason": "[KJ7SpWsBZnen1jNBRWWM]: version conflict, required seqNo [1418], primary term [1]. current document has seqNo [1419] and primary term [1]", "index_uuid": "2-fSZILVQzuJE8KVmpLFXQ", "shard": "0", "index": "events" }, "status": 409 } ] } The code that produced the error was this call to the dsl delete method: connections.create_connection( hosts=[settings.ELASTICSEARCH_HOST], timeout=20, ) search = EventDocument.search() # The query is made by the django model's id search.query('match', id=self.id).delete() And here's the definition of EventDocument: from elasticsearch_dsl import ( Document, Integer, ) class EventDocument(Document): id = Integer() # other fields Our biggest issue right now is that we don't have access to the server, we got the error through an automated email we configured for errors. So I don't … -
Footer is displayed inside the header
I am using bootstrap 4 attribute, but when the body has big height the footer gets stuck in the middle. Please let me know if there is need for any css code. <header id="fh5co-header" class="fh5co-cover js-fullheight" role="banner"> <div class="overlay"></div> <div class="container"> <div class="row"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} <meta http-equiv="refresh" content="2"> {% endif %} {% block content %} {% endblock %} </div> </div> </header> <footer id="fh5co-footer" role="contentinfo"> <div class="container"> <div class="row copyright"> <div class="col-md-12 text-center"> <p> <small class="block">&copy; 2019 . All Rights Reserved.</small> </p> </div> </div> </div> </footer> </div> -
python3 manage.py runserver ==> django.db.utils.OperationalError: fe_sendauth: no password supplied
I am trying to run a code cloned from github but I am getting following error when I run command python3 manage.py runserver: -
How to add google calendar to my web site by django?
I want to add google calendar to my web site. The user will first click on the button and then google calendar will be displayed to him and after the user has done his work,the changes must save in the database. But I don't know how to do it in django framework!! -
How can I show an image in a radio select with Django?
I am trying to do a radio select or a simple select with Django but I don't get that works. I have tryed something but when I try to print in html with a for to put a img tag near the radio select it doesn't work (The code in html that add the image isn't showing because I haven't done yet due to don't work the "for" in HTML). However with {{profile_form.choice_picture|as_crispy_field}} works fine but I can put url value as an image: html: <form action="{% url 'edit_profile' %}" method="post"> {% csrf_token %} {% for radio in profile_form.picture_choice %} {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> {% endfor %} {{profile_form.choice_picture|as_crispy_field }} {{ user_form|crispy }} {{ profile_form.description|as_crispy_field }} <input class="btn btn-outline-info my-2 my-sm-0" type="submit" value="Guardar"> <a href="{% url 'profile' %}" class="btn btn-primary">Cancelar</a> </form> model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.CharField(default='users/img/default.png', blank=False, null=False, max_length=200) description = models.TextField(max_length=250, blank=True) played_tournaments = models.PositiveIntegerField(default=0) won_tournaments = models.PositiveIntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Picture(models.Model): name = models.CharField(max_length=200, blank=False, null=False, unique=True) image = models.ImageField(upload_to='users/static/users/img', null=False, unique=True) def __str__(self): return str(self.name) forms: class EditProfileForm(forms.ModelForm): images = Picture.objects.all() CHOICES = [(i.image.url, i.name) for i in images] choice_picture = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) class Meta: model = … -
502 Bad Gateway with nginx/1.14.0 (Ubuntu) while deploying django app on app engine
I have successfully deployed my app while following the tutorial on Google cloud platform for deploying django on a standard environment. I have mapped my custom domain to app engine like six hours back so am not sure whether DNS propagation is not complete AND am nolonger using the default .appspot.com in allowed hosts, I have only my domain. What could the issue really be? NB: Am using app engine for my first time thou experience has been a bad one since morning. Fixing error after error. Tutorials should be improved -
change value form after press button (django)
I have a form where when I select my option and press the "Select" button I need to update the form with the data of my selected object. My problem is that when I do my static object the {% for%} already marks me an error because it is not a list. I do not know if this is the correct way to do it. This is running Mysql, django 1.11 and python 2.7.15 views.py def administrador(request): alumno = Alumnos.objects.all() mapa = mapas.objects.all() competencias = Competencias.objects.all() context = { 'alumno': alumno, 'mapa': mapa, 'competencias': competencias } return render(request, 'competencias_app/competencias.html', context) def seleccion(request): alumno = Alumnos.objects.get(pk=request.POST['Nombre']) context = {'alumno': alumno} return render(request, 'competencias_app/competencias.html', context) competencias.html <form action="/seleccion" method="POST"> {% csrf_token %} <div> <select id="carrera" name="Carrera"> <option value="1">TICS</option> <option value="2">Carrera</option> <option value="3">Carrera</option> <option value="4">Carrera</option> <option value="5">Carrera</option> </select> </div> <div> <select id="Alumno" name="Nombre"> {% for alumno in alumno %} <option value="{{alumno.idAlumnos}}">{{alumno.nombre}}</option> {% endfor %} <input type="submit" name="Seleccionar"> </select> </div> <label for="ID">ID</label> <input type="input" name="id" disabled value="{{alumno.idAlumnos}}"><br> <label for="apellidos">Apellidos</label> <input type="input" name="apellidos" disabled value="{{alumno.apellidos}}"><br> <label for="Correo">Correo</label> <input type="input" name="Correo" disabled value="{{alumno.correo}}"><br> </form> the output when press "seleccionar" is Request Method: POST Request URL: http://localhost:8000/seleccion Django Version: 1.11.21 Exception Type: TypeError Exception Value: 'Alumnos' object … -
Can we find namedtuple key on the basis of value?
I want to find the key of a particular value in namedTuple. For example, code = ( (1, 'a 1'), (2, 'a 2'), ) I have 'a 1' with me. I want to find its key (i.e 1). Is there a way to do this? -
My mystyle.css is not working in django index.html
css is not working in django, image and the text are showing, but text didn't get the css effect. i tried at my best, but failed I need to get the css effect to the text in the index.html file, please help me index.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> first app Static Files </title> <link rel="stylesheet" type="text/css" href="{% static 'mystyle.css' %}"/> </head> <body> <h1> This is the photo of Cal</h1> <img src="{% static "Images/cal.jpg" %}" width="400" height="400", alt="oh ohhh!!... Cant display image"/> </body> </html> mystyle.css h1{ color: red, } this is linked with index.html, but not working settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static") ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'first_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'first_project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', … -
Django Connection refused: Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I want to deploy django applications with apache and mod_wsgi on Ubuntu using Virtualbox. When i run python manage.py run server ,it returns " Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? ".I have database with tables in postgresql and I connected the database in settings.py , but it doesnot work. -
Collecting data from a json array using jquery or javscript
I would love to be able to collect the json array data , passed from my Django channels to my templates. What is the best way to go about it using jquery or javascript. async def websocket_connect(self,event): print("connected",event) #await execut the code and waits for it to finis data=self.get_obj() await self.send({ "type":"websocket.accept" "text":json.dumps(content) }) ) def get_obj(self): objects = modelname.objects.all() content={ 'objs':self.objs_to_json(objects) } return content def objs_to_json(objects): result=[] for objs in objects: result.append(self.objects_to_json(objs)) def objects_to_json(objs): return { 'name':objs.name, 'date':objs.str(objs.date), } var data =JSON.parse(e.data); /* how to use for loop to access the jason data and append it todisplay_objects */ -
Uploading large files to Server with resumable option and then server move file to S3
I need to design an architecture in which user can upload a large file e.g 1GB to server using REST API and then a stream open from server that connect with bucket and there should be resume option if in case connection lost. I have used a package name "Django-chunk-upload" but this not satisfy may requirements. -
Integrity error: null value in column violates constraint
I have a ;django view set. I added the create method to my viewset to create new instances and objects to store them. I have 6 fields in the model that include version, path, namespace, value, user_id, and person(ForeignKey) When i open the django rest framework backend page and attempt to create preference, it throws the following error: DETAIL: Failing row contains (20, 1, , , , 1, null). and when i create the object I am adding all of the correct fields so i am not sure why it is throwing null at then end. @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): # switch user_id value with logged in users id queryset = Preference.objects.create() serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) I want to be able to create a new preference without an error. -
Exporting data to a tab delimited file from Django
I have exported a .csv file using the csv library of Python and it has a huge amount of columns and data that I want to be able to tab so its more easy to read. Is there some kind of way to deal with this? I'm guessing something like writerow() but for tabs? For example: Tab One: Name and Emails for people with more than 20 years Tab Two: Name and Emails for people with more than 30 years Tab Three: Name and Emails for people with more than 40 years -
AJAX GET Request Being Ignored
I am brand new to AJAX requests and I am still learning Django, but I have a project where the user enters an Elasticsearch query and then we generate a downloadable document (report) for the user. I have an AJAX request to continuously check on the existence of a file in my form.html file and it doesn't seem to be getting picked up at all. I can tell this because it isn't giving me any alerts and it's just automatically timing out on big requests after ~30 seconds. I tried to write a temporary fix in my views.py that is basically attempting to do what the javascript in form.html is doing, but A) I feel like this isn't the best method to use in production, B) it doesn't feel like a good use of time to essentially re-invent the wheel, and C) I want the user to get some sort of alert or indication on their end that the report is in progress, and then when it's ready to download. How can I modify my code to actually perform the AJAX request? Or why does it appear that the AJAX request isn't working? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', … -
Fetch request on React with redirect in Django is blocked due to CORS
I am trying to use Spotify authentication in my app. The backend works without any problems on its own, but with React I get an error. In React frontend app, there is a button which makes a successful request to my Django app. For Spotify authentication, I have to create a URL and redirect the request to Spotify API. Spotify has a redirect URI which they use to pass authentication code to the user. I have another endpoint in my Django app to process the authentication code. The first endpoint is /api/v1/login and the redirect endpoint is /api/v1/login_complete on my app. The first endpoint redirects the request to https://accounts.spotify.com/authorize?client_id=*** and Spotify redirects it back to the Login Complete endpoint. The process works without any problems when I try it by directly going to /api/v1/login on my browser. On React, however, I get blocked by the following error: Access to fetch at 'https://accounts.spotify.com/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=http://127.0.0.1:8000/api/v1/login_complete&state=STATE&scope=user-top-read' (redirected from 'http://127.0.0.1:8000/api/v1/login') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Firstly, I am using django-cors-headers. I added … -
How to use "LIKE" on "FROM" clause in sql
I am trying to query a specific table based on a user input, and want to query the table that contains that user input as the search_id in the name. For example, the table names are structured as run_000000_search_000000_lda_000000 and I want to get the table that has the same search_id as the on they put in. I know when "LIKE" is used on the Where clause you can get a column with a specific string or int in the name. However, I have found nothing on using it with the "FROM" clause. Specific hardcoded query for search_id 50 SELECT * FROM `run_000044_search_000050_lda_000366`; In summary, how can I get the table that has the same search_id as the one the user put in. Also trying to use the run and lda to form a full table name does not work because there is no noticeable pattern in between the 3 names. -
How to properly use Nested relationships for serializers?
I am trying to display whatever data I have in my CatPerm inside my Category API endpoint. My CatPerm data consists of 'cat', 'permission', and 'description' whereby they are category name, permission and description respectively Current 'Category' API endpoint look: { "name": "Travel", "permission": [ { "description": "Camera is used to take photos" } ] }, This is my desired 'Category' API endpoint look: { "name": "Travel", "permission": [ { "cat": "Travel", "permission": "Internet", "description": "This is a description inside CatPerm" } ] }, models.py class CatPerm(models.Model): cat = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='permissions') permission = models.ForeignKey(Permission, on_delete=models.CASCADE) description = models.TextField() class Category(models.Model): name = models.CharField(max_length=50) permission = models.ManyToManyField(Permission, related_name='category_permissions', through='CatPerm' ) class Permission(models.Model): name = models.CharField(max_length=100) description = models.TextField() platform = models.CharField( max_length=10, choices=PLATFORM_CHOICES, default=BOTH, ) classification = models.CharField( max_length=10, choices=CLASSIFICATION_CHOICES, default=LOW, ) serializer.py class CatPermSerializer(serializers.ModelSerializer): cat = serializers.SlugRelatedField(slug_field='name', read_only=True) permission = serializers.SlugRelatedField(slug_field='name', read_only=True) class Meta: model = CatPerm fields = ("cat", "permission", "description") class CategorySerializer(serializers.ModelSerializer): permission = CatPermSerializer(many=True, read_only=True) class Meta: model = Category fields = ("name", "permission") -
How to Save User Input (Django)
I have a dropdown menu which is populated through the combination of two different object values contact.firstName and contact.lastName. How can I submit these two values separately on POST so I can query them at a later time? This issue arose because I need to handle when a first name or last name is more than one word. views.py if form.is_valid(): obj.contact = request.POST.get('select_contacts') template.html <div class="select"> <select name="select_contacts" id="select_contacts" required> <option value="">Contact</option> % for contact in contacts %} <option value="{{ contact.firstName }} {{ contact.lastName }}" name="selected_contact" id="selected_contact">{{ contact.firstName }} {{ contact.lastName }}</option> {% endfor %} </select> </div> -
Redirect does not redirect in Django
I'm doing a registration for a user using jquery for the event of the register button, although my createUser method correctly registers a user does, not redirect to the indicated page, but paints it by console views.py @csrf_exempt def createUser(request): #if request.method == 'POST': ''' nombres = request.POST.get('nombres') apellidos = request.POST.get('apellidos') email = request.POST.get('email') password = request.POST.get('password') direccion = request.POST.get('direccion') hour = timezone.now() day = timezone.now() myuser=User(password,day,hour,email,nombres,apellidos,direccion) myuser.save() ''' return redirect('http://127.0.0.1:8000/platos/') def platos(request): platos=Plato.objects.all() return render(request,"core/platos.html",{'platos':platos}) urls.py path('register/',views.createUser,name="register"), path('platos/',views.platos,name="platos"), jquery $('#registro').click(function(){ var nombres = $("#exampleInputNombresRegistrarse").val(); var apellidos = $("#exampleInputApellidosRegistrarse").val(); var email = $("#exampleInputEmailRegistrarse").val(); var password = $("#exampleInputPasswordRegistrarse").val(); var direccion=$("#exampleInputDireccionRegistrarse").val(); if (nombres == '' || email == '' || password == '' || apellidos == '' || direccion == '') { alert("Por favor completa todos los campos...!!!!!!"); } else if(email.indexOf('@', 0) == -1 || email.indexOf('.', 0) == -1){ alert("Por favor ingrese un correo válido...!!!!!!"); } else{ alert("Bien hecho "+nombres); $.ajax({ url: "http://127.0.0.1:8000/register/", method: 'POST', // or another (GET), whatever you need data: {'nombres': nombres,'apellidos':apellidos,'email':email, 'password':password,'direccion':direccion }, success: function (data) { // success callback // you can process data returned by function from views.py console.log(data); } }); } }); -
Login required for Django UpdateView
Why am I always able to access the view even if I am not authenticated: from django.contrib.auth.mixins import LoginRequiredMixin class MyClass(LoginRequiredMixin, UpdateView): model = MyModel fields = ['my_field'] template_name = 'my_template.html' def get_success_url(self): messages.success(self.request, 'Update: success') return reverse('my_ns:my_view') def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) Is there something I should add? -
IntegrityError at /cart/update-transaction/0cqydz1f/
Hello am trying to make a transaction pressing submit this is the error am getting IntegrityError at /cart/update-transaction/0cqydz1f/ NOT NULL constraint failed: shopping_cart_transaction.product_id Request Method: GET Request URL: http://localhost:8000/cart/update-transaction/0cqydz1f/ Django Version: 2.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: shopping_cart_transaction.product_id models.py class Transaction(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) token = models.CharField(max_length=120) order_id = models.CharField(max_length=120) amount = models.DecimalField(max_digits=100, decimal_places=2) success = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.order_id class Meta: ordering = ['-timestamp'] views.py @login_required() def update_transaction_records(request, token): # get the order being processed order_to_purchase = get_user_pending_order(request) # update the placed order order_to_purchase.is_ordered=True order_to_purchase.date_ordered=datetime.datetime.now() order_to_purchase.save() # get all items in the order - generates a queryset order_items = order_to_purchase.items.all() # update order items order_items.update(is_ordered=True, date_ordered=datetime.datetime.now()) # Add products to user profile user_profile = get_object_or_404(Profile, user=request.user) # get the products from the items order_products = [item.product for item in order_items] user_profile.ebooks.add(*order_products) user_profile.save() # create a transaction transaction = Transaction(profile=request.user.profile, token=token, order_id=order_to_purchase.id, amount=order_to_purchase.get_cart_total(), success=True) # save the transcation (otherwise doesn't exist) transaction.save() messages.info(request, "Thank you! Your purchase was successful!") return redirect(reverse('accounts:my_profile')) Please help out am stuck here -
Trying to do a RadioSelect or Select with Imagen
I am trying to do a Radio Select or a simple Select with Django but I don't know how to do. I have tryed something but when I try to print in html with a for to put a img tag near the radio select it doesn't work. However with {{profile_form.choice_picture|as_crispy_field}} works fine: Why my "for" in html doesn't work? Is there any better way to do this? html: <form action="{% url 'edit_profile' %}" method="post"> {% csrf_token %} {% for radio in profile_form.picture_choice %} {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> {% endfor %} {{profile_form.choice_picture|as_crispy_field }} {{ user_form|crispy }} {{ profile_form.description|as_crispy_field }} <input class="btn btn-outline-info my-2 my-sm-0" type="submit" value="Guardar"> <a href="{% url 'profile' %}" class="btn btn-primary">Cancelar</a> </form> model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) picture = models.CharField(default='users/img/default.png', blank=False, null=False, max_length=200) description = models.TextField(max_length=250, blank=True) played_tournaments = models.PositiveIntegerField(default=0) won_tournaments = models.PositiveIntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' class Picture(models.Model): name = models.CharField(max_length=200, blank=False, null=False, unique=True) image = models.ImageField(upload_to='users/static/users/img', null=False, unique=True) def __str__(self): return str(self.name) forms: class EditProfileForm(forms.ModelForm): images = Picture.objects.all() CHOICES = [(i.image.url, i.name) for i in images] choice_picture = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) class Meta: model = Profile fields = ['description', ] labels = { 'description': 'Descripción' } views: @login_required() def edit_profile(request): if …