Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at / type object 'Form' has no attribute 'objects', how to fix?
AttributeError at / type object 'Form' has no attribute 'objects', I'm new to django, I'd appreciate a brief explanation views.py from django.shortcuts import render,redirect from django.contrib import messages from .forms import * def main(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): Form.objects.get_or_create( name=form.cleaned_data['name'], email=form.cleaned_data['email'], phone=form.cleaned_data['phone'] ) messages.success(request, 'Form has been submitted') return redirect('/') else: return HttpResponse("Invalid data") else: form = Form() return render(request, 'app/main.html', {'form': form}) models.py class ModelsForm(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone = models.CharField(max_length=30) objects = models.Manager() forms.py from .models import ModelsForm class Form(ModelForm): class Meta: model = ModelsForm fields = '__all__'``` -
how to make multiple select checkbox with ajax and no button submit
Python 3.9 Django 3.2 I have categories and product , and through a simple form in the template I choose 1 or 2-3 checkboxes and I get the result. How to do it now via ajax and without button 'submit'. I select several product categories and each click on the checkbox is ajax and the next click on the checkbox adds the parameter to the request. it is similar to how you select several parameters in online stores. You have selected 2 parameters and received a filtered list of products I suppose that you need to intercept the sending, store one request in the cache and add a new one to this request <form method="post" id="category-box"> {% csrf_token %} <div class="form-check"> <input class="form-check-input" type="checkbox" name='category' value="{{c.name}}" > <label class="form-check-label" for="{{c.name}}"><a href="{{ c.get_absolute_url }}">{{ c.name }}</a></label> </div> {% endfor %} <button type="submit">Submit</button> </form> -
Will Django always consider an Emoji as 1 character long?
I'm making a Post Reaction model that uses emojis as reactions, and at this point I'm not mapping them to Choices, but instead inserting the utf-8 value (e.g. 😀) directly to the Database (Postgres) as a CharField instance. This made me think which value should I use to the max_length of this field. I know Rust will take emojis as 1 char long, but I'm not sure about how python or Postgres will react. -
Django Forms: How do I use a selected object from dropdown menu?
I have a functioning dropdown menu filled with some objects from a database. When a user selects one, they should be directed to the objects appropriate page. Each object is a "Workout" and each workout has "Exercises". It is working, however, I am struggling to get the appropriate 'id' from the object that has been selected by the user. Below I will provide the view, template, url, and form. view.py @login_required def routines(request): """This view will provide a dropdown list of all of the workouts of a specific user. Once one is selected, the user will hit a submit button. After submitted, a new page will show all the exercises for that workout""" if request.method == "GET": #if we have a GET response, provide a form with filled data form = RoutineForm(request.GET, user=request.user) #data needs to equal the object that was selected from the GET form data = 1 if form.is_valid(): data=form.cleaned_data("workout") form.instance.owner = request.user #make sure we have the right user form.save() return HttpResponseRedirect('routine_workouts_app:routines') context = {'form':form, 'data':data} return render(request, 'routine_workouts_app/routines.html', context) @login_required def routine(request, data): """I think this is the view that will display the information of a workout as of now. Should be similar to the workout … -
how do I create a javascript function that changes the html when a form submit button is pushed in django
I can easily update the html when it's not part of the form's submit or button. Or even when it's just a pure button element (rather than an input from a form). However, when I try to append a string to the class "chatGoesHere", nothing happens. The consolealso quickly reloads since the form is going to \send. I'm happy to post my views.py and urls.py, however, I'm pretty sure the issue is inside of my html document below: <p class="chatGoesHere" id="chatGoesHere"> 1st Item! </p> <form action="\send\" method="post"> <input type="text" name="userMessage" /> <input type="submit" value="Send to smallest_steps bot" class="sendButt" id="sendButt" /> </form> <script> var btn = document.getElementById("sendButt"); btn.addEventListener("click", updateChat); function createMenuItem(name) { let li = document.createElement('p'); li.textContent = name; return li; } const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST2")) function updateChat(){ const td = document.getElementById('chatGoesHere'); td.appendChild(createMenuItem("TEST3")) } </script> I'd like it so that every time a user pushes the submit button of the form something gets added to the page without the page reloading. Thank you -
Django window.location not replacing string
I have a javascript function in a django view that is supposed to redirect the user to a different URL that contains a query parameter. When I print out the url before assigning it to window.location, it matches the url pattern as expected. However once I assign the URL to window.location, it seems to append the url to the already existing one instead of replacing it, and thus cannot find the matching url pattern. Javascript function: function downloadEvidence() { var product_review_ids = getProductReviewIDs(); if (product_review_ids === '') { window.alert("Please select at least one deployment.") return; } var url = window.location.href + "download_evidence?productReviewIDs=" + product_review_ids console.log(url); //prints: http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence?productReviewIDs=14 window.location = url; } The url pattern it is supposed to match: urlpatterns = [ path('access-review-owner/configure/<str:product_name>/download_evidence/',views.download_evidence_view, name='download_evidence_view'), ] The view it's supposed to navigate to: @require_http_methods(['GET']) def download_evidence_view(request, product_name): product_id = request.GET.get('productReviewIDs', None) print(product_id) ''' NOTE: Package up evidence here ''' return HttpResponseRedirect(os.environ['BASE_URL']+f'access-review-owner/configure/{product_name}/download_evidence/') The url it's attempting to find when I assign the correct one to window.location: GET http://127.0.0.1:8000/access-review-owner/configure/new%20test%20product/download_evidence/access-review-owner/configure/new%20test%20product/download_evidence/ -
Proper way to construct classes - Django dartCounter project
I was recently starting to do some programming. I figured out how to use Django a couple of days ago. And now I'm trying to integrate some old Python code with it. I created a simple dartCounter. Which is quite easy in a while-loop. However for the new version I want some graphical interface, so I figured I should make some proper classes to interact with without the usage of while loops for the count mechanism. Those classes should be used in the views.py section in Django. The thing is, I think I already made it overcomplex using this method. First I created a class dart_player() class dart_player(): def __init__(self, name): self.name = name self.score = None self.leg = 0 self.thrown_scores = [] def set_start_score(self, start_score): self.score = start_score self.thrown_scores = [] def update_score(self, score): if self.score != None: self.score = self.score - score self.thrown_scores.append(score) else: print("Error score equals 'None' \n") def reverse_score(self, score): if self.score != None: self.score = self.score + score self.thrown_scores = self.thrown_scores[:-1] else: print("Error score equals 'None' \n") def update_leg(self, leg): self.leg = self.leg + leg Next I ended up creating a class dart_match() and within it, the class leg() since the leg is part of … -
Can you access variable attributes in the django template language with other variables?
Let's say I have two variables - User and Fruitlist. User is a model instance, while fruitlist is a list. {% for user in users %} <tr> <td>{{ user.title }} </td> <td>{{ user.text }} </td> {% for fruit in fruitlist %} <td>{{ user.fruit }} </td> {% endfor %} {% endfor %} I'm trying to create a table with the code above where a column is created for each fruit in fruitlist, and that column is filled with the value of an attribute user.fruit (the user model has a field for every fruit which contains a value). Why doesn't the above code work? -
"extends" and "load" in one template (django project) , is this possible . Thanks in advance
I m trying to extend from the base template the navigation and the footer and also to load the static files ,but it doesnt show me any changes when im doing it (When i remove {% extends 'index.html' %} the css is working). I tried with include and it works but its broken - the body is under the footer etc. I tried also with {% block css %} and a lot of other things , but i dont think that is the way of fixing this one.. register_user.html {% extends 'index.html' %} <head> {% load static %} <link rel="stylesheet" href="{% static 'css/register/register.css' %}"> <title>Register - Audi Our Love</title> </head> {% block content %} <h1>Register User</h1> <form method="post">{% csrf_token %} {% for field in register_form %} <p> {{ field.label_tag }} {{ field }} {% if field.help_text %} {{ field.help_text }} {% endif %} {% for error in field.errors %} <p style="color:red;">{{ error }}</p> {% endfor %} {% endfor %} <button type="submit" class="register-button">Register</button> </form> <div> <p>Already have an account ? | <a href="{% url 'login' %}">Login</a></p> </div> {% endblock %} -
Django slow admin change view with autocomplete
To speed up the admin change view I did the following: class CaseAdmin(admin.ModelAdmin): ... autocomplete_fields = ('client', ) But if I look in de source code I see there are still 1000's of options loaded. Does anyone know how to solve this? -
Stream chat room with Django
i wanted to build a chat room with Django and i've built it so far but i'm stock in one particular area, i wanted the chat room to have realtime chatting room. Currently with my code i have to refresh the page each time before the message show up if i'm logged in the another user. This is my code in model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(User, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.body[0:50] and this is the code in my views.py def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all() participants = room.participants.all() if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room': room, 'room_messages': room_messages, 'participants': participants} return render(request, 'base/room.html', context) -
CSRF cookie not set - possibly blocked by kubernetes ingress
I use Axios in React and Django Rest Framework with dj-rest-auth. After migrating from GCP to Azure and removing the unmaintained django-rest-auth, I got some new CSRF issues. Initially I removed django-rest-auth and created my own LoginView from Django.contrib.auth.views. Noticed that this also gave the CSRF error in development. So I added dj-rest-auth, which solved my issue locally. Pushed to the AKS, but there the cookie still does not appear. I'm suspecting my ingress to be the problem, which is able to set INGRESSCOOKIE for both my backend and frontend, but no CSRF. I know there's a million tickets about this topic, my Django settings are fine, the set-cookie resopnse header is set. Also use the right axios settings to make sure that if the cookie is there, it's used for requests. The problem is really with the fact that the set-cookie is not coming through, as it is being created in Django. I use an Nginx controller with TLS on a static IP with and have my ingress defined as follows: apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: basic-ingress annotations: kubernetes.io/ingress.class: nginx cert-manager.io/cluster-issuer: letsencrypt-prod nginx.ingress.kubernetes.io/rewrite-target: / kubernetes.io/ingress.allow-http: "true" spec: tls: - hosts: - XXXXX secretName: tls-secret rules: - host: XXXXXXXX … -
Making Model fields for Aligner Tracking that automatically fill other fields by it's total amount and time they need to wear it
I'm trying to build a website for Aligner Tracking. In my Model file, I have length, aligner_number, and time. I want to set it up where let's say I put length (total of aligners) is 10 then my other aligner_number field would generate 10 fields going from 1-10 where each aligner that patient completes we can check off one of the aligner_numbers as complete which is also in the class Treatment. Also, time is the amount of time the patient wears the aligner so let's say they have to change it every 2 weeks. From the length and treatment_number I want it to automatically generate the same number of fields for total aligner numbers with the date being 2 weeks apart. So let's say length is 10 and the aligner_number has a list of aligner numbers 1, 2 , 3, and etc, I want each aligner_number to have a corresponding time_date 2 weeks apart for delivery. So, let's say patient start aligner 1 on November 1st, I want it to automatically generate the time fields to November 14th for Aligner 2, and November 28th for Aligner 3 and etc, so we know the patient needs to start wearing Aligner number … -
Access model field with two keys in template
I am a bit lost. It is been a while since I did some Django and I almost forgot everything about querysets and template. The app is a questionaire for comparing different vendors - hence their products. It is a questionaire with a scoring (best match) to each product. I want to access a specific element in a for loop which has two foreign keys to other classes. Here my model: Model: class Question(models.Model): questionText = models.CharField(max_length=500) class Vendor(models.Model): vendorName = models.CharField(max_length=30, unique=True) class Scoring(models.Model): score = models.IntegerField(default='0', blank=True) questionScoreForKey = models.ForeignKey(Question, null=True, related_name='scorequestion', on_delete=models.SET_NULL) vendorForKey = models.ForeignKey(Vendor, null=True, related_name='scorevendor', on_delete=models.SET_NULL) views.py def index(request): questions = Question.objects.all() vendors = Vendor.objects.all() return render(request, 'compare/index.html', {'questions': questions, 'vendors': vendors}) Template {% for ask in questions %} <tr> <td>{{ ask.questionText }} </td> {% for vend in vendors %} <td id="Vendor_{{ ask.pk }}_{{ vend.pk }}" style> {{ HERE THE SCORE OF THE QUESTION AND VENDOR }} </td> {% endfor %} </tr> {% endfor %} Both keys are existing but I have no clue how to access the score of e. g. the first question for the first vendors. Any hint appreciated. -
How to fix a mkdir error on a dockerized ap on ec2?
I have a django app based on django-cookiecutter running on an aws-ec2. The application itself built and is running ok. This application uses the django-cities-light library. When I run docker-compose -f production.yml run --rm django python manage.py cities_light which is the command to populate the database with countries/cities I get this error: INFO 2021-11-30 15:17:36,780 cities_light 1 140562076800832 Creating /usr/local/lib/python3.9/site-packages/cities_light/data Traceback (most recent call last): File "/app/manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/cities_light/management/commands/cities_light.py", line 145, in handle os.mkdir(DATA_DIR) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.9/site-packages/cities_light/data' ERROR: 1 As '/usr/local/lib/python3.9/site-packages/cities_light/data' is inside the docker I am very confused regarding what permissions I should set and to whom. If anyone could shed some light it will be much appreciated. Thank you! -
I cannot install pywallet in Ubuntu
I enter this in terminal : $ sudo pip3 install pywallet And these errors are displayed : ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/setup.py'"'"'; file='"'"'/tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-xidjadbh cwd: /tmp/pip-install-8qataqqd/sha256_e76f1676b6c24b1da2acf05fb844c2d4/ Complete output (121 lines): running bdist_wheel running build running build_ext building 'sha256' extension creating build creating build/temp.linux-x86_64-3.9 x86_64-linux-gnu-gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.9 -c sha256.c -o build/temp.linux-x86_64-3.9/sha256.o sha256.c: In function ‘PyInit_sha256’: sha256.c:2823:28: error: ‘PyTypeObject’ {aka ‘struct _typeobject’} has no member named ‘tp_print’ 2823 | __pyx_type_6sha256_sha256.tp_print = 0; | ^ sha256.c: In function ‘__Pyx_ParseOptionalKeywords’: sha256.c:3061:21: warning: ‘_PyUnicode_get_wstr_length’ is deprecated [-Wdeprecated-declarations] 3061 | (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : | ^ In file included from /usr/include/python3.9/unicodeobject.h:1026, from /usr/include/python3.9/Python.h:106, from sha256.c:24: /usr/include/python3.9/cpython/unicodeobject.h:446:26: note: declared here 446 | static inline Py_ssize_t _PyUnicode_get_wstr_length(PyObject *op) { | ^~~~~~~~~~~~~~~~~~~~~~~~~~ sha256.c:3061:21: warning: ‘PyUnicode_AsUnicode’ is deprecated [-Wdeprecated-declarations] 3061 | (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : | ^ In file included from /usr/include/python3.9/unicodeobject.h:1026, from /usr/include/python3.9/Python.h:106, from sha256.c:24: /usr/include/python3.9/cpython/unicodeobject.h:580:45: note: declared here 580 | Py_DEPRECATED(3.3) PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode( | ^~~~~~~~~~~~~~~~~~~ sha256.c:3061:21: warning: ‘_PyUnicode_get_wstr_length’ is deprecated [-Wdeprecated-declarations] 3061 … -
Django making tons of duplicate queries
Im working with on an ecommerce project where django is making tons of tons of duplicate queries while fetching products from database using django ORM. please find the below codes for your reference help to resolve. Thanks in advance. Product model class Product(models.Model): variations = ( ('None', 'None'), ('Size', 'Size'), ) name = models.CharField(max_length=200, unique=True) store = models.ManyToManyField(Store) slug = models.SlugField(null=True, blank=True, unique=True, max_length=500) sku = models.CharField(max_length=30, null=True) tax = models.IntegerField(null=True, blank=True) stock = models.CharField(max_length=10, null=True) variations = models.CharField(choices=variations, max_length=20) short_description = models.CharField(max_length=500, null=True) details = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) delivery_time = models.CharField(max_length=5, null=True, blank=True, verbose_name="Delivery Time") returnable = models.BooleanField(max_length=5, null=True, blank=True, verbose_name="Returnable") emi = models.BooleanField(max_length=5, null=True, blank=True, verbose_name="EMI available") image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) # This is used only for filtration color = models.ManyToManyField(Colors) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super(Product, self).save(*args, … -
Django with LDAP user authentication
I'm working in a Django and LDAP project. For now, with my basic code, a user can login after establishing a Connection with ldap (I'm using ldap3 library) @csrf_exempt def login_view(request): if request.method == "POST": data = json.loads(request.body.decode('utf-8')) cn = data["cn"] password = data["password"] user = Connection(server, 'cn='+cn+',ou=users,dc=syneika,dc=com', password, auto_bind=True) if user is not None: return HttpResponse('authenticated') else: return HttpResponseForbidden('wrong username or password') I am facing a problem when wanting to implement Tokens (JWT), I should Customize authentication backend in Django so I can use the authenticate() function and add tokens. I have a problem understanding the logic there, Django will save a authenticated user in the database but if we change the user password in LDAP? we can always login with the user in the database which is not convenient! Also, how can we customize Django authentication backend to login correctly using LDAP? Thank you -
Python/Django - multiple choice for ForeingKey
I am designing the models for the database that will consist of several apps. It has been decided to add a simple Document Management System to allow infinite documents to be attached to different models. This is the solution that I have thought but I don't know if it there is a better way to do it. Let's say for simplicity 3 models models.py class Contract(models.Model): .... class Invoice(models.Model): .... class Personal_record(models.Model): .... Each model can have multiple documents associated at user discretion for example: "Contract" can have 1 contract_file.pdf and 'n' amendments_to_the_contract.pdf "Invoice" is the only model that can have, in theory, an invoice.pdf per record "Personal_record" is free to the user to attach/upload any file he desires, therefore 'n' records.pdf The solution I thought of is to create another model called Documents that will store all the documents uploaded from any upload form. I would list all the links to the other models and make them blank and use a simple if/else to which type of ForeignKey update. class Documents(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE,blank=True, null=True) invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE,blank=True, null=True) p_records = models.ForeignKey(Personal_record, on_delete=models.CASCADE,blank=True, null=True) .... Is there a better way to do it? Maybe having only one … -
ModuleNotFoundError: No module named 'graphql.execution.executors' using graphql-ws
I try to write a subscription for my django webapp by using graphql-ws. I followed instruction that are written in README file inside the github repository (https://github.com/graphql-python/graphql-ws) but when I execute ./manage.py runserver, this error raises: File "/myproject/urls.py", line 16, in <module> from graphql_ws.django_channels import GraphQLSubscriptionConsumer File "/myproject/env2/lib/python3.8/site-packages/graphql_ws/django_channels.py", line 11, in <module> from .base_sync import BaseSyncSubscriptionServer File "/myproject/env2/lib/python3.8/site-packages/graphql_ws/base_sync.py", line 1, in <module> from graphql.execution.executors.sync import SyncExecutor ModuleNotFoundError: No module named 'graphql.execution.executors' I understand that this is caused by an in import inside graphql-ws: from graphql.execution.executors.sync import SyncExecutor. Here the problem is the graphql-core's version, in my project I need 3.1.6 for a lot of other things, and there isn't executors folder with file sync.py... but graphql-ws requires 2.* for graphql-core. Here is a part of my requirments: graphene~=3.0b7 graphene-django==3.0.0b7 django-graphql-jwt==0.3.2 graphql-ws==0.4.4 graphene-django-optimizer==0.9.0 graphene_file_upload==1.3.0 graphql-core==3.1.6 How can I fix it? Thanks a lot in advance -
Use function in Django Include Tag?
I'm trying to pass a value into a template via an include tab, like so: {% include "shared/page_title.html" with text=local_time_format(job.date, user.timezone, "M j P") %} So basically, i want the text value to be the result of calling local_time_format (a filter function) with job.date (context object value) and a user property and the final argument. Getting Could not parse the remainder error-- how to fix? -
Generate a new database when insert row in table
First of all i need to say i'm noob here and probably it is silly question I have a database called Projects, with one table like this: ID Project_name For example: ID projec_name 1 P301 2 P302 I want that every time I insert a record in this table of the database , generate a new database called db_project_name (e.g db_P301) with a structure that i have already defined. It is possible to do this by means of triggers? As far as i know, the triggers are only used to insert, update and delete records in a table, if it can not be done by a trigger I would like to know what options I have Or maybie it could be possible to do this via a scheduled task or an event? All this would be for a database of a web developed with django. Thanks -
Field 'xxx' expected a number but got <django.forms.boundfield.BoundField>
Here is my code: In forms.py class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ("title","business_partner","transaction") widgets = { 'transaction': forms.NumberInput() } In views.py def uploadpdf(request,pk): project_form = ProjectForm(request.POST) if project_form.is_valid() and request.FILES: project_form.instance.user = request.user project = Project.objects.get(id=pk) project.title = project_form['title'] project.business_partner = project_form['business_partner'] project.transaction = project_form['transaction'] project.save() project = Project.objects.get(id=pk) file_path = None for file in request.FILES: file = request.FILES[file] pdf_file = PDFFile(file=file, filename=file.name) pdf_file.project = project pdf_file.save() if PRODUCTION: file_path = HOST_NAME +'/'+ str(pdf_file.file) else: file_path = HOST_NAME +'/media/'+ str(pdf_file.file) resp = HttpResponse(f'{{"message": "Uploaded successfully...", "id": "{project.id}","url":"{file_path}","title": "{project.title}"}}') resp.status_code = 200 resp.content_type = "application/json" return resp else: return reverse("dashboard:homepage") When I run this, it says like "TypeError: Field 'transaction' expected a number but got <django.forms.boundfield.BoundField object at 0x000001A803935250>." Looking forward to hearing a good solution. -
How to sent to a personal mail with django contact form?
I'm creating a contact form on my Django website, I created a form, now I need to add into function an option when the contact form is filled to be sent to my private Gmail. Can I do this within a views function, if I can, please tell? views.py from .forms import ColorfulContactForm def contact(request): form = ColorfulContactForm() if request.method == 'POST': form = ColorfulContactForm(request.POST) if form.is_valid(): pass # what to add here? else: form = ColorfulContactForm() return render(request, 'contact.html', {'form': form}) forms.py class ColorfulContactForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'style': 'border-color: blue;', 'placeholder': 'Write your name here' } ) ) email = forms.EmailField( max_length=254, widget=forms.TextInput(attrs={'style': 'border-color: green;'}) ) message = forms.CharField( max_length=2000, widget=forms.Textarea(attrs={'style': 'border-color: orange;'}), help_text='Write here your message!' ) -
Django-NuxtJs: can't get cookie from request
I am using django and nuxt js to create a webapplication but I am having a problem with getting the user's data from the server after authentication. I tried using cookies but it didn't work so far. the server can't get the cookie from the request even though I have set credential: true. appreciate any help Views.py: from django.contrib.auth import authenticate from rest_framework.reverse import reverse import requests import jwt,datetime from django.contrib.auth.models import User from rest_framework.response import Response from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.decorators import api_view,permission_classes from rest_framework.permissions import * from .serializers import * from .models import * class BrandView(APIView): def get(self, request, *args, **kwargs): brands = Brand.objects.all() serializer= BrandSerializer(brands,many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializers= BrandSerializer(data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) return Response(serializers.errors) class ProductViewSet(viewsets.ModelViewSet): queryset=Product.objects.all() serializer_class= ProductSerializer class CustomersViewSet(viewsets.ModelViewSet): queryset=Customers.objects.all() serializer_class= CustomersSerializer class OrderdetailsViewSet(viewsets.ModelViewSet): queryset=Orderdetails.objects.all() serializer_class= OrderdetailsSerializer class OrdersViewSet(viewsets.ModelViewSet): queryset=Orders.objects.all() serializer_class= OrdersSerializer @api_view(['POST']) def register(request): username= request.query_params['username'] email= request.query_params['email'] password= request.query_params['password'] user = User.objects.create_user(username,email,password) @api_view(['POST']) def login(request): username= request.data.get('username') # email= request.query_params['email'] password= request.data.get('password') user = authenticate(username=username, password=password) if user is None: if not User.objects.filter(username=username): raise exceptions.AuthenticationFailed('User does not exist') else: raise exceptions.AuthenticationFailed('Incorred password') serializers = UserSerializer(user) token_endpoint = reverse(viewname='token_obtain_pair',request=request) token = requests.post(token_endpoint, …