Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do a calculation using angular
I am new to angular and I am trying to calculate the salary of an employee when his ID, his basic salary and the relevant month is given. For this, I should add the total additions and substract the total deductions from the basic salary to calculate the final salary. Currently I am having this angular form where the id, basic salary and the month is provided. <div class="row justify-content-center"> <div class="col-md-11"> <nb-card> <nb-card-header>Add Salary</nb-card-header> <nb-card-body> <form class="form-horizontal"> <fieldset> <legend>Details</legend> <br> <div class="form-group row"> <label for="id" class="label col-sm-3 form-control-label">Name</label> <div class="col-sm-9"> <nb-select id="id" name="id" [(ngModel)]="salary.id" placeholder="Select ID" [(selected)]="selectedItem"> <nb-option *ngFor="let usr of users" value="{{usr.id}}">{{usr.username}}</nb-option> </nb-select> </div> </div> <div class="form-group row"> <label for="month" class="label col-sm-3 form-control-label">Month</label> <div class="col-sm-9"> <input type="number" nbInput fullWidth id="month" name="month" [(ngModel)]="salary.month" placeholder="Month"> </div> </div> <div class="form-group row"> <label for="date" class="label col-sm-3 form-control-label">Issue Date</label> <div class="col-sm-9"> <input nbInput type="date" id="date" name="date" [(ngModel)]="salary.issueDate" placeholder="Date"> </div> </div> <div class="form-group row"> <label for="basicsal" class="label col-sm-3 form-control-label">Basic Salary</label> <div class="col-sm-9"> <input type="text" nbInput fullWidth id="basicsal" name="basicsal" placeholder="BasicSalary"> </div> </div> <div class="form-group row"> <div class="col-md-3 offset-md-3"></div> <div class="col-md-3 offset-md-3"> <button nbButton hero status="success" (click)="onCalculate()">Calculate</button> </div> </div> </fieldset> <div class="form-group row"> <div class="col-6"> <fieldset> <legend>Additions</legend> <br> <div class="form-group row"> <label for="addition" class="label col-sm-3 form-control-label">Total … -
Django copy pdf to s3bucket
I am in trouble saving my local file to s3bucket. I have a corn job in my Django project, after a certain time, it generates a pdf file. And I want to save the file in s3bucket. Currently, Django s3bucket is working very well like saving my uploaded file to s3bucket and lots more thing is working. But I am not getting how to copy local file and save in s3bucket. CURRENTLY I AM SAVING THIS IN MY LOCAL MACHINE LIKE THIS WAY: shutil.copyfile('/var/www/local.pdf' ,'media/newfileins3bucket.pdf') But it will not works that way i want to save it directly to s3bucket. Can anyone help me in this case? -
Django Rest API that takes in SQL query and return the result of the executed query from Database
I'm trying to design a dynamic API with Django Rest and the requirement is slightly unique. The API is meant to take in an SQL query and execute that query and return the result of that query. So basically it can be a GET request that returns some data, or a POST request that inserts some data. I currently have no idea how this can be achieved so any advice/example would be greatly appreciated. And also, will it be simpler to go with plain Django, or with Django Rest Framework? Thank you! -
Custom User model does not follow with the extended BaseUserManager implementation in django admin
I am a a newbie in django and currently I am exploring with creating Custom User model subclassing the AbstractBaseUser in django. I wrote the following code for the userModel and BaseUserManager implementation. from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.contrib.auth.base_user import BaseUserManager from django.utils import timezone class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): values = [email] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError("The {} value must be set".format(field_name)) email = self.normalize_email(email) extra_fields.setdefault("username", email) #this line of code here user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) extra_fields.setdefault("username", email) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) username = models.CharField(unique=True, max_length=200) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) address = models.CharField( max_length=200, ) latitude = models.FloatField(default=0.00, blank=True) longitude = models.FloatField(default=0.00, blank=True) … -
The view lessons.views.login didn't return an HttpResponse object. It returned None instead
i started to learn django, im getting The view lessons.views.login didn't return an HttpResponse object. It returned None instead. i dont know where i'm making mistake. my HTML codes <div class="formBx"> <form method="POST"> {% csrf_token %} <h2>Sign In</h2> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="" value="Login"> <p class="signup">Don't have an Account?<a href="#" onclick="toggleForm();">Sign Up.</a></p> </form> </div> </div> <div class="user signUpBx"> <div class="formBx"> <form method="POST"> {% csrf_token %} <h2>Create an account</h2> <input type="text" name="username1" placeholder="Username"> <input type="email" name="email" placeholder="E-mail"> <input type="password" name="password1" placeholder="Create Password"> <input type="password" name="confirm" placeholder="Confirm Password"> <input type="submit" name="" value="Register"> <p class="signup">Already Have an Account?<a href="#" onclick="toggleForm();">Sign In.</a></p> </form> </div> <div class="imgBx"><img src="{% static 'img/logbg2.jpg' %}"></div> </div> </div> My views.py codes def login(request): if request.method == "GET": return render( request,"login.html") if request.method == "POST": if request.POST.get("submit") == "Login": if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(username = username,password=password) if user is None: messages.info(request,"Username or password is incorrect") return render(request,"login.html") messages.success("Logged In") login(request,user) return render(request,"index.html") elif request.POST.get("submit") == "Register": if request.method == "POST": username = request.POST["username1"] email = request.POST["email"] password = request.POST["password1"] confirm = request.POST["confirm"] if password and confirm and password != confirm: newUser = (User.objects.create_user(username,email,password)) newUser.save() login(request,newUser) return render(request,"login.html") … -
How to make notification system with django framework?
Well i am actually wanting to build notification system with Django, When someone follow to some other people than they get notify or when someone like other people posts than those people also get notify. I just to want know which will be the best approach for building this notification system with Django framework and which Django tools i suppose to use such as Django signals or Django built in messages etc? please tell me the best and easy way to build such notification system with Django quite similar to Instagram or Facebook notification system since Instagram also use Django for its back-end so at least i know this is possible with Django but i don't know the path or complete track of building that system. Many thanks in advance!. -
Secured connection with Heroku and CORS
I have a Django/ Vue.js app deployed on Heroku. When I open the app for the first time it's none secured (http://) and I have issues with the CORS because my app won't permit connections from an insecured website to my secured endpoints. But as soon as I log in, my site turns into a secured one and I have no more issus with the CORS. As I log out, no issues whatsoever. My question is what can I do to have my website secured as soon as it's open? Do I have to change the CORS settings? Or the Heroku settings? -
Django Models get all models with the objects with the a ForeignKey's
I would like to have a method which I can call and the return will be something like this (dict, list or queryset doesn't matter to me): { 'name': 'test', 'long': '1.2345', 'lat': '1.2345', 'measurements': [ { 'time': datetime 'value': 3245.2 }, { 'time': datetime 'value': 3213.1 }, ] } I have the following models: class Block(models.Model): id = models.AutoField(primary_key=True, auto_created=True) long = models.DecimalField(default=0.0, max_digits=9, decimal_places=7) lat = models.DecimalField(default=0.0, max_digits=9, decimal_places=7) class BlockMeasurement(models.Model): block = models.ForeignKey(Block, on_delete=models.SET_NULL, null=True) value = models.DecimalField(default=0.0, max_digits=9, decimal_places=2) time = models.DateTimeField(default=datetime.now, blank=True) I could make a function that would loop through all of the Blocks and then add measurements to an array and later add the list of measurements to the dict, but there must be a nicer way to handle this. -
How to diagnose a segfaulting Apache ModWSGI Django site?
How do you diagnose and fix a segmentation fault in a Python process running behind Apache? I have a Django web app being served via a fairly standard Apache+ModWSGI server on Ubuntu 20. After a recent code deployment, the site's worker process now immediately crashes upon startup, with the error: [core:notice] [pid 32373:tid 140340980481088] AH00051: child pid 32375 exit signal Segmentation fault (11), possible coredump in /etc/apache2 I've roughly identified the Python code that appears to trigger the crash, which is a new O365 package import. However, the package is pure Python, and only references a few generic external packages like requests and python-dateutil. There's nothing exotic or unstable in it that would cause Apache to crash. I've encountered this type of issue before with Apache, but it's very rare, and none of my past tricks have fixed it. I've tried upgrading all system packages, tweaking some Apache settings like KeepAlive, disabling some unnecessary modules, and changing the location of the import to load dynamically during the request, but nothing's had any effect. I have LogLevel debug set but Apache still isn't outputting anything besides the above line and the normal "Starting process" type messages. -
how to get first news of any category in Django?
i created 2 table News and Category at models.py file in my Django project. I use first_news = News.objects.first() to have the first news in database. How can i do if i want to get first news of any category? -
how much mysql knowledge i need for python django? and how to be more efficient in back end development?
i recently learned basics of python and library like requests , and i want to go ahead for django and back end development with python , but i need some help, and i didnt find my answers in google how much database knowledge i need? i know , for a back end developer , i should know how database works and what is sql and nosql databases i know what are these, but going further and deeper, in technical section, how much i should learn, to be more efficient? my knowledge about sql , nosql , how they work + mysql.connector and pymongo python libraries , is enough? do you have any suggetion for me to become a back end developer? -
Django admin template not loading (Wrong path)
When i try to load my web page, i get: Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /usr/lib/python3/dist-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/lib/python3/dist-packages/django/contrib/auth/templates/index.html (Source does not exist) Inside django/contrib/admin/templates/ there are two folders, admin and registration. The correct path would be django/contrib/admin/templates/admin/index.html The path is almost correct, but not quite. How do i go about this? Thank you. -
why it cant find the image , please view the image
here the error I put the image everywhere also in src I change the direction like ../ or ../.. but it did not find it -
Django objects.get() function does not work but objects.filter().first() works
When I look up for the user with User.objects.get(username=username) it shows error User matching query does not exist but it works fine with User.objects.filter(username=username).first() why does this happen? -
Create a table in dbshell with django
here is my code : frontgreat=> CREATE TABLE contact_titlemessagesuggestion; ERROR: syntax error at or near ";" LINE 1: CREATE TABLE contact_titlemessagesuggestion; i don't understand why it's not working and why it's an syntax error. frontgreat=> DROP TABLE contact_titlemessagesuggestion; ERROR: table "contact_titlemessagesuggestion" does not exist have no syntax error and work fine. Regards -
post related with django-taggit not showing results
tried to build related post on post detail view using django-taggit plug-in, everything seem right but no result. views.py def news_detail(request, post): post = get_object_or_404(Article, slug=post, status=“published”) post_related = post.tags.similar_objects() return render( request, “blog/post/news_detail.html”, {“post”: post, “post_related”: post_related}, ) news_detail.html {% extends "blog/base.html" %} {% block content %} <img src="{{ post.images.url }}" width="100%"> <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|linebreaks }} <p> {% for tag in post.tags.all %} <a href="{{ tag.slug }}">{{ tag.name }}</a> {% endfor %} </P> {% for post in post_related %} <h1>{{ post.post_title }}</h1> {% endfor %} {% endblock %} thanks for any help -
Download file after payment with Django
I am building a digital ecommerce platform with Django. When my customers pay for a digital product, I want that the digital product gets downloaded immedately after payment. So when they complete a payment they get automatically the file downloaded. For now after a payment I am getting rendered back to the home page and get a succesful payment. But instead of rendering back to home page I want the file to be downloaded after payment, so I want to be rendered to something like I return redirect( {{item.file.url}} ) instead of return redirect("/" ) (see last line of Views). My code in Views and Models is as follows: Views class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) context = { 'order': order } return render(self.request, 'dashtemplates/payment.html', context) def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token ) #create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() #assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your order was succesful!") return redirect("/" ) Models … -
is_valid() not running after my form request.POST
This is my views.py. I am creating my product from by creating an object and trying to store values posted from my html form This is my models. My product form inherits all of the fields from the models. -
Why is Django ORM so slow?
This code - raw SQL - takes 2.6 sec: ''' q_sku = MainData.objects.raw(f'SELECT id as id, COUNT(DISTINCT sku) as "count" FROM imports_maindata WHERE feed_id={feed.id}') q_loc = MainData.objects.raw( f'SELECT id as id, COUNT(DISTINCT locale) AS "count" FROM imports_maindata WHERE feed_id={feed.id}') q_spec = MapSpecs.objects.raw( f'SELECT id as id, COUNT(DISTINCT f_feat_id) AS "count" FROM imports_mapspecs WHERE feed_id={feed.id}') q_mapped = MapSpecs.objects.raw( f'SELECT id as id, COUNT(DISTINCT ic_feat_id) AS "count" FROM imports_mapspecs WHERE feed_id={feed.id} AND ic_feat_id IS NOT NULL') q_date = MainData.objects.raw( f'SELECT id as id, MAX(last_update) as "last_date" FROM imports_maindata WHERE feed_id={feed.id}') print(q_sku[0].count, q_loc[0].count, q_spec[0].count, q_mapped[0].count, q_date[0].last_date) ''' While this one - ORM only - takes 3.1 sec: ''' f = Feed.objects.all() for feed in f: prods_count = f.filter(maindata__feed_id=feed.id).values('maindata__sku').distinct().count() locales_count = f.filter(maindata__feed_id=feed.id).values_list('maindata__locale', flat=True).distinct() total_specs = f.filter(mapspecs__feed_id=feed.id).count() mapped_specs = f.filter(mapspecs__feed_id=feed.id, mapspecs__ic_feat_id__isnull=False).all().count() try: last_update = f.filter(maindata__feed_id=feed.id).values('maindata__last_update').distinct().order_by('-maindata__last_update').first()['maindata__last_update'] except TypeError: pass ''' And this one, using ORM but different approach, is returned in 3.1-3.2 sec: ''' f = Feed.objects.all() prods = f.annotate(num_prods=Count('maindata__sku', distinct=True)) locs = f.annotate(num_locs=Count('maindata__locale', distinct=True)) total_sp_count = f.annotate(num_books=Count('mapspecs__f_feat_id', distinct=True)) total_sp_mapped = f.filter(mapspecs__ic_feat_id__isnull=False).annotate( num_books=Count('mapspecs__ic_feat_id', distinct=True)) ''' So how come that Django ORM is so inefficient and slow? The timings are for a low number of rows in DB (below 50K)... So it's not only slower than raw … -
How to write URL and VIEWS
Below is my model class Movie(models.Model): name = models.CharField(max_length=55) artists = models.ManyToManyField(Artist) def __str__(self): return self.name Below is the View: def moviesView(request): movies = Movie.objects.all() context = { "movies": movies } return render(request, 'movies/movies.html', context=context) def movieView(request, name): print(name) movie = Movie.object.get(name=name) context = { "movie": movie } return render(request, 'movies/movie.html', context=context) Below are the URLS: urlpatterns = [ path('movies', moviesView, name='movies'), re_path('movies/(\d+)', movieView, name='movie'), path('artists', artistView, name='artists') ] Below is the template: <h1>Movies</h1> {% for movie in movies %} <a href="{% url 'movie' movie.name %}">{{ movie.name }}</a> <h3>{{ movie.name }}</h3> {% for artist in movie.artists.all %} <ul> <li><a href="{{ artist.wiki }}">{{ artist.name }}</a></li> </ul> {% endfor %} {% endfor %} If I click a movie avengers, it should carry to another page with movie details of avengers as mentioned in the model: I need to frame the url as: http://127.0.0.1:8000/movies/avengers -
How do I pass parameter to the form in Django?
So as the title states, I'm trying to pass a parameter from views to forms. I've seen several Stack Overflow posts regarding this issue, but none of them solved my problem :( So what I'm trying to build is basically a question-and-answer application. Each user answers to pre-provided questions. I want to make an answering template for each corresponding question. So here's my code: forms.py class AnswerForm(forms.ModelForm): main_answer = formsCharField(required=True) # Some other fields def __init__(self, *args, **kwargs): self.q = kwargs.pop('q') super(AnswerForm, self).__init__(*args, **kwargs) self.fields['main_answer'].label = q.main_question views.py def createAnswer(request, pk): thisQuestion = Question.objects.get(question_number=pk) AnswerFormSet = modelformset_factory(Answer, form=AnswerForm(q = thisQuestion), extra=1) formset = AnswerFormSet(queryset=Answer.objects.filter(authuser=request.user.id, question_number=pk)) # And some other codes I'm supposed to show this formset in my template using {% crispy_formset%}. However I keep getting this error: "name 'q' is not defined". What is the problem here? -
How to remove the default order by set by Django admin changelist on primary key
Django admin automatically sets sorting on primary key when rendered on changelist (Django Admin) which causes quite a lot amount of query cost of data (5-6lakhs) records. The same issue is faced due to which the page is giving 504. How can the default sorting be removed. I have checked and the ordering is set in base class (main.py) in get_queryset (method). Overriding that particular method causing extra queries. What can be the best way to remove that default ordering. -
Django: Included template does not appear
I am implementing messages system with ajax. Everything works fine when I post new message. I mean new message appears without reloading, but when I go to create message page I cannot see included template(with messages), it includes after posting message. I tried to include other template and it worked. My code below, thanks for help in advance. views.py class MessageCreateView(CreateView): model = Message fields = ['content'] template_name = 'users/create_message.html' def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): if request.method == 'POST': sender = self.request.user.profile receiver_pk = self.kwargs['profile_pk'] print(receiver_pk) receiver = Profile.objects.get(id=receiver_pk) new_message = Message.objects.create( message_by=sender, message_to=receiver, content = form.cleaned_data['content']) return JsonResponse({'message': model_to_dict(new_message)}, status=200) else: return self.form_invalid(form) def get_context_data(self, **kwargs): context = super(MessageCreateView, self).get_context_data(**kwargs) context['profile_pk'] = self.kwargs['profile_pk'] return context def messages(request, profile_pk): current_user_profile = request.user.profile second_profile = Profile.objects.get(pk=profile_pk) messages = Message.objects.filter( Q(message_to=current_user_profile, message_by=second_profile)| Q(message_to=second_profile, message_by=current_user_profile)).order_by('date_of_create') context = { 'messages': messages } return render(request, 'users/messages.html', context=context) urls.py urlpatterns = [ path('login/', CustomLoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('register/', register, name='register'), path('profile/<int:pk>/', ProfileDetailView.as_view(), name='profile_detail'), path('profile/follow/<int:pk>', follow_profile, name='follow_profile'), path('results/', search, name='search'), path('create_message/<int:profile_pk>/', MessageCreateView.as_view(), name='create_message'), path('messages/<int:profile_pk>/', messages, name='messages') ] create_message.html {% extends 'users/base.html' %} {% load crispy_forms_tags %} {% block title %}Chat{% endblock %} {% block content %} <div class="messages"> {% include 'users/messages.html' … -
Switch two Unique Constraint Form Fields Django
I have a Unique Constrained model where a Client can have a primary and a secondary supporter, which is indicated by a BooleanField on the model. A supporter is basically someone who if responsible for the client in an internal ticketing system. When trying to switch primary and secondary supporter in a form, or removing the current primary supporter and instead replacing it with the current secondary, the form throws a UniqueConstraint ValidationError. Any idea as to how to overcome this? Tried multiple things in regards to manipulating the forms post-validation, like reversing the supporter field changes if primary_supporter_form.initial['supporter'] == secondary_supporter_form.cleaned_data['supporter].id, flipping the BooleanFields on each form instead and removing thrown UniqueConstraint error the forms; however the forms ignore the change all together. Very frustrating, as manipulating the form post-validation doesn't seem to be documented anywhere. Models: class Client(models.Model): name: str = models.CharField(max_length=255) created: datetime = models.DateTimeField(auto_now_add=True) class ClientSupporter(models.Model): supporter: User = models.ForeignKey(User, on_delete=models.CASCADE, related_name='clients') primary: bool = models.BooleanField(default=False) client: Client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='supporters') class Meta: constraints = [ UniqueConstraint(fields=['client'], condition=Q(primary=True), name='unique_primary_supporter') ] unique_together = ('client', 'supporter') ordering = ('-primary',) Forms: class ClientSupporterForm(forms.ModelForm): supporter = forms.ModelChoiceField(queryset=User.objects.all(), required=False, label='') class Meta: model = ClientSupporter fields = ('supporter', 'primary', 'id', 'client') … -
Crontab job not executing in django project
I am using crontab to execute certain function, however when i run the server the job is not processed. When i use the command crontab show , it shows me the job , bit again when i run the server its not executed. I followed this documentation https://pypi.org/project/django-crontab/ and watched YT tutorial as well but nothing worked. crontab -l. shows this : '*/1 * * * * /Users/nourelgeziry/.local/share/virtualenvs/Equal_Distribution_maintainance-M-bcKwQz/bin/python /Users/nourelgeziry/Desktop/MyProjects/Equal Distribution maintainance/EDMS/manage.py crontab run bd84e5bec9ad4805b334e11fafec1b5c # django-cronjobs for EDMS' . Also worth mentioning i am using pipenv for the virtual env. Let me know if there is anything i can provide more . Thank you in advance