Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get sum of the salary for each user
I am on a django project where the admin assigns work to users by uploading the work to each user, and the user can only see the job they have been assigned. I want a way to get the total amount for all the work the user have done by the end of a month. I have a model Work, and it has a field Pay_Amount, which is the amount for one job, I want a way to add the Pay_Amount of only one user per month. I already have the total amount to pay all the users, I just want the amount to pay a single user for all the jobs he/she has done for one month... Please assist... -
Unknown layer: Patches. Please ensure this object is passed to the `custom_objects` argument
Unknown layer: Patches. Please ensure this object is passed to the custom_objects argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. Anyone please? I have passed the Patches object to the "custom_object"but getting again and again same error. Patches Layer: class Patches(layers.Layer): def __init__(self, patch_size, **kwargs): super(Patches, self).__init__() self.patch_size = patch_size def call(self, images): batch_size = tf.shape(images)[0] patches = tf.image.extract_patches( images=images, sizes=[1, self.patch_size, self.patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates=[1, 1, 1, 1], padding="VALID", ) patch_dims = patches.shape[-1] patches = tf.reshape(patches, [batch_size, -1, patch_dims]) return patches def get_config(self): config = super(Patches, self).get_config() config.update({ 'patch_size': self.patch_size, }) return config Second Layer class PatchEncoder(layers.Layer): def __init__(self, num_patches, **kwargs): super(PatchEncoder, self).__init__() self.num_patches = num_patches self.projection = layers.Dense(units=projection_dim) self.position_embedding = layers.Embedding( input_dim=num_patches, output_dim=projection_dim ) def call(self, patch): positions = tf.range(start=0, limit=self.num_patches, delta=1) encoded = self.projection(patch) + self.position_embedding(positions) return encoded def get_config(self): config = super(PatchEncoder, self).get_config() config.update({ 'num_patches': self.num_patches, }) return config Layer Passing Arguments: loaded_2 = keras.models.load_model(r"E:\FYPProject\Notebooks\vit.h5", custom_objects={"Patches": Patches, "PatchEncoder":PatchEncoder}) print("Loaded Model With Custome Layers/Objects", loaded_2) -
How to display the user id in django
I have a function in which I have to, among other things, pass to the template the ids of the users who conducted the correspondence, but I get an error in the line: pk_list = messages.values('user_from__pk').distinct() views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values('user_from__pk').distinct() correspondents = get_user_model().objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'],correspondents=correspondents) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message Error: TypeError: Field 'id' expected a number but got {'user_from__pk': 1}. how can I fix this error? -
Django Channels message read and unread
I am new to django channels and trying to build a chat app, I met some trouble in developing read and unread functioning, I hope you can give me a hand. chat consumer has a very simple structure: room name chat_1 is for user 1 to receive message. whoever connects to it, can send message to user 1, and database save method is defined in consumer which takes self.scope["user"] as sender, and self.room_name as receiver to create message record and mark it as unread user has a friend list, by clicking on the name, load all messages, meanwhile mark all messages to read, I did this by ajax function rather than ws as user click away from talking target. but here is one scenario, where two user is on each other's page and does not click anyone else, I need to init the message with read already when creating to database. let's say user_1 is talking to user_22, user_1 connect to many ws, but currently facing ws_22 to send message to user_22. In the receive method, how can I determine whether user_22 is currently facing ws_1 which waiting for the message? by saying facing, I does not mean connect to … -
django-tenants basics: SHARED_APPS vs TENANT_APPS
I am using django-tenants for a multi-tenant app. In the docs it talks about setting up SHARED_APPS and TENANT_APPS. SHARED_APPS is a tuple of strings just like INSTALLED_APPS and should contain all apps that you want to be synced to public If I want an app (e.g. django.contrib.auth) to be accessible on both the public schema and shared schema, do I include it only in the SHARED_APPS or do I need to include it in both SHARED_APPS and TENANT_APPS? "SHARED" would imply that everything in this list is accessible via all tenants and the public schema, but the docs seem to imply otherwise? -
how to pass user id values to parameters in django?
I have a code where I need to pass the user_from id (the user from whom the message comes), but when I write user_from__pk writes an error that there is no such name NameError: name 'user_from__pk' is not defined My code: views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values(user_from__pk).distinct() correspondents = get_user_model().objects.filter(pk__in=list(pk_list)) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'], correspondents=correspondents) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message how can I pass the user_from id in the line: pk_list = messages.values(user_from__pk).distinct() -
Data fetching issues from table which is using jinja2 (django)
I have a table which contains some list of student from my database, I want to fetch data from that html table which contains data from database but I want to add if the student is present or not. I have a code which works perfectly but there is an issue that my functions only takes last row data and skips all other rows. HTML code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table"> <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {% for student in students %} {% if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year %} <tr> <td style="color:white;"><input type="hidden" name="student_name" value="{{student.id}}" >{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> </td> </tr> {% endif %} {% endfor %} </tbody> </table> <div class="form-group"> <button type="submit" class="btn … -
Django form not saving - cannot identify problem with code
Trying to save the below form, but it's not saving. The traceback doesn't identify any problem, and print(form.errors) doesnt not return any issue. I have the exact same code working for another page. So I am not sure what I am missing here. There has to be a typo, I cannot find it. You will notice that I have an autocomplete function in my template. I initially thought autocomplete was not returning data in all the fields, so also tried to input data manually but not luck either. Also tried with and without is_ajax but same result. Models class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True) country_1 = models.CharField(verbose_name="Country1",max_length=100, null=True, blank=True) country_2 = models.CharField(verbose_name="Country2",max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True) latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True) phone = models.CharField(max_length=120) web = models.URLField('Website Address') email_address = models.EmailField('Venue Email Address') def __str__(self): return str(self.name) if self.name else '' Form class VenueForm(ModelForm): name = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"name"})) address = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'id':"address"})) town = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"town"})) county = forms.CharField(max_length=100, required=True, widget = forms.TextInput(attrs={'id':"county"})) post_code = forms.CharField(max_length=8, required=True, … -
Django - Default on multiple radio buttons
I am making an absence control where you select the presence/absence per user through a radio button. This absence control is already working. But right now, when you save the absences and re-open the page, all the radio buttons are unselected so it is not possible to see what was filled in. How can I fix this so you can see in which way the radio buttons where selected? The absence control is saved through this view: def baksgewijs_attendance(request, baksgewijs_id, peloton_id): peloton = Peloton.objects.get(id=peloton_id) users = peloton.users.all() baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) random_list = list() for usertje in users: if Absences.objects.filter(date=baksgewijs.date, user=usertje).exists(): random_list.append(getattr(Absences.objects.get(date=baksgewijs.date, user=usertje), "explanation")) else: random_list.append("") zipped_list = zip(random_list, users) if request.method == "POST": print(request.POST) id_list = request.POST.getlist('id') for id in id_list: if request.POST.getlist(id): attendance = Attendance() attendance.user = User.objects.get(pk=id) attendance.attendance = request.POST.getlist(id)[0] attendance.baksgewijs = Baksgewijs.objects.get(id=baksgewijs_id) attendance.save() message = messages.success(request, ("De aanwezigheid is opgeslagen")) return HttpResponseRedirect(reverse("baksgewijs_index"), {"message" : message}) return render(request, "baksgewijs/mbaksgewijs_attendance.html", { "users" : users, "peloton" : peloton, "baksgewijs" : baksgewijs, "zipped_list" : zipped_list }) This is baksgewijs/mbaksgewijs_attendance.html: <form action="{% url 'create_attendance' baksgewijs.id peloton.id %}" method="post"> {% csrf_token %} <div class="table-responsive fixed-length"> <table id = "userTable" class="table table-striped table-hover table-sm table-bordered"> <tbody> {% for reason, user in zipped_list %} <tr> … -
why are my forms not valid (both forms.Form and ModelForm), and why is it not saving data to data base?
views.py my view contains two form, userform which I created with forms.Form and snippetform which I created with ModelForm. from django.shortcuts import render from .forms import Snippetform, Userform from .models import User, Snippet from django import forms # Create your views here. def user(request): form = Userform() if request.method == "POST": form = Userform(request.POST) if form.is_valid(): username = form.cleaned_data["username"] fname = form.cleaned_data["fname"] lname = form.cleaned_data["lname"] email = form.cleaned_data["email"] password = form.cleaned_data["password"] password2 = form.cleaned_data["password2"] new_user = User.objects.create(username,fname,lname,email,password,password2) new_user.save() return render(request,'my_app/user.html',{'form':form}) def snippet(request): form = Snippetform() if request.method == "POST": form = Snippetform(request.POST) if form.is_valid(): form.save() else: print(form.errors.as_data()) return render(request,'my_app/snippet.html',{'form':form}) def thanks(request): return render(request,'my_app/thanks.html',) forms.py from django import forms from . models import Snippet class Userform(forms.Form): username = forms.CharField() fname = forms.CharField(label="First name") lname = forms.CharField(label="Last name") email = forms.EmailField(label="E-mail") password = forms.IntegerField(required=False) password2 = forms.IntegerField(label="Confirm password",required=False) class Snippetform(forms.ModelForm): class Meta: model = Snippet fields = ("name","body") models.py from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=100) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) email = models.EmailField(max_length=30) password = models.IntegerField() password2 = models.IntegerField() class Snippet(models.Model): name = models.CharField(max_length=50) body = models.TextField(max_length=150) urls.py from django.urls import path from . import views #registered namespace for my app name which … -
Django models for questionaire with questions with different answer types
This question is similar to Designing Django models for questions to have different answer types but hopefully more specific. For my particular case I can see different ways for an implementation but I am not sure what a good way would be. I have a base usermodel. Users are presented with a questionnaire which can be the same for different user but can also be different from one user to another and also might be different on different days for a single user. Each questionnaire has different questions and the questions might have different answer types (text, int, etc). At the end I want a list of the questionnaires with answers for a specific user (e.g. of the past week for user X). I guess one way to implement this would be to only have one answer type (text) and let the form handle the validation and let the view handle the rendering with correct answer formatting: class Question(models.Model): question_text = models.CharField() answer_type = models.CharField() class Questionnare(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) questions = models.ManyToManyField(Question, through='Answer') date = models.DateField(auto_now_add=True) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) questionnaire = models.ForeignKey(Questionnare, on_delete=models.CASCADE) answer = models.TextField() Maybe another way would be to have different Answer … -
How to integrate Django web application with blockchain? [closed]
I need to integrate a Django application with blockchain. But I can't figure out how to do that. The main theme is I need to store some user information on the blockchain and connect it through a Django table which will link to the blockchain. -
static/home/bootstrap/css/bootstrap.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
when I run normally code on local machine , it's working fine , but on heroku production from github it shows only html , no js , css working ...enter code here it sends this error I test my application on apple safari, chromium, firefox, google chromes ... The resource from “https://mywebsite.herokuapp.com/static/home/bootstrap/css/bootstrap.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). The resource from “https://mywebsite.herokuapp.com/static/home/js/masonry.pkgd.min.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). -
Is it better to deploy django to production with docker or without docker?
JUST FOR TECHNICAL ADVICE Please the question above is not complex, but I need extra professional advice, I have been using docker for years now and I am thinkng of the possibility of making a switch to dockerless or containerless deployment of django Despite docker has its pros and cons, I need more technical advice on which way to go Using without docker may refer to a single point of failure, but at the same time, I dont know using docker how it can completely match for this case -
Cannot import Django
During an online course, I came across this error! According to the error, Django isn't available on my machine. Tried reinstalling the same, but got the same error! Was checking for errors when I came across this error in VS code. Tried various solutions found online but to no avail. Please help! -
Set Apache to prompt a password for a Django site?
I have a Django wsgi site that I would put online soon. I would rather the site to not be accessible except through an Apache login prompt until it is ready. I investigated and found limited or outdated information about how to do it (which I tried anyway). There is more information to make it work with a plain Apache served webpage and I was able to made it work on my default Apache welcome page, but Django seems less documented in that regard. For example I added something like this in my .conf file: <Directory "/path/to/djangosite"> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require valid-user </Directory> where /path/to/djangosite is where wsgi.py resides. Password was set in .htpasswd successfully. How are you all doing this? -
Unwanted glassy border outside of background images
I'm using Django, HTML and CSS to build a website to post some pictures, but I'm fairly new. I'm using a <div> with backgound-image style to load picture on a website. For some reason, every picture is loaded with some border radius (even though I don't have any in my CSS) and it has this weird glassy-looking border, some of the pictures also have a black line among some of the borders. Here is how it looks like. My html file: <div class="container"> <div class="photo-grid"> {% for i in image|dictsort:'pub_date' %} {% if i.is_tall == True and i.is_wide == False %} <div class="card" style="background-image:url('{{i.image.url}}')"> {{i.title}} </div> My CSS file: .container { display: flex; justify-content: center; justify-items: center; } .photo-grid { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); grid-auto-rows: 240px; margin-top: 75px; margin-bottom: 3vw; width: 1500px; } .card { display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%; width: 100%; overflow: hidden; background-size: cover; background-position: center; background-repeat: no-repeat; } I have no idea what could be wrong with it. I tried deleting random lines of CSS, but nothing seemed to be working. -
Django no reverse match at
I have a problem with my code I'm trying to create an edit button to modify the employees subsequently displayed and make the changes but I can't display with dynamic url in django. views.py def editerEmploye(request, pk): editer = Employe.objects.get(id=pk) context = {'editer':editer} return render(request, 'accounts/editer_form.html', context) url.py urlpatterns = [ path('', views.home), path('dashboard/', views.home, name="dashboard"), path('employe/', views.employe, name="employe"), path('disciplinaire/', views.disciplinaire, name="disciplinaire"), path('employe_form/', views.createEmploye, name="employe_form"), path('editer_form/<str:pk>/', views.editerEmploye, name="editer_form"), employe.html <td><a href="{% url 'editer_form' employe.id %}">Editer </a> models.py class Employe(models.Model): Matricule = models.CharField(max_length=10, null=False) Prenom = models.CharField(max_length=40, null=True) Nom = models.CharField(max_length=40, null=True) Tel = models.CharField(max_length=20, null=True) Adresse = models.CharField(max_length=100, null=True) Courriel = models.CharField(max_length=100, null=True) Horaire = models.CharField(max_length=50, null=True) Date_embauche = models.CharField(max_length=100, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) screenShot of the page -
Django templating for loop working for the first item
Can't really find out what am doing wrongly !! I created a template that has a view and in that view I created a context dictionary which contain filtered orders for a specific user but for some reason in the template I created a loop for order details with a button which allows the user to see more order details but its working only for the first order item my order model class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) total = models.FloatField(max_length=15,null=True, blank=True) shipping = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=15, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) delivery = models.CharField(max_length=200, default="3-20 business days", blank=True, null=True) def __str__(self): return str(self.id) my view: @login_required(login_url="login") def user_Orders(request): user = request.user.customer orders = Order.objects.filter(customer=user).filter(complete=True) return render(request, 'shop/orders.html', {'orders':orders, "user":user}) my template <h3 style="color: #0457ae;padding-left: 40px;"><u>YOUR ORDERS</u></h3> {% for order in orders %} <p>Order total: ${{order.total}}</p> <p>Status: Paid</p> <p>Transaction id/tracking number :<span id="trans_id">&nbsp;{{order.transaction_id}}</span></p> <button id="myBtn" class="btn btn-outline-primary">more details</button> <div id="myModal" class="modal"> <!-- Modal content --> <div class="modal-content"> <span class="close">&times;</span> <center><u>More order details</u></center> <p>shipping to :{{order.shipping}}</p> <p>Estimated delivery: {{order.delivery}}</p> <p>phone: {{order.phone}}</p> </div> </div> {% endfor %} </div> the images below shows the output ... I want … -
When setting use multiple databases getting error settings.DATABASES is improperly configured
I am trying to setup multiple databases in django and I am getting error message when trying to submit information using website form. The web form still submits data but shows error message. Also I am able to access the django admin page successfully. error: ImproperlyConfigured at /signup settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. Here is the code of my settings.DATABASES DATABASES = { 'default': { }, 'users_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'users.db.sqlite3', } } here is DATABASE_ROUTERS=['routers.db_routers.AuthRouter',] below is code for Auth Router: class AuthRouter: router_app_labels={'auth','user','contenttypes','sessions','admin' } def db_for_read(self, model, **hints): if model._meta.app_label in self.router_app_labels: return 'users_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.router_app_labels: return 'users_db' return None def allow_relation(self, obj1, obj2, **hints): if( obj1._meta.app_label in self.router_app_labels or obj2._meta.app_label in self.router_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.router_app_labels: return db == 'users_db' return None Would like to see the reason for this error and resolution. I have already done data migration for users_db A simple successfull example of implementation of github code would also help if solutions don't work. -
What is the most Django-appropriate way to combine multiple database columns into one model field?
I have several times come across a want to have a Django model field that comprises multiple database columns, and am wondering what the most Django way to do it would be. Three use cases come specifically to mind. I want to provide a field that wraps another field, keeping record of whether the wrapped field has been set or not. A use case for this particular field would be for dynamic configuration. A new configuration value is introduced, and a view marks itself as dependent upon a configuration value, redirecting if the value isn't set. Storing whether it's been set yet or not allows for easy indefinite caching of the state. This also lets the configuration value itself be not-nullable, and the application can ignore any value it might have when unset. I want to provide a money field that combines a decimal (or integer) value, and a currency. I want to provide a file field with a link to some manner of access rule to determine whether the request should include it/a request for it should succeed. For each of the use cases, there exists a workaround, that in each case seems less elegant. Define the configuration fields … -
How make buttons in all cards clickable?
Hi I created a web app with Django. In this app there are 6 cards with a button for increase and a button for decrease the quantity of food to buy. I have a problem: only the buttons in the first card work. Here's the HTML code <div class="container"> <div class="row"> {% for roll in rolls %} <div class="col-4"> <div class="card" style="width: 16rem;"> <img src="{{ roll.immagine.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ roll.nome }} Roll</h5> <p class="card-text">€ {{ roll.prezzo }}</p> <button id="incrementBtn" style="border-radius: 8px; background-color:orange;">+</button> <span id="counter">0</span> <button id="decrementBtn" style="border-radius: 8px; background-color: lightsalmon;">-</button> <a href="{% url 'ordina' %}" class="btn btn-primary">Acquista</a> </div> </div> </div> {% endfor %} </div> </div> Here's the Javascript code: document.addEventListener("DOMContentLoaded", function() { let idCounter = "counter1, counter2, counter3, counter4, counter5, counter6"; let arrIdCounter = idCounter.split(", "); console.log(arrIdCounter); let valueCounter = document.getElementById('counter').innerHTML; const incrementBtn = document.getElementById('incrementBtn'); const decrementBtn = document.getElementById('decrementBtn'); incrementBtn.addEventListener('click', () => { console.log(valueCounter); valueCounter++; document.getElementById('counter').innerHTML = valueCounter; console.log(valueCounter); }); decrementBtn.addEventListener('click', () => { if (valueCounter > 0) { valueCounter--; } document.getElementById('counter').innerHTML = valueCounter; }); }); -
How to write custom validation on django rest framework?
How to write custom validations on drf. I have validate function on serializer. Can someone help whats wrong with my code? my views: class MyCustomView(ListCreateAPIView): def create(self, request, *args, **kwargs): serializer = MyCustomSerializer(data=request.data) serializer.is_valid(raise_exception=True) my serializer: class MyCustomView(serializers.Serializer): name = serializers.CharField(required=True, max_length=64) address = serializers.CharField(required=True, max_length=64) def validate(self, attrs): if not attrs.get('name'): raise serializers.ValidationError('Name field is required.') when i request with blank name and address it shows default drf error. How to override this function? -
Why my form isn't valid in view whatever I type in?
I am trying to create authentication app with form and it isn't working. I have put some print functions in my view and it prints post and than not valid. I want to click submit button which would trigger post request and view would create new user. view.py def index(request): form = forms.RegisterForm() context = { 'form': form } if request.POST: print('post') if form.is_valid(): print('valid') form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password') account = authenticate(email=email, password=raw_password) print('authenticate') login(request, account) return redirect('home') else: print('not valid') context['registration_form'] = form else: form = forms.RegisterForm() context['registration_form'] = form return render(request, 'index.html', context) html <!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>Document</title> </head> <body> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </body> </html> forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField User = get_user_model() class RegisterForm(forms.ModelForm): """ The default """ full_name = forms.CharField(max_length=30) password = forms.CharField(widget=forms.PasswordInput) password_2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ['email'] def clean_email(self): ''' Verify email is available. ''' email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean(self): ''' Verify both passwords match. ''' … -
PyCharm doesn't recognize user instance when using custom user model in Django
I have a custom user model in my Django project and when I create an instance of request.user in my views PyCharm doesn't seem to recognize the user instance correctly. The available methods/attributes suggested by PyCharm still point to the built-in Django user model but not to my new one. Is there any way to set this up properly? Example: # settings.py AUTH_USER_MODEL = 'user.UserProfile' # models.py custom user model class UserProfile(AbstractBaseUser, PermissionsMixin): # Email and name of the user email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) # Privilege and security booleans is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) email_confirmed = models.BooleanField(default=False) # Company on whose behalf the user acts on company = models.ForeignKey('company.Company', on_delete=models.CASCADE, blank=True, null=True) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def email_user(self, subject, message, from_email=None, **kwargs): """Send mail to user - Copied from original class""" send_mail(subject, message, from_email, [self.email], **kwargs) def __str__(self): return self.email # views.py def render_dashboard_benefits(request): # Get current user instance current_user = request.user # Typing... current_user.company # Pycharm suggests 'first_name' and 'last_name' depending on the initial user model # but not e.g. "email" or "company" according to the new user model return render(request, 'test.html') I'm using the paid PyCharm …