Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django - Javascript) Timer javascript and datetime python variable in html template
I've found a timer countdown in javascript online and it works fine... I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)... These are my piece of codes: views.py import datetime auction = Auction.objects.get(id=id) endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S") startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") template.html <script> // Set the date we're counting down to var countDownDate = new Date("{{endDateFormat}}").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date("{{startDateFormat}}").getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + … -
Django custom command to write a file without debug logging
I have a Django custom command to write csv file. In the code, I use writer = csv.writer(sys.stdout, lineterminator=os.linesep). When I run it with python manage.py write_csv>sample.file, it contains the file content and debug information, like CDLL(libgeos_c.so.1) Library path: 'libgeos_c.so.1' DLL: <CDLL 'libgeos_c.so.1', handle 5609f58baeb0 at 0x7f03df6b2c88> Trying CDLL(libc.so.6) Library path: 'libc.so.6' DLL: <CDLL 'libc.so.6', handle 7f03ea069450 at 0x7f03df6b2b70> System check identified some issues: and also the part of logging: logging.info('finish uploading') is in the file. Is there anything I can do to prevent those debug information write to file? -
Multiprocessing.Pool runs only one process
I have a Django project and I must fill/update the database with data from an external API. For every user, I must update the values for every minute of every day fetched by the external API. As you understand this is a time-consuming process if I pass multiple months. Please note that I make a call for each day, and process the data of the fetched json. After a specific number of requests, I must wait one hour. With all that in mind, I prepared a script that did all the work but it was taking ages to complete so I decided to proceed with multiprocessing. There is a method user_sync(day_list, user) that handles everything and works perfectly. and here are the lines of code that initiate multiprocessing. user_list = User.objects.filter(username__startswith='US') start_date = datetime.datetime(2020, 6, 28, 0, 0, tzinfo=pytz.UTC) end_date = datetime.datetime(2021, 1, 20, 0, 0, tzinfo=pytz.UTC) day_list = create_day_list(start_date, end_date) pool = multiprocessing.Pool() try: part = partial(user_sync, day_list) pool.map(part, user_list) pool.join() except Exception as e: print(e) pool.close() finally: pool.close() print('FINISHED') To my understanding, it should run multiple user_sync methods for every user in parallel but it doesn't Any help or point to the right direction would be much appreciated. -
Why doesn't HTML input type range work in Django
Am trying to play a song with the input type range in html. I made my own music player with HTML and javascript and when django return's a song, javascript handles it and plays it in the player. It loads the songs and even play it but the range doesn't work. I don't think i should use form widgets range since am not trying to submit a form. Am just playing a song. I did the same thing before in Flask and the range worked but in django it's not working. So am no sure if django support input type. I did alot of research i didn't get an answer so am stuck Here are the songs.(When the image is clicked the song plays) {% for song in playlist %} <div class="card" style="width: 17rem; border: none; margin-right: 20px;"> <img src="{{song.song_img.url}}" width="300" height="300" id="img" class="card-img-top" alt="..." onclick="add_data('{{song.id}}','{{song.song_name}}' ,'{{song.song_path.url}}')"> <div class="card-body"> <h5 class="card-text" id="song" ><a href="{{song.song_path.url}}" style="color: black; text-decoration: none; cursor: pointer;">{{song.song_name}}</a></h5> </div> </div> {% endfor %} Here is the html player <div class="own" id="own" style="display: none;"> <div class="buttons"> <div class="prev-track" onclick="prevPlay()"> <i class="fa fa-step-backward fa-2x"></i> </div> <div class="playpause-track" onclick="play()"> <i class="fa fa-play-circle fa-4x" id='pause'></i> </div> <div class="next-track" onclick="nextPlay()"> <i class="fa fa-step-forward … -
UserCreationForm don't return ValidationError
I don't understand why this form don't raise the ValidationError if the input don't contains only letters, what is wrong?, I tried to follow the steps in order to make a custom validation for these inputs but it seems that is not in the right way? class UserRegistrationForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(), help_text='Enter a help text ex: name@example.com') first_name = forms.CharField(widget=forms.TextInput(), help_text='Enter just letters') last_name = forms.CharField(widget=forms.TextInput()) marketing_email = forms.BooleanField(widget=forms.CheckboxInput(), required=False) accept_terms_and_conditions = forms.BooleanField(widget=forms.CheckboxInput()) class Meta: model = User fields = [ 'email', 'username', 'first_name', 'last_name', 'password1', 'password2', 'marketing_email', 'accept_terms_and_conditions' ] error_messages = { 'first_name' : _('First name can contain only letters'), 'last_name' : _('Last name can contain only letters') } def clean_first_name(self): first_name = self.cleaned_data.get('first_name') if not first_name.isalpha(): raise forms.ValidationError( self.error_messages['first_name'], code='first_name_invalid' ) return data def clean_last_name(self): last_name = self.cleaned_data.get('last_name') if not last_name.isalpha(): raise forms.ValidationError( self.error_messages['last_name'], code='last_name_invalid' ) return data template: <div class="form-row"> <div class="form-group col-md-6"> <label for="firstName">First name</label> {% render_field user_update_form.first_name class="form-control" placeholder="John" id="firstName" %} {% for error in user_update_form.first_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} </div> <div class="form-group col-md-6"> <label for="lastName">Last name</label> {% render_field user_update_form.last_name class="form-control" placeholder="Hanks" id="lastName" %} {% for error in user_update_form.last_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} … -
Docker + Django + Vue + Nginx configuration not reading CSS or JS files (Ioading wrong MIME type)
I have been working on a project that uses Django REST Framework for an API with an embedded Vue frontend. The Vue frontend is located within the Django project folder and uses Django templates for authentication. I have been trying to get this project working with Docker using Nginx as the server. I have it mostly working but have been struggling with getting the media and static folders to work properly. In my most recent version, Nginx is able to find them but the browser is giving a warning that they are being read as text/html and have the incorrect MIME type. I already have "include /etc/nginx/mime.types" included in my Nginx conf file, attempted to add a location function for css and js but nothing seems to work. My docker-compose file looks like this: version: '3' services: backend: build: context: ./django command: > sh -c "python3 manage.py wait_for_database && python3 manage.py collectstatic --no-input && python3 manage.py makemigrations && python3 manage.py migrate --no-input && gunicorn django.wsgi -b 0.0.0.0:8000" networks: - django-nginx volumes: - ./django:/app - django-static:/django/static - django-media:/django/media environment: - DB_HOST=db - DB_NAME=keeptrackdb - DB_USER=postgres - DB_PASS=postgres depends_on: - db db: image: postgres:10-alpine environment: - "POSTGRES_HOST_AUTH_METHOD=trust" - POSTGRES_DB=djangodb - POSTGRES_USER=postgres - … -
Using Database VIEW statements in Django
Hopefully just a quick question. I am having some difficulty with using Database VIEW statements in Django. I came across Getting the SQL from a Django QuerySet But its seems all those post are outdated. I have a couple of Postgresql VIEW that i want to use them in django. Models.py class Boookshelf(models.Model): title = models.CharField(max_length=100) id = models.IntegerField(primary_key=True) class Meta: managed = False db_table = "bookshelf" I would like the official Django way of doing this if its exist. Whenever i add this code i cant use in my page. Nothings happen. How do i check if its work or not? I think so i missed something here. PS: IN PSPQL side everything is fine and VIEW bookshelf is ready to use. -
Query ManyToMany models to return number of instance of A that are linked to B and reverse?
I have 2 models (Customers and Orders) with a declared throught models (Customers_Orders) to manage manytomany relationship. But I did'nt understand how to query to have : for one Customer, all its orders: How many orders were made by each customer for one Order, all its customers: How many customers were associated for each order class Customers(SafeDeleteModel): customer_id = models.AutoField("Customer id", primary_key = True) orders = models.ManyToManyField(Orders, through = Customers_Orders, related_name = "CustomersOrders") created_at = models.DateTimeField("Date created", auto_now_add = True) class Orders(SafeDeleteModel): order_id = models.AutoField("Order id", primary_key = True) created_at = models.DateTimeField("Date created", auto_now_add = True) class Customers_Orders(SafeDeleteModel): order = models.ForeignKey("Orders", on_delete = models.CASCADE) customer = models.ForeignKey("Customers", on_delete = models.CASCADE) -
if there are instances of method that user created display them else display a string Django
code: views.py: @login_required(login_url='loginPage') def boardPage(request): if Board.objects.filter(user=request.user).exists(): boards = get_list_or_404(Board, user=request.user) context = {'boards': boards} return render(request, 'tasks/boards.html', context) else: context = {'boards': False} return render(request, 'tasks/boards.html', context) boards.html: {% extends 'tasks/main.html' %} {% block content %} <center>board page<hr> <a href="{% url 'boardAdd' %}">add board</a> <br><br> your boards: <br> <br> {% if boards is false %} <p>you don't have any boards... Have you tried creating one? ;)</p> {% else %} {% for board in boards %} <a href="{% url 'insideBoard' board.id %}">{{board}}<br></a> {% endfor %} {% endif %} <br> <br> <hr> <a href="{% url 'logoutPage' %}">Logout</a> </center> {% if messages %} {% for message in messages %} <u><br>{% if message.tags %} {% endif %}>{{ message }}</u> {% endfor %} {% endif %} {% endblock %} models.py: class Board(models.Model): title = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): title = models.CharField(max_length=200, null=True) done = models.BooleanField(default=False, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE) due_to = models.DateField(null=True, validators=[dateValidation]) def __str__(self): return self.title every time user deletes all of his/her boards or new user visits that page (new users doesn't have any boards yet, they are able to create one … -
Add "\n" or "<b>" to select options in Django Forms
I need to display the values of my form with something like this: Telecomunicaciones y Redes\nIngeniería en Informática <p> Telecomunicaciones y Redes <br>Ingeniería en Informática WHAT I WANT Telecomunicaciones y Redes Ingeniería en Informática HOW IT IS RENDERED -
How to do checks on Django form classes
I'm playing with django forms a little, and trying to check if all form fields correspond to a field of a model through name-checking, this is being done in form constructor function, but i find silly to make such a check on every form instance made so, i would like to do so but on form class. I came to think that to attain it i would need models to be loaded first in django and maybe... to listen to a signal and wait for executing the code once they are loaded, but this is just a suposition. Is there a way to do it??. Any help is welcome. What you'll below on the code section is a form with a basic filtering functionality. FORM CODE : class NoticeFilter(forms.ModelForm): name = forms.CharField(max_length=12, required=False) def checkfields(self): #Check that the form fields are a subset of the model fields #Granting that every field defined here corresponds only to a model field #and has its same name, no aditional input. list_ = [] field_names = set(boundfield.name for boundfield in self) for model_field in self.__class__.Meta.model._meta.get_fields(): list_.append(model_field.name) set(list_) if field_names.issubset(list_): print('You are good to go') else: print('You have one or more fields whose name doesnt … -
Separating development/staging/production media buckets on S3 in Django
We are currently using AWS S3 buckets as a storage for media files in a Django 1.11 project (using S3BotoStorage from django-storages library). The relevant code is here: # storage.py from storages.backends.s3boto import S3BotoStorage class MediaRootS3BotoStorage(S3BotoStorage): """Storage for uploaded media files.""" bucket_name = settings.AWS_MEDIA_STORAGE_BUCKET_NAME custom_domain = domain(settings.MEDIA_URL) # common_settings.py DEFAULT_FILE_STORAGE = 'storage.MediaRootS3BotoStorage' AWS_MEDIA_STORAGE_BUCKET_NAME = 'xxxxxxxxxxxxxxxx' MEDIA_URL = "//media.example.com/" # models.py import os import uuid from django.db import models from django.utils import timezone from django.utils.module_loading import import_string def upload_to_unique_filename(instance, filename): try: extension = os.path.splitext(filename)[1] except Exception: extension = "" now = timezone.now() return f'resume/{now.year}/{now.month}/{uuid.uuid4()}{extension}' class Candidate(models.Model): [...] resume = models.FileField( storage=import_string(settings.DEFAULT_PRIVATE_FILE_STORAGE)(), upload_to=upload_to_unique_filename, ) [...] The issue is that the bucket key is hardcoded in the settings file, and since there are multiple developers + 1 staging environment, all of the junk files that are uploaded for testing/QA purposes end up in the same S3 bucket as the real production data. One obvious solution would be to override AWS_MEDIA_STORAGE_BUCKET_NAME in staging_settings.py and development_settings.py files, but that would make the production data unavailable on staging and testing instances. To make this work, we would somehow how to sync the production bucket to the dev/staging one, which I'm unsure how to do efficiently and … -
I learned Django for Python but hate making it look pretty. Need ideas
So, I learned Django. I'm fine with creating the view controller but hate making the looks of an app. I can make animations and stuff, just not the looks. I know this sounds stupid, but I want to freelance mobile dev. Is there any, and I mean ANY ideas you guys have for this? Is there a UI designer or something that you can convert to code? -
Django Admin CSS files is Broken on Plesk
i have problem with Django amdin CSS files. i'm using Plesk. i add static root and static url in settings.py and after that run command manage.py collecstatic, but still my admin dont have css files. please help me. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
(Django - Python) Problems with timedelta saving form
I have a problem with my auction site because when I publish an auction the function doesn't save my variable correctly, these are my codes: views.py import datetime from datetime import timedelta def publishAuction(request): user=request.user form = auctionForm(request.POST, request.FILES) if request.method=="POST": if form.is_valid(): auction=form.save(commit=False) auction.advertiser=user auction.startDate=datetime.datetime.now() auction.endDate=auction.startDate+timedelta(days=1) auction.endPrice=request.POST.get("startPrice") auction.save() return redirect("../") else: form=auctionForm() models.py class Auction(models.Model): advertiser = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_advertiser', null=True) winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_winner', null=True) title = models.CharField(max_length=30) text = models.TextField() startPrice = models.FloatField(null=True) endPrice = models.FloatField() status = models.BooleanField(default=True) image = models.ImageField(upload_to='images/') startDate = models.DateTimeField(auto_now=False, auto_now_add=True) endDate = models.DateTimeField(auto_now=False, auto_now_add=True) The publication is done correctly, everything except endDate that is always equal to startDate... I have tried also with datetime.datetime.now instead of auction.startDate or datetime.timedelta(days=1) but when I get the value in the shell is always the same... In the scratch.py file I write the same codes and it works, I don't know why doesn't work in the function... :S Thanks to everyone! -
TypeError Posting from React Native to Django Rest API (Server 500 Error)
The error I am receiving is is a 500 server error: TypeError: 'Habit' object does not support item assignment found in the debug log of my Django App. (Habit is the name of the model connected with a Foreign Key in the Post model) I have a React Native app where I post data using fetch. An example of a post that works: Serializers.py from rest_framework import serializers from .. import models class EFHabitMeasSerializer(serializers.ModelSerializer): class Meta: model = models.HabitMeasurement fields = ('id','habit_record','habit','reply','created') Views.py from rest_framework import viewsets from .. import models from . import serializers from rest_framework import permissions class EFHabitMeasViewset(viewsets.ModelViewSet): def get_queryset(self, *args, **kwargs): return models.HabitMeasurement.objects.order_by('-created') serializer_class = serializers.EFHabitMeasSerializer Models.py class HabitMeasurement(models.Model): habit_record = models.ForeignKey(HabitRecord, on_delete=models.CASCADE, related_name='habitmeasurements') habit = models.ForeignKey(Habit, on_delete = models.CASCADE, related_name="habitsentered") REPLY_CHOICES = (("Yes","Yes"),("No","No")) reply = models.CharField(max_length = 10, choices=REPLY_CHOICES, default = 1) created = models.DateTimeField() slug = models.SlugField(max_length=200, allow_unicode=True, unique=True, blank=True) def save(self, *args, **kwargs): created_slug = str(self.habit_record) +'-'+ str(self.habit) +'-'+ str(self.created) self.slug = slugify(created_slug) super().save(*args, **kwargs) def __str__(self): return '[{}] {} {} taken on {}'.format( self.habit_record, self.habit, self.reply, self.created ) class Meta: ordering = ['-created'] The Function submitYes = () => { fetch(`${this.props.enemies.internet}/api/habit_measurements/`, { method: "POST", headers: { // "Accept": "application/json", "Content-Type": "application/json", // … -
Unkown Column error on django admin, how to fix it?
i have an error in my django admin: (1054, "Unknown column 'flora2estado.id' in 'field list'") the model flora2estado has two fields, they are used in unique together as a pseudo composite key, how can i fix this? admin.py admin.site.register(Flora2Estado) models.py estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True) especie_id = models.IntegerField() flora2estado = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) I tried to add the "flora2estado" field without sucess. All migrations done, thank you for your time -
divide django form fields to two divs
hi guys i have a form with a checkbox that if checked needs to display an additional bunch of fields, is it possible to tell the form to wrap some fields in one div and the rest in another div? this way I can play around client-side with javascript, I also want to do it client-side for styling purposes, any help will be greatly appreciated thanks in advance -
In settings.py, how should environment variables be loaded/set if they're only used in one environment?
I have a Django application where I'm handling environment variables using python-decouple and separate .env files. This works fine for variables that exist in both development and production environments, such as DEBUG. SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) While DEBUG has distinct values in each environment, other variables like SECURE_HSTS_SECONDS only need to be set in production and do not need to be set at all in development. I'm currently just hard-coding these values in my settings.py file: if not DEBUG: SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_REFERRER_POLICY = 'same-origin' SECURE_HSTS_PRELOAD = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True I suppose I could include these values in my dev .env file and just set them to their default values, but that seems unnecessary. Is there a cleaner way to implement this or a best practice? -
redirect to landing page How i can do that?
The problem is the logged in user who, after logging in, is on the main page of the application and after pressing the back button of the browser, I return to the login page, where the entire navbar is, there is a possibility that after clicking back the user will be redirected to the home page or checking some condition if the user is logged in, it is not possible to enter the login page -
How to return just the id number from queryset for a counter?
I'm really just a beginner in python and django... I'm looking for a way on how to get just the id of the last item in the queryset as a counter of posts for my project. I know about the ModelName.objects.last or .latest() however if I use last i still get the "Topic object (id)" I need just the id without the preceding text. Could anyone help me? -
Erro Python Django
Eu coloquei mais uma tabela no models dos usários, onde eu crio um modelo personalizado para um usuário. Eu criei uma tabela pra capturar algumas informações de onde ele. quando eu dou migrate ocorre o seguinte erro: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user' E todas as outras partes que eu uso a chave estrangeira apontando para o usuário ele dá esse problema -
Rename content_type and object_id in ContentTypeFramework
I want to create specific relation in my Django app. For doing this, I've chosen ContentTypeFramework and GenericForeignKey. In the django documentation there are not so much info about it. Here is it: There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. The usual name for this field is “content_type”. Give your model a field that can store primary key values from the models you’ll be relating to. For most models, this means a PositiveIntegerField. The usual name for this field is “object_id”. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named “content_type” and “object_id”, you can omit this – those are the default field names GenericForeignKey will look for. And it works great if I left fields with default names: content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField(null=True, blank=True) item = GenericForeignKey('content_type', 'object_id') But if I change their names, for something more specific (just custom field names) e.g: item_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE) item_id = models.UUIDField(null=True, blank=True) item = GenericForeignKey('item_ct', 'item_id') My Application tests fails with traceback: .................. File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1021, in add_annotation annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None, File "/usr/local/lib/python3.8/site-packages/django/db/models/expressions.py", line … -
how to take input from form submission and use it to display an entry using django
I'm trying to take the input from a form in Django and to then search storage and display any matches here is the code I have so far. views.py def search(request): input = request.GET.get('q') return render(request, "encyclopedia/search.html", { "entry": util.get_entry(input) == None, "display": util.get_entry(input) }) search.html {% extends "encyclopedia/layout.html" %} {% block title %} {% endblock %} {% block body %} {% if entry %} <div>No entry found</div> {% else %} <div>{{ display }}</div> {% endif %} {% endblock %} layout.html <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="get"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> <input type="submit"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> urls.py urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.entry, name="entry"), path("search", views.search, name="search") ] utils.py def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None It works with taking you to the search page but always displays no entry found even if the entry does exist. This is my first project using Django so its pretty new, I'm assuming there is an issue with how I'm feeding in the … -
Profile() got an unexpected keyword argument 'user'
Hi i working with Django . I'm trying to turn my user into a profile with signals When registering the user through a form I get the following error : TypeError at /Registro/ Profile() got an unexpected keyword argument 'user' and the user is created in 'AUTHENTICATION AND AUTHORIZATION' (ADMIN), but not in profiles. Models.py from django.db import models class Profile(models.Model): id = models.AutoField(primary_key=True) nombreUsuario = models.CharField('Nombre usuario : ', max_length=15, null = False, blank=False, unique=True) email = models.EmailField('Email', null=False, blank=False, unique=True) password = models.CharField('Contraseña', max_length=25, null=False, blank=False, default='') #Unique sirve para validar si el usuario existe y sea unico el email y nombre de usuario. nombres = models.CharField('Nombres', max_length=255, null= True, blank=True) apellidos = models.CharField('Apellidos', max_length=255, null=True, blank=True) imagen = models.ImageField(upload_to='img_perfil/',default='batman.png',null=True, blank=True) fecha_union = models.DateField('Fecha de alta', auto_now = False, auto_now_add = True) facebook = models.URLField('Facebook', null=True, blank=True) instagram = models.URLField('Instagram', null=True, blank=True) def __str__(self): return f'Perfil de {self.nombreUsuario}' class Meta: verbose_name = "Perfil" verbose_name_plural = "Perfiles" views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.views.generic.edit import FormView from .models import Profile from .forms import RegistrationForm from django.contrib import messages from django.contrib.auth.models import Group from django.utils.decorators import method_decorator def iniciarSesion(request): return render(request,'social/inicio.html') def registro(request): if request.method …