Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
please help why it doesnt save this to my database
well i trying to create an app for my school an then i decided to use django and cbvs my registration view use the createview this is my createview: it doesnt give any error but it doesnt save anything what a im doing wrong? class Register(CreateView): form_class = RegForm model = Users template_name = 'registro.html' success_url = '/home' def get_form(self, form_class=RegForm): if form_class is RegForm: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) def get_initial(self, *args, **kwargs): initial = super().get_initial(**kwargs) initial['name'] = 'Enter Name' return initial def form_valid(self, form): self. object = form.save() return super(form_valid, self).form_valid(form) but it doesnt save anything or am i using the wrong view but this is my forms: Paises = ( (1, "Bolvia"), (2, "Ecuador"), (3, "Chile"), (4, "Agentina"), (5, "Peru"), (6, "Colombia"), (7, "Venezuela"), (8, "Paraguay"), (9, "Uruguay"), (10, "Mexico"), (11, "Estados-Unidos"), (12, "España"), ) users = ( ("student", "estudiante"), ("teacher", "profesor"), ) class RegForm(ModelForm): class Meta: model = Users fields = ['name', 'lname1'] Name = forms.CharField(label="Nombre", max_length=100, required=False) Fatherslname = forms.CharField(max_length=100, required=False) Motherslname = forms.CharField(max_length=100, required=True) age = forms.IntegerField() UserName = forms.CharField(required=True, max_length=80) userType = forms.ChoiceField(label="Eres?", choices=users) birthplace = forms.ChoiceField(label="Pais", choices=Paises) dateOfBirth = forms.DateField(label="Fecha de Nacimiento", initial=datetime.date.today) imagen = forms.ImageField(label="foto") Email = forms.EmailField(required=True) passwd = forms.CharField(label="contraseña", … -
i was trying to create django model and i got this error TypeError: 'type' object is not subscriptable
gender_choices = models.CharField[('M', 'Male'), ('F','Female')] gender = models.CharField(choices=gender_choices, max_length=1, default=None, null=True) -
Django-mptt filter in template
I use django-filter for filter in my website. Django-filter works well for my field. But when I use categories which to build with django-mptt in my template does not display tree (or taxonomy-node). I don't understand how to make it. I tried to build it you can see my try in template.html. But I get an error. I will be happy of any advice. template.html <form method="get" class="d-flex flex-column"> {% for su,structure in filter.form.subject|tree_info %} {% if structure.new_level %}<ul> <li>{% else %}</li> <li>{% endif %} {{ su }} {% for level in structure.closed_levels %}</li> </ul>{% endfor %} {% endfor %} <button class="btn-primary mt-2" type="submit">Search</button> </form> models.py class Book(models.Model): title = models.CharField(max_length=255, db_index=True) author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, db_index=True ) category = TreeManyToManyField("Category") class Category(MPTTModel): name = models.CharField( max_length=100, unique=True, verbose_name=_("category name"), help_text=_("format: required, max-100"), ) slug = models.SlugField( max_length=150, null=False, unique=False, blank=False, verbose_name=_("category safe URL"), help_text=_( "format: required, letters, numbers, underscore, or hyphens"), ) parent = TreeForeignKey( "self", on_delete=models.PROTECT, related_name="children", null=True, blank=True, unique=False, verbose_name=_("parent of category"), help_text=_("format: not required"), ) class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = _("article category") verbose_name_plural = _("article categories") views.py class ArticleListView(ListView): model = Book template_name = "template.html" def get_context_data(self, **kwargs): context = … -
How can I send comment notification email with blog post url in Django?
I have a Django blog website and I want to get notified when any user comment on my website. I want to get the notification as email with blog post url. Here is my code for sending email. #views.py context = { 'domain': settings.DOMAIN_NAME, 'site_name': settings.SITE_NAME, 'protocol': 'http', } def comment_email_setting(): email_template_name = "email/comment_email.txt" email = render_to_string(email_template_name, context) mail_obj = CommentFormNotification.objects.latest('id') send_mail( mail_obj.subject, email, mail_obj.from_mail, [mail_obj.to_mail], fail_silently=False, ) class PostDetailView(DetailView): model = Post context_object_name = 'posts' form = CommentForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form return context def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = self.get_object() form.instance.user = request.user form.instance.post = post comment_email_setting() form.save() return redirect(reverse('post_detail', kwargs={'slug': post.slug})) This is my views.py. When someone posts comment on my blog post, I want to get the url of the blog post in my email. How can I get it? #comment_email.txt {% autoescape off %} Hello, We received a notification from post {{ protocol }}://{{ domain }}. Sincerely, The Website Team {% endautoescape %} -
Flask vs Django
I am a JavaScript Engineer and have been building full stack large scale applications using Node.js, Vue.js, Mongo as the core components. Now, I am looking to pick up Python and write some existing smaller applications/functionality using it. What would be the community's recommendation to transition, Flask or Django given that I prefer Express over Nest -
Django rest framework - "This field is required."
I have two classes, class Amount and Transaction class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) account_number = models.BigIntegerField(unique=True) currency = models.CharField(max_length=3) balance = models.DecimalField(max_digits=20, decimal_places=2, default=0) class Transaction(models.Model): sender_account_number = models.BigIntegerField() recipient_account_number = models.BigIntegerField() amount = models.DecimalField(max_digits=20, decimal_places=2) date_creation = models.DateTimeField(auto_now_add=True) account = models.ForeignKey(Account, on_delete=models.CASCADE) My serializers: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ['sender_account_number', 'recipient_account_number', 'amount', 'date_creation', 'account'] extra_kwargs = { 'date_creation': {'read_only': True}, }`` class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_number', 'currency', 'balance', 'user'] extra_kwargs = { 'balance': {'read_only': True}, 'user': {'read_only': True}, } I want to add a transaction to the database, but so that it automatically sets my account_id based on the account number. I tried the perform_create method def perform_create(self, serializer): serializer.save(account=Account.objects.values('id').filter( account_number=self.request.data['sender_account_number'])) but I failed. I get error { "account": [ "This field is required." ] } for example, I want to send these data { "sender_account_number": 346, "recipient_account_number": 546, "amount": 60 } and Post method: def post(self, request): serializer = TransactionSerializer(data=request.data) serializer.is_valid(raise_exception=True): return Response(serializer.data) How to solve it? -
Restrict new form creation on frontend in Django
How can I restrict new form creation using Django formset? For eg. I want to present an "Add row" button to the user which will duplicate a set of input fields, AND, when the number of rows reaches 10, I want to give a prompt to the user that no more rows can be created. For eg., in the image below, if the user clicks on "+" one more time, it should either do nothing or prompt the user that max number of rows reached or something like that. -
MyRide, Carpooling website, built on older version, need help running it, TypeError: view must be a callable or a list/tuple in the case of include()
File "C:\Users\tabis\MY-RIDE\Carpool\urls.py", line 27, in url(r'^%s(?P.*)$' % settings.MEDIA_URL.lstrip('/'), File "C:\Users\tabis\anaconda3\lib\site-packages\django\conf\urls_init_.py", line 22, in url return re_path(regex, view, kwargs, name) File "C:\Users\tabis\anaconda3\lib\site-packages\django\urls\conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). from django.conf.urls import patterns, include, url from django.contrib import admin import app from django.conf import settings from django.conf.urls.static import static import notifications.urls from os import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', include('smuggler.urls')), url(r'^admin/', admin.site.urls), url(r'^app/', include('app.urls')), url(r'^api/', include('api.urls')), url(r'^broadcast/', include('broadcast.urls')), url(r'^$', app.views.IndexView.as_view()), url('^inbox/notifications/', include(notifications.urls, namespace='notifications')), url('', include('app.urls')), url(r'^admin/', admin.site.urls), ] urlpatterns += patterns('', url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),) # urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() -
How can I count how many products are ordered by a single user?
This is a single-page website that is kinda ecommerce site. I just want to count a single user how many products are ordered. How can I count? index view: def index(request): total_user = User.objects.count()-1 total_orders =Frontend_Order.objects.count() context = { "total_user":total_user, "total_orders":total_orders } return render(request,'0_index.html',context) frontend_view: def frontend_orders(request): if request.user.is_authenticated: if request.method == "POST": frontend_orders_request = request.FILES['frontend_file'] if 'frontend_file' in request.FILES else None sections = request.POST.get('numField11') functionality = request.POST.get('frontend') if functionality == "Portfolio": price = int(sections)*10 elif (functionality == "e-Commerce") or (functionality == "social-media"): price = int(sections)*15 Frontend_Order.objects.create( files = frontend_orders_request, Number_of_Section = sections, Website_Functionality = functionality, Price = price, USer = request.user, Email = request.user.email ) messages.success(request,f"{request.user.first_name}, Your order is procecing. I'll cotact you before placing the order.") return redirect("/", userz = request.user) else: messages.error(request,"Please login or create an account.") return redirect("/") Frontend Order Model: class Frontend_Order(models.Model): USer = models.CharField(max_length=50, null=True) Price = models.CharField(max_length=250, null=True) Number_of_Section = models.CharField(max_length=250, null=True) Website_Functionality = models.CharField(max_length=1, null=True) Email = models.EmailField(max_length=50, null=True) files = models.FileField(upload_to="new_file/", null=True, blank=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) -
Insert cv.imshow in a frame in Django
I need to encapsulate rtsp streaming in Django page. I'm actually using openCV, to take a frame and show it using StreamingHttpResponse(). I update this frame constantly using a thread to have the video. The solution isn't bad but I have the video on the center and a black frame all around. I need to add some buttons in the interface and with my solution I they can't be visible. There is a way to encapsulate this video in a Django frame? It's possible to encapsulate the frame using cv2.imshow()? I read about using Ajax to do what I need. It's possible with ajax? -
How can I present data from a model that inherits across multiple web pages?
I'm making a form divided into several pages (like a wizard form), I could not implement it and reviewing, Wizard is not what I need, so I divided it into pages. The point is that there are 7 steps and they all save information, step 8 has to show the data that was previously saved, only it is not displayed. How do I show that information that has already been saved? views.py class step7(ListView): model=Presupuestos template_name='Presupuestos/new-estimate-7-preview.html' context_object_name='presupuestos' queryset=Presupuestos.objects.all() models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) carro=models.ForeignKey(Carro, on_delete=models.SET_NULL, null=True) mano_obra=models.ForeignKey(ManoObra, on_delete=models.SET_NULL, null=True) parte=models.ForeignKey(Parte, on_delete=models.SET_NULL, null=True) garantia=models.CharField(max_length=255,default=0) pago = models.ForeignKey(Pagos, on_delete=models.SET_NULL, null=True) foto = models.ForeignKey(Foto, on_delete=models.SET_NULL, null=True) tecnicos=models.ForeignKey(Tecnicos, on_delete=models.SET_NULL, null=True) #detalle=models.ForeignKey(Detalle, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente} {self.carro}{self.mano_obra} {self.parte}{self.garantia}' \ f'{self.pago}{self.foto}{self.tecnicos}' new-estimate-7-preview.py <div class="invoice-title"> {% if presupuestos %} <h4 class="float-end font-size-16">Estimate #0001 <span class="badge bg-success font-size-12 ms-2">Paid</span></h4> <div class="mb-4"> <strong>LOGO</strong> </div> {% for presupuesto in presupuestos %} <div class="text-muted"> <p class="mb-1"><i class="uil uil-envelope-alt me-1"></i> {{presupuestos.cliente}}</p> <p class="mb-1"><i class="uil uil-phone me-1"></i> {{presupuestos.carro}}</p> </div> {% endfor %} {% endif %} </div> -
dealing with long form submission times
When a user creates a post it is broken into two forms one with the details one with the images. However if the user is uploading a lot of images the form can take a few minuets to submit leaving the user waiting at the create a post screen. Is there any way I can return the first form and then have the image upload and compression work in the background? Or is there a better way to handle this if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() if len(request.FILES.getlist('images')) == 0: return redirect('post-detail', PostFormID.pk , PostFormID.slug) else: for f in request.FILES.getlist('images'): postImages = PostImagesForm(request.POST, request.FILES) if postImages.is_valid(): instance = postImages.save(commit=False) instance.post_id = PostFormID.id instance.images = f instance.save() return redirect('post-detail', PostFormID.pk, PostFormID.slug) -
Query Performance Optimization in Django
I am creating a Blog website in django and while creating a page for specific blog posts I came across a problem in querying the data using the ORM. I have a model for Post which is related to another model comments where all the comments are captured. The comments model have following fields -> class Comment(models.Model): comment = models.TextField(null=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments_post') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments_user') def __str__(self): return self.comment Now while Querying the single blog post there could be N number of comments and for each comment there is a user assigned who has written the comment. So I want to find the user details such (name, email or phone number) for the user for each comment. The Query that I have executed is -> post = Post.objects.select_related().prefetch_related('images_set','comments_post').get(id=post_id) Now when I try to use {{post.user.email}} and if there are 3 comments for the post, the ORM will query 3 times to the DB to find the email for each user. But if I use {{post.user_id}} it will query only once as it preloads the user_id as it is available in comments table. Is there any way I can make … -
How can I solve invalid connection option "init_command" for django heroku using MySQL database? [duplicate]
I am trying to create an application using django and am trying to host that application online using heroku. For the last step I need to migrate my database to heroku for my results to show up. But this is always showing an error - File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/__init__.py", line 121, in connect dsn = _ext.make_dsn(dsn, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/extensions.py", line 167, in make_dsn parse_dsn(dsn) psycopg2.ProgrammingError: invalid dsn: invalid connection option "init_command" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( … -
Cors Issue with React Frontend and Django Backend
So I have build backend API in Django with inbuilt user module for authentication login etc. The login API is return Set Cookie when correct user and pass is passed. However when fetch is called, it's not setting Cookie in browser to be used later on further requests. Django CORS Setting. ALLOWED_HOSTS = ["django-env-south-1.elasticbeanstalk.com", "*","127.0.0.1"] CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'https://127.0.0.1:3000', 'http://127.0.0.1:3000', 'https://localhost:3000', 'http://localhost:3000', ] CSRF_TRUSTED_ORIGINS = [ "127.0.0.1:3000", "localhost:3000", ] React Fetch Code var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); var urlencoded = new URLSearchParams(); urlencoded.append("username", `${users.username}`); urlencoded.append("password", `${users.password}`); var requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded, redirect: 'follow', credentials: "include" }; //Fetching Login api fetch("http://127.0.0.1:8000/authentication/signin", requestOptions) .then(response => response.text()) .then(data => handleResult(JSON.parse(data))) .catch(error => console.log('error', error)); } Once Cookie is set in browser using below Code to pass Cookie in a new API Call. let myHeaders = new Headers(); let requestOptions = { method: 'GET', headers: myHeaders, credentials: "include" }; //Calling ME api fetch("http://127.0.0.1:8000/authentication/me", requestOptions) .then(response => response.text()) .then(result => handleData(JSON.parse(result))) .catch(error => console.log('error', error)); -
deploy python-socketio on django project
I would like to deploy this project which works perfectly on localhost or on python manage.py runserver command, when I try to deploy it I read on the documentation on the worker you should add these to gunicorn service which when I do -k eventlet -w 1, it returns 502 bad gateway This is what i'm getting based off https://github.com/miguelgrinberg/python-socketio/tree/main/examples/server/wsgi/django_example This is my gunicorn service [Unit] Description=gunicorn daemon Requires=dev.socket After=network.target [Unit] Description=gunicorn daemon Requires=dev.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/var/lib/jenkins/workspace/myproject ExecStart=/var/lib/jenkins/workspace/myproject/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ -k eventlet \ --bind unix:/run/dev.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target wsgi.py import os from django.core.wsgi import get_wsgi_application import socketio from app.views import sio os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') wsgi_application = get_wsgi_application() application = socketio.WSGIApp(sio, wsgi_application) settings.py ... WSGI_APPLICATION = 'myproject.wsgi.application' ... If I remove the -k eventlet from the dev.service gunicorn service, the 502 bad gateway goes away and the page keeps loading forever and it returns 504 Gateway Time-out, and if I revert back wsgi.py to it's django by default boilerplate, it shows the page, but the websockets doesn't work and the page keeps sending https://example.com/socket.io/?EIO=4&transport=polling&t=opIU5ZA GET requests, that gets 502 bad gateway -
Provide path of the file to be downloaded in django
views.py def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 urls.py from unicodedata import name from django.urls import path from Profile import views urlpatterns = [ ... path('download/<str:path>/', views.download, name="download"), ] models.py from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager # Create your models here. class ProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True) address = models.CharField(max_length=255 , null=True) image = models.ImageField(null=True, blank=True) def __str__(self): return str(self.user) template {% extends 'base.html' %} {% block content %} Welcome, {{request.user.username}} <table> <tr> <th>First Name: </th> <th>{{user.first_name}}</th> </tr> <tr> <th>Last Name: </th> <th>{{user.last_name}}</th> </tr> <tr> <th>Email: </th> <th>{{user.email}}</th> </tr> <tr> <th>Image: </th> {% if user.image %} <!-- here is the error --> <th><a href="{% url 'download' user.image.url%}"><img src=" {{user.image.url}}" alt="IMage...." style="object-fit: cover; border-radius: 50%; height: 200px; width: 200px;"></a></th> {% endif %} </tr> <tr> <th>Address: </th> <th>{{user.address}}</th> </tr> <tr> <th>Bio: </th> <th>{{user.bio|linebreaks}}</th> </tr> </table> MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') The problem is with the path I have provided for the file to be downloaded in the template. I don't know the correct way to give the required path of … -
problem on showing calculated value in django formsets field using javascript
I am trying to calculate value from quantity and rate once user enter it in the field and show it in amount field. this is my html file {% for iforms in iform %} <tbody > <tr> <td>{{ iforms.item_no }}</td> <td>{{ iforms.particular }}</td> <!-- <td>{{ iforms.alt_qty }}</td> --> <td id="itemqty">{{ iforms.qty }}</td> <td>{{ iforms.Uom }}</td> <td id="itemrate">{{ iforms.rate }}</td> <td id="itemdiscount">{{ iforms.discount }}</td> <td id="itemamount">{{ iforms.amount }}</td> </tr> </tbody> {% endfor %} </table> <input type="hidden" value="false" name="itemadd" id="itemadd"> <button class="btn btn-primary" id="additemsbutton">Add items</button> this is script in same html file which calculate field $(document).ready(function () { $("#itemqty").on('keyup',function(){ var itemquantity = parseFloat($(this).val()); var itemrate = parseFloat($("#itemrate").val()); $("#itemamount").html(parseFloat(itemquantity * itemrate)); }); $("#itemrate").on('keyup',function(){ var itemquantity =parseFloat($("#itemqty").val()); var itemrate =parseFloat($(this).val()); $("#itemamount").html(parseFloat(itemquantity * itemrate)); }); }); the field dissappear after entering value rather than showing calculated value and this message is shown on browser console inspect: Empty string passed to getElementById(). -
two page django site
I need to create simple website with two pages: List of Users List of Groups for Users actions – two buttons 'Edit' and 'Delete' Also, under the list, there should be a button ‘Add User' for editing and adding new pages with such fields: username (text input) and group(select) Please, can you recomend tutorials for creating it -
Unexpected token < in JSON when using fetch to [closed]
I am trying to connect my React signup page to my Django API so when a user signs up a user profile is created in my backend. I get this error on my console when I try to create a new user: Signup.js:33 POST http://127.0.0.1:8000/api/v1/users/profiles/?format=api 400 (Bad Request) onSubmit @ Signup.js:33 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ react-dom.development.js:237 VM1121:5 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 4 This is the code I have on signup.js: const onSubmit = e => { e.preventDefault(); const user = { email: email, name: name, location: 'Example', password: password, user_id: 1 }; console.log(user); fetch('http://127.0.0.1:8000/api/v1/users/profiles/?format=api', { method: 'POST', headers: { 'Content-Type':'application/json' }, body: JSON.parse(JSON.stringify(user)) }) .then(res => res.json()) .then(data => { if (data.key) { localStorage.clear(); localStorage.setItem('token',data.key); window.location.replace('http://localhost:3000/profile/'); } else { setEmail(''); setName(''); setPassword(''); localStorage.clear(); setErrors(true); } }); }; return ( <div className="base-container"> <div className="content"> <div className="image"> <ProcessImage image={secure_signup} resize={{ width:400, height: 400 }} processedImage={(src,err) => this.setState({ src,err})} /> {loading === false && <h1>Signup</h1>} {errors === true && <h2>Cannot signup with provided credentials</h2>} </div> <div className="form"> <div className="form-group"> <label htmlFor="username">Username</label> <input type="text" name="name" placeholder="name" value= {name} onChange= {e => setName(e.target.value)} required />{' '} </div> <div className="form-group"> <label htmlFor="email">Email</label> <input type="text" name="email" placeholder="email" value= {email} … -
How to pass two PK through urls in Django?
I've created a function that adds the user to an event, that is working fine but, i'm having problems with the one that removes the users from the event, I didn`t figure out how to get the attendant so that the owner can remove it. By now, I have this: views.py (Function that adds the user to the event) @login_required def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) Attending.objects.create(post=post, attendant=request.user) messages.success(request, f'Request sent!') return redirect(previous) except post.DoesNotExist: return redirect('/') (Function that removes users from the event, handled by the event owner) @login_required def remove_attendant(request, pk, id): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) attendant = Attending.objects.get(id=attendance_id) Attending.objects.filter(post=post, attendant=attendant).delete() messages.success(request, f'User removed!') return redirect(previous) except post.DoesNotExist: return redirect('/') Urls.py path('post/(?P<pk>[0-9]+)/remove_attendant/(?P<attendance_id>[0-9]+)$', views.remove_attendant, name='remove-attendant'), Any help or comment will be very welcome! thank you!!! -
Why mySQLclient is not installed
I want to install the MySQLclient package on my Cpanel host through the terminal. Because I want to connect my Django project to the database. When I want to install the necessary packages, everyone installs except MySQLClient. It also gives an error: Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [43 lines of output] mysql_config --version /bin/mysql_config: line 8: rpm: command not found ['8.0.28'] mysql_config --libs /bin/mysql_config: line 8: rpm: command not found ['-L/usr/lib64/mysql', '-lmysqlclient', '-lpthread', '-ldl', '-lssl', '-lcrypto', '-lresolv', '-lm', '-lrt'] mysql_config --cflags /bin/mysql_config: line 8: rpm: command not found ['-I/usr/include/mysql', '-m64'] ext_options: library_dirs: ['/usr/lib64/mysql'] libraries: ['mysqlclient', 'pthread', 'dl', 'resolv', 'm', 'rt'] extra_compile_args: ['-std=c99', '-m64'] extra_link_args: [] include_dirs: ['/usr/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,0,'final',0)"), ('__version__', '2.1.0')] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.8/MySQLdb creating build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.8/MySQLdb/constants copying … -
Django 3.2.1 KeyError in admin panel "django/db/models/fields/related_descriptors.py", line 173
I have models set up like the following: class A(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) def __str__(self): return self.name class B(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) a = models.ForeignKey(A, on_delete=models.CASCADE) def __str__(self): return self.a.name class C(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) b = models.ForeignKey( B, on_delete=models.CASCADE, related_name="c_name" ) def __str__(self): return self.b.a.name When I access C in the admin panel, I'm getting the following error: KeyError: 'a' File "django/db/models/fields/related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "django/db/models/fields/mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] I can't seem to find anything that explains why this would fail. I have looked at the underlying data (via psql) and the foreign keys are pointing to the right models etc. -
Display blog Tittle, Created Date and Body from database in a HTML page using Django
My database table : class Post(models.Model): title = models.CharField(max_length=100) body = models.CharField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank=True) My view : def post(request, pk): posts = Post.objects.filter(title=pk.replace('-', ' ')) blog_content = Post.objects.all() return render(request, 'posts.html', {'posts': posts}, {'blog_content': blog_content}) My template : {% block content %} <section class="blog-list px-3 py-5 p-md-5"> <div class="container"> <div class="item mb-5"> <div class="media"> <div class="media-body"> <h1 class="title mb-1"><a style = "text-decoration:none;">{{blog_content.title}}</a></h1> <div class="meta mb-1"><span class="date">{{blog_content.body}}</span></div> <div class="intro">{{blog_content.created_at}}</div> </div><!--//media-body--> </div><!--//media--> </div><!--//item--> </div> </section> {% endblock %} When I click an individual blog title from the home page it should show that post title, created date, and body on the posts.html page. But its showing raw html and css tags ! What's the solution ? -
Making SQS boto3 base class python
Need a help with writing base class for Amazon SQS boto3 client. The idea is that we will have three classes, one parent and two child. In the parent class there are all base functionality to connect to AWS SQS and child will be with custom body and URLs. (because there will be different body and URLs from each other) So I don't understand where need to create send function in the main class or in a child? And the basic structure of the classes, there is no information for this case on the internet, please help. What I have done at the moment: import boto3 import logging from abc import ABC, abstractmethod from django.conf import settings logger = logging.getLogger(__name__) class BaseQueueController(ABC): """" Base controller for Amazon SQS """ def __init__(self): self.sqs = boto3.client('sqs', region_name=settings.AWS_REGION, aws_access_key_id=settings.AWS_SQS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SQS_SECRET_ACCESS_KEY, endpoint_url=settings.AWS_SQS_ENDPOINT_URL, ) @abstractmethod def send(self): pass class FirstChild(BaseQueueController): """" SQS 1st """ pass class SecondChild(BaseQueueController): """" SQS 2nd """ pass