Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - issue with displaying SearchHeadline object in a template
I am working on search functionality and I need to implement SearchHeadline to highlight searched words however I am struggling to do it in multiple fields. What I'd like to do is to highlight not only words in the title field but also the short_description field. I found this question and tried to implement Concat however, in my case title and short_description are placed in 2 seperated html elements so I cannot just concatenate them and display as 1 headline because I need to display the whole title and the whole short_description and highlight matching words. views.py class SearchResultsList(LoginRequiredMixin, ListView, CategoryMixin): model = QA context_object_name = "query_list" template_name = "search/SearchView.html" def get_queryset(self): query = self.request.GET.get("q") search_vector = SearchVector("title", weight="A") + SearchVector("short_description", weight="B") search_query = SearchQuery(query) search_headline = SearchHeadline('title', search_query, start_sel='<span class="text-decoration-underline sidebar-color">',stop_sel='</span>') # how to implement SearchHeadline to short_description? return QA.objects.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ).annotate(headline=search_headline).filter(rank__gte=0.3).order_by("-rank") #The code below is working but it concatenates the title with the short description and I need to separate these fields. Moreover, it shows only a preview, not the whole title and short description value # return QA.objects.annotate(search_vectors=SearchVector('title', 'short_description'), ).annotate(headline=SearchHeadline(Concat(F('title'), Value(' '), F('short_description')),SearchQuery(query),start_sel='<strong>', stop_sel='</strong>')).filter(search_vectors=SearchQuery(query)) SearchView.html {% for query in query_list %} <div class="col-12"> <a href="{{ … -
Django set ImageView of User Profile
So i've been working on a project for a while, in which I use the Django default User Instance but with additional attributes, which are stored in a "Profile"-Model. So right now i have an assigned company, and an Profile-Image for the user in the Profile Model. Now i have a detailview to edit the user's attributes (firstname, username, email, etc.). i used generic.DetailView for this View. But this is only working for the Attributes in the User-Model from Django. How can I also change Attributes in the Profile Model when editing the User? This is my Edit-View: class ProfileUpdateView(LoginRequiredMixin, UpdateView): model = User fields = ['username', 'email', 'first_name', 'last_name'] template_name = 'inventory/edit_forms/update_profile.html' success_url = '/profile' login_url = '/accounts/login' redirect_field_name = 'redirect_to' def form_valid(self, form): profile = Profile.objects.get(user=self.request.user) profile.img = self.request.POST.get('profile_img') profile.save() return super().form_valid(form) def get_object(self): return User.objects.get(pk = self.request.user.id) This is my HTML: <form class="edit_object" action="" method="post" enctype='multipart/form-data' class="form-group"> <div style="width: 20%; margin-bottom: 1rem;"> <label>Profile Image</label> <input name="profile_img" type="file" accept="image/png, image/gif, image/jpeg"> </div> {% csrf_token %} {{form|crispy}} <input type="submit" value="Submit" class="btn action_btn"> </form> As you see i already tried using a external Input field and setting the image like that. But after submitting, the img attribute in the Profile-Model … -
'SessionStore' object has no attribute 'cart' - Django
I generated a basket with 2 products, at the level of the basket page and also on this same page I added a form to insert the customer's name. by clicking on the submit button which will send the request to a view for insert into the database. but I have an error ('SessionStore' object has no attribute 'cart') I am using django-shopping-cart 0.1 and also I am using an API to post the products Views.py def postCommande(request): for key,value in request.session.cart.items: data={ 'products':[ { 'date':'23-09-22 00:00:00', 'nameclient': request.POST['name'], 'type':'typeproduct' } ] } url='http://myapi/products/postCommande' x=requests.post(url,json=data) return render(request,'panier/succes.html') And the error is on this line (for key,value in request.session.cart.items:) -
How can i makemigrations & migrate in AWS with Django
I have a question! I'm trying to change tables (for example> add product.category111 ) my postgresql database in AWS RDS, but RDS tables weren't changed. And i have NO ERROR...(this makes me going crazy) I'd tryed almost everything that I can googling but I can't find answer. First, .ebextensions/10_django.config like this container_commands: 01_makemigrations: command: "source /var/app/venv/*/bin/activate && python /var/app/current/manage.py makemigrations --noinput" leader_only: true 02_migrate: command: "source /var/app/venv/*/bin/activate && python /var/app/current/manage.py migrate --noinput" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings.production aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application Second, config.settings.production.DATABASES DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": get_secret("AWS_RDS_HOST"), "NAME": get_secret("AWS_RDS_NAME"), "USER": get_secret("AWS_RDS_USER"), "PASSWORD": get_secret("AWS_RDS_PASSWORD"), "PORT": "5432", } } Third, AWS cfn-init-cmd.log (when i added products.category111 table) ... [INFO] Migrations for 'products': [INFO] /var/app/current/apps/products/migrations/0001_initial.py [INFO] - Create model Category [INFO] - Create model Category111 ... [INFO] Command 02_migrate [INFO] -----------------------Command Output----------------------- [INFO] Operations to perform: [INFO] Apply all migrations: "some tables that i made", products [INFO] Running migrations: [INFO] No migrations to apply. ... as you can see, there is "Create model Category111" in makemigrations section but "No migrations to apply." in migrate section. and there is no change in RDS ofc. Any helps makes me better programmer, Thanks config command options that I'd tried (all combinations) … -
You need to create a User CRUD application using Python Django Note
You need to create a User CRUD application using Python Django Note - Create authentications. Users sign up ( FIRST NAME, LAST NAME, EMAIL, PASSWORD). A Verification should go to email to know whether it is existing or not. User sign in (Email, PASSWORD). Show a user dashboard page when sign in. Two Roles (User role and Admin role) if admin show admin dashboard, if user show user dashboard. -
Why is mail not sent? (Django)
I've written this code and I cannot figure out why the mail is not sent. In this code I check the POST field of the class request and I get the IP address inserted in a form. Once gotten the IP address I make a call to the server indicated by the IP and then I would like to send an email with the text of the response. def startPing(request): servers = Server.objects.all() context = {"servers": servers} if request.method == 'POST': indirizzoIP = request.POST.get('indirizzoIP') timer = request.POST.get('timer') indirizzoIP = "http://" + indirizzoIP while True: response = requests.get(indirizzoIP) if response != "": response = "Server OK" send_mail( 'Report server', '{}'.format(response), 'from@', ['to@'], fail_silently=False, ) print(response) sleep(float(timer)*3600) return render(request, 'homepage.html', context) -
Dynamically Limit Choices of Wagtail Edit Handler
I would like to limit the choices available of a field in the Wagtail-Admin edit view. My Wagtail version is 2.16.3. In my case, if have a page model, that describes product categories. To each category might exist some tags. There is another page model, that describes concrete products and always is a subpage of a category page. A product can now be described with some tags, but only tags, that belong to the product's category make sense, so I would like to restrict the edit handler of the products to these tags. My models.py looks similar to this: class ProductTag(ClusterableModel): name = models.CharField(_("Name"), max_length=50) category = ParentalKey( "ProductCategoryIndexPage", related_name="tags", on_delete=models.CASCADE ) class ProductPage(Page): parent_page_types = ["products.ProductCategoryIndexPage"] tags = ParentalManyToManyField("ProductTag", related_name="products") content_panels = Page.content_panels + [ FieldPanel("tags", widget=widgets.CheckboxSelectMultiple()), ] class ProductCategoryIndexPage(Page): subpage_types = ["products.ProductPage"] content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel("tags", label="Tags")], heading=_("Produkt Tags"), ), ] My approach was to create a custom edit handler and inject the wigdet overriding the on_instance_bound method using the correct choices argument for the widget. class ProductTagEditPanel(FieldPanel): def on_instance_bound(self): self.widget = widgets.CheckboxSelectMultiple( # of_product is a custom manager method, returning only the tags, that belong to the product's category choices=ProductTag.objects.of_product(self.instance) ) return super().on_instance_bound() But … -
The Django password reset form is not working, where is the problem?
My motive is to reset the password by sending an email to the user. When the user will click on the link that sends by mail will open an Html page, which will have a password and confirm password form. The email sending system is working well, when I click on the link that sends by mail opens a password reset form. But the problem is, the password reset form is not working. Password not being changed. Where did the actual problem occur? Password not being change. Where did the actual problem occur? Please give me a relevant solution😢... helper.py: from django.core.mail import send_mail from django.conf import settings def send_forget_password_mail(email , token ): subject = 'Your forget password link' message = f'Hi , click on the link to reset your password http://127.0.0.1:8000/changepassword/{token}/' email_from = settings.EMAIL_HOST_USER recipient_list = [email] send_mail(subject, message, email_from, recipient_list) return True views.py: def ChangePassword(request, token): context = {} try: profile_obj = User.objects.filter(forget_password_token=token).first() print(profile_obj) if request.method == 'POST': new_password = request.POST.get('new_password') confirm_password = request.POST.get('reconfirm_password') user_id = request.POST.get('user_id') if user_id is None: messages.warning(request, 'No user id found.') return redirect(f'/changepassword/{token}/') if new_password != confirm_password: messages.warning(request, 'both should be equal.') return redirect(f'/changepassword/{token}/') return redirect('login_user') context = {'user_id' : profile_obj.user.id} except Exception … -
How to upload more than 2 files once in django?
I put two files in web, but i can only get one file always. can you guys do me a favour, i will be deeply grateful! in web [i have put two files in web][1] form.py ``` class UFileForm(forms.Form): file = forms.FileField(label="资料文件上传", widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': 'bg-info'})) ``` view.py ```class UploadFileView(View): """ 文件上传的视图类 """ def get(self, request): form = UFileForm() return render(request, 'data_check/upload_file.html', {'form': form, 'title': '文件上传'}) def post(self, request): data = {} form = UFileForm(request.POST, request.FILES) files = request.FILES.getlist('file') # print files in request here print(files) ``` result is:[<InMemoryUploadedFile: 20220609奥莉公会-积分统计表.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>] There is only one file. [1]: https://i.stack.imgur.com/CG97G.jpg -
django read json file with relative file path
I am attempting to deploy django in production, but have an issue with a relative file path in my models.py. When I use python3 manage.py runserver 0.0.0.0:8000, the site works fine. When I run django using http and wsgi, I get the error that the below file cannot be found. I assume this is because it is looking for the file using a relative path. How should I fix this? This is the line in my models.py, which imports the json file. data = open('orchestration/static/router_models.json').read() -
Railway.app can't find staticfiles after deployment django app
I try to deploy my app to Railway.app. App generally works but static files are not found. I have made collectstatic folder using command django manage.py collectstatic as advised in deployment tutorials but it doesn't help. Any clue what could went wrong ? settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') staticfiles folder is situated in directory that contains menage.py file deploy logs from railway.apps Not Found: /staticfiles/style.css Not Found: /staticfiles/base.css Not Found: /staticfiles/MyImage.png Not Found: /staticfiles/base.js -
Django `sender` not working for signal receiver
I am trying to create a post_save handler for when the model Client has been saved. The reason I am using a signal is because I require for the code run when a Client is added via loaddata as well. Heres the sender: # apps.py from django.db.models.signals import post_save class ClientsConfig(AppConfig): name = 'clients' verbose_name = "clients" def ready(self): """https://docs.djangoproject.com/en/4.1/topics/signals/""" # Implicitly connect signal handlers decorated with @receiver. from . import signals # Explicitly connect a signal handler. post_save.connect(signals.write_svg, dispatch_uid="clients_client_post_save") Heres the receiver: # signals.py from django.db.models.signals import post_save from django.dispatch import receiver from .models import Client @receiver(post_save, sender=Client) def write_svg(sender, instance, **kwargs): """Using a signal so that when one loaddata the DB, it performs this action too""" print('\n-----------------------------------------------------') print('Signal called, sender', sender) Here you can see it prints for a whole bunch of Session events, and many other events, instead of being filtered for only the client model: ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> ----------------------------------------------------- Signal called, sender <class 'django.contrib.sessions.models.Session'> -
Django - separating prod and dev settings - delete original settings.py?
I'm following the below answer on separating development and production Django settings file. https://stackoverflow.com/a/54292952/15166930 After separating, would I delete the original settings.py file? Is this the common practice on separating the files? I see multiple methods on that SO post. Also, per the SO answer, I'm to update the BASE_DIR in my base.py file to BASE_DIR = Path(file).resolve().parent.parent.parent right now it's as below: settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) Just want to confirm because the two are so different.. thx (Django 2.1.7) -
error in django of -- MultiValueDictKeyError at /signup
i create a simple login and signup project but at the signup process when i sign up and redirect to the login page i got the error called "MultiValueDictKeyError" this is my signup.html file --> <!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"> <title>sign up here</title> </head> <body> <h3>Sign Up</h3> <form action="/signup" method="POST"> {% csrf_token %} <label for="">username</label> <input type="text" id="username" name="username" placeholder="Create a user name" Required><br> <label for="">first name</label> <input type="text" id="fname" name="fmyname" placeholder="First Name" Required><br> <label for="">last name</label> <input type="text" id="lname" name="lname" placeholder="Last Name" Required><br> <label for="">email</label> <input type="email" id="email" name="email" placeholder="enter your email address" Required><br> <label for="">password</label> <input type="password" id="pass1" name="pass" placeholder="enter your password" Required><br> <label for="">re-enter password</label> <input type="password" id="pass2" name="pass2" placeholder="re enter your password" Required><br><br> <button type="submit">Sign Up</button> </form> </body> </html> and this is views.py def signup(request): if request.method == "POST": # username = request.POST.get('username') username = request.POST['username'] firsname = request.POST['fmyname'] #here i got ERROR of the multivaluedictkeyerror lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username, email, pass1) myuser.first_name = firsname myuser.last_name = lname myuser.save() messages.success(request, "your account is created.") return redirect('signin') return render(request, 'authentication\signup.html') -
How to force this field to submit data?
I have a form that looks like I am trying to add a product. The description of which will be entered through this form. But my textarea dont send data to product html: <div class="col-12"> <div class="mb-2"> <label class="form-label">Текст новости</label> <div id="blog-editor-wrapper"> <div id="blog-editor-container"> <div class="editor"> <textarea name="text" class="form-control" id="text" rows="3" required>TEXT</textarea> </div> </div> </div> </div> </div> vievs: def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.preview=request.POST.get("preview") obj.date=request.POST.get("date") obj.image=request.POST.get("image") obj.save() models: text = models.TextField('Текст статьи') Мy other fields (not custom) look like this <label class="form-label" for="blog-edit-title">Заголовок</label> <input type="text" id="blog-edit-title" class="form-control" value="" name="title" /> -
Django RedirectView CSRF verification failed. Request aborted
Ran into a problem when redirecting a request through RedirectView. Returns a 403 CSRF verification failed response. Request aborted. I'm a newbie, please explain what's wrong? project/urls.py urlpatterns = [ path('v2/partner/products/groups', RedirectView.as_view(url=f"{abm_url.ABM_URL}/v2/partner/products/groups"))] -
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' in Django inside Swagger
This error is thrown in django even though it's not even imported anywhere. It's thrown by OpenAPISchemaGenerator as follows: File "/opt/hostedtoolcache/Python/3.8.13/x64/lib/python3.8/site-packages/drf_yasg/inspectors/field.py", line 406, in <module> (serializers.NullBooleanField, (openapi.TYPE_BOOLEAN, None)), AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' How do I fix this? link. It doesn't answer the question. -
AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField'
After upgrading djangorestframework from djangorestframework==3.13.1 to djangorestframework==3.14.0 the code from rest_framework.serializers import NullBooleanField Throws AttributeError: module 'rest_framework.serializers' has no attribute 'NullBooleanField' Reading the release notes I don't see a deprecation. Where did it go? -
error in creating an order by the customer while checking out
"Environment: Request Method: POST Request URL: http://127.0.0.1:8000/makeOrder/9/ Django Version: 3.0.5 Python Version: 3.6.8 " Traceback (most recent call last): File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HARSHA\Documents\sdp-2\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\HARSHA\Documents\sdp-2\website\views.py", line 232, in makeOrder 'fuel' :fuel, Exception Type: UnboundLocalError at /makeOrder/9/ Exception Value: local variable 'fuel' referenced before assignment -
Notify admin in django REST API
while uploading files i need to notify admin.How can i do this models.py class File(models.Model): file = models.FileField(blank=False, null=False) remark = models.CharField(max_length=20) timestamp = models.DateTimeField(auto_now_add=True) Serializers.py class FileSerializer(serializers.ModelSerializer): class Meta(): model = File fields = ('file', 'remark', 'timestamp') Views.py class FilesViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = (permissions.IsAuthenticated,) -
Date and File name are not showing while Updating the Data in Django
I have Tried some patterns which are suggested by some Stackoverflow users. They are like : date:'jS M Y' & date:'c' But not working in my case. Also referred this article : django update view not showing date input (previous) values Models.py from tkinter import CASCADE from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Ticket2(models.Model): ticketholder = models.ForeignKey(User, on_delete=models.CASCADE, default=None) ticket_id = models.CharField(max_length=8, default='NS000001') server_details = models.CharField(max_length=100) send_date = models.DateTimeField(default=timezone.now) license_no = models.CharField(max_length=25) file = models.FileField(upload_to='documents/%Y%m%d/') def __str__(self): return self.ticket_id edit.html {% extends 'base.html' %} {% block content %} <h3 class="row justify-content-around">Edit Form</h3> <div class="row justify-content-around" class="modal-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Ticket ID</label> <input type="text" value="{{ticketdata.ticket_id}}" name="ticket_id" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Server Details</label> <input type="text" value="{{ticketdata.server_details}}" name="server_details" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Send Date</label> <input type="datetime-local" value="{{ ticketdata.send_date.value|date:'jS M Y' }}" name="send_date" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">License No</label> <input type="text" value="{{ticketdata.license_no}}" name="license_no" class="form-control" id="exampleInputPassword1" required> </div> <div class="form-group"> <label for="exampleInputPassword1">Files</label> <input type="file" value="{{ticketdata.file}}" name="file" class="form-control" id="exampleInputPassword1" required> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary">Submit</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> {% endblock %} views.py … -
Django uwsgi nginx cloudpanel.io
I'm using ubuntu server 22 with cloudpanel.io. Error from nginx error logs: connect() failed (111: Connection refused) while connecting to upstream, client: 123.123.123.123, server: django.secretdomain.com, request: "GET / HTTP/2.0", upstream: "uwsgi://127.0.0.1:8080", host: "django.secretdomain.com" vhost file: (nginx file) server { listen 80; listen [::]:80; listen 443 ssl http2; listen [::]:443 ssl http2; {{ssl_certificate_key}} {{ssl_certificate}} server_name django.secretdomain.com; {{root}} {{nginx_access_log}} {{nginx_error_log}} if ($scheme != "https") { rewrite ^ https://$host$uri permanent; } location ~ /.well-known { auth_basic off; allow all; } {{settings}} index index.html; location / { include uwsgi_params; uwsgi_read_timeout 3600; uwsgi_pass 127.0.0.1:8080; } if (-f $request_filename) { break; } } The domain.uwsgi.ini [uwsgi] plugins = python3 master = true protocol = uwsgi socket = 127.0.0.1:8080 wsgi-file = /home/admin/htdocs/django.secretdomain.com/django5/Django5/mysite/mysite/wsgi.py virtualenv = /home/admin/htdocs/django.secretdomain.com/django5/Django5/venv buffer-size = 8192 reload-on-rss = 250 processes = 4 threads = 2 enable-threads = true close-on-exec = true umask = 0022 uid = admin gid = admin ignore-sigpipe = true ignore-write-errors = true disable-write-exception = true On the frontpage i get a simnple 'internal server error'. A simple python test file works but django doesn't. What I'm supposed to do? -
Django Celery Beat did not send message to SQS broker (Django, SQS, DatabaseScheduler)
I have 2 t2 instances on AWS, one for beat, one for worker. Beat (t2.micro): celery -A iso_backend beat -l info --scheduler django Worker (t2.small): celery -A iso_backend worker -l info --scheduler django I'm using djang_celery_beat_clockedschedule's table for scheduling a lot of long-running job. A lot of clocked has_many jobs, so example: at 08:20:00am, Beat must call 100 messages to SQS queue at the same time, the issue is, it call only a fews, sometimes 1/2, sometimes 1/3 number of the jobs Scheduler: Sending due task... Actually, this issue is really hard and I cannot figure out the root cause. Anybody met this before and has any solutions help me? Thank a lot! -
How to by pass login required url authen by any mean in website?
Hope you are doing good. i am new to Django so basically i want an idea of how we can access page that required login but i want one time login not every time.or just by pass this authentication by any mean i don't know? i-e: i have chat bot i want to give that page specific url to some client and that client add that url in his website so his clients just use my chatbot by click my chatbot url that are present in my client website.but i want that by clicking that url does not require to login first but i want the secure access only that client domain only access my url . not other domain or from chrome brower. if you give any idea it will be very kindness of you thanks alot. my-sloution: i used django-cors but i dont know that using cors will restrict access to other domain accept the allowed one? i experence from cors-test websites i just send post request but cannot access my site when i allowed that domain in cors then they can get post response . so basically when i search that url from chrome on same LAN … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
I am trying to save a user with its respective group but it gives me an error error: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. I also don't know if I make a correct call of the group column models.py @login_required #@allowed_users(allowed_roles=['Administrador']) def crearusuario(request): data = { 'empleado': CrearEmpleadoForm() } if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=make_password(request.POST.get('contrasena')) usersave.activo=request.POST.get('activo') usersave.cargo_empleado=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) usersave.id_empresa=Empresa.objects.get(pk=(request.POST.get('id_empresa'))) usersave.id_unida=UnidadInterna.objects.get(pk=(request.POST.get('id_unida'))) if request.method == 'POST': formulario = CrearEmpleadoForm(data=request.POST) if formulario.is_valid(): username=request.POST.get('rut') password=request.POST.get('rut') first_name=request.POST.get('nombres') last_name=request.POST.get('apellidos') email=request.POST.get('correo_electronico') groups=Group.objects.get(pk=(request.POST.get('group'))) cargo=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) activo=request.POST.get('activo') user=get_user_model().objects.create( username=username, password=make_password(password), first_name=first_name, last_name=last_name, email=email, cargo_empleado=cargo, is_active=True, groups=groups ) cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+str(usersave.cargo_empleado.id)+"', '"+str(usersave.id_empresa.id)+"', '"+str(usersave.id_unida.id)+"')") messages.success(request, "El empleado "+usersave.nombres+" se guardo correctamente ") return render(request, 'app/crearusuario.html', data) else: return render(request, "app/crearusuario.html", {'empleado':formulario}) else: return render(request, 'app/crearusuario.html', data) help me please