Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User Password Automatically changes in django after 15 days
I am facing a serious issue in production, that password of users table is automatically changes after 15 days or probably 2 weeks we are using:- server:- AWS server EC2 instance database:- MYSql Usertable :- Django auth table please look into this on priority -
Type error when trying to run django app on localhost
I am trying to deploy a Django app to heroku. I was able to successfully run the app on my local and I did several steps to migrate and run to heroku. After which I ran into this error when I try to run it in local and the application failed to run on Heroku. I am actually not able to determine where the problem is, is it the last line which says about str expected not function call. I am sharing the screenshot for my error. -
Django - collectstatic using incorrect declaration of STATIC_ROOT
my declaration of STATIC_ROOT doesn't seem to be used when I execute the command collectstatic: Printing from the terminal I get the correct path: STATIC_ROOT: [..]/Dev/bidding_tool_project/project/staticfiles from the python console: settings.STATIC_ROOT: Dev/staticfiles Would you have any idea how/why this happens ? -
how to retrieve data from database using raw SQL not django ORM
I have a django project that is connected to SQL server database and when i tried to click button to retrieve data from the database the system crash . i am trying to convert the below syntax in ORM into raw sql: dbEntry = Person_.objects.get(pk =pk) Note : I am not using ORM once i tried to perform the task the system crash and display: getEvents() got unexpected keyword argument "id" urls.py path("events/<int:id>/",getEvents,name = "getEvents"), views.py def getEvents(request,pid): q1 = cuesor.execute("Select Person_.ID FROM Person_ WHERE ID = pid") print("q1=",q1) qresult = q1.fetchone() print("qresult",qresult) return render(request,"connect.html",{"qresult":qresult}) list.html <form method = "GET" action = "{% url 'getEvents' obj.0 %}"# obj is the iterator --- 0 is the first field in the table == ID <button class = "btn btn-primary">get details</button> </form> display.html {% for row in qresult %} <p> {{ row.0 }} </p> {% endfor %} -
save user instance to another model after post_save django
i have to two models CustomUser and artist and what i am trying to achieve that when i create user it should automatically create artist. i don't want to add OneToOne field in artist model i just want to fill these field name, artist_category, artist_image, bio with post_save when CustomUser created. custom user model class CustomUser(AbstractBaseUser, PermissionsMixin): artist_choice = [ (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ] artist_category = models.IntegerField(choices=artist_choice, null=True) mobile_number = PhoneNumberField(null=True) city = models.CharField(blank=True, max_length=50) bio = models.TextField(blank=True) email = models.EmailField(max_length=100, unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) last_login=models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) country = CountryField() USERNAME_FIELD = 'email' EMAIL_FIELD='email' REQUIRED_FIELDS=[] objects=UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class Artist(models.Model): CHOICES = ( (0, 'celebrities'), (1, 'singer'), (2, 'comedian'), (3, 'dancer'), (4, 'model'), (5, 'Photographer') ) name = models.CharField(max_length=100) artist_category = models.IntegerField(choices = CHOICES, null=True) artist_image = models.ImageField(upload_to= 'media',null=True) bio = models.TextField(max_length = 500) def __str__(self): return self.name -
returning "non_field_errors": in Postman
There is validation in StorySerializer, which works fine. In Postman during creating story with 3+ genres it returns { "non_field_errors": [ "Max genres: 2" ] } class StorySerializer(serializers.ModelSerializer): .... def validate(self, data): if len(data['genres']) > 2: raise ValidationError('Max genres: 2') return data Can I change non_field_errors to another name? -
How to add show password icon in django-bootstrap4 login form?
I'm designing the user interface of a login page using django-bootstrap4 form. I need some help on how to add a show password icon using font-awesome in the form field. I tried adding the addon_after parameter as said in the docs (https://django-bootstrap4.readthedocs.io/en/latest/templatetags.html) but the icon did not show up. Here is the snippet of my html template: <form method="post"> {% csrf_token %} {% bootstrap_form form addon_after='<span><i class="fas fa-eye-slash"></i></span>' %} <button class="btn btn-success ml-0" type="submit">Sign In</button> <div><a href="{% url 'password_reset' %}">Forgot password?</a></div> </form> -
Django Found another file with destination path
I am trying to deploy the app on GCP but when I run the following command: python manage.py collectstatic It returns: Found another file with the destination path 'admin\css\autocomplete.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Found another file with the destination path 'admin\css\base.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. And many other like this. Here's my Settings.py STATIC_URL = 'https://storage.googleapis.com/yantra-packs/static/' # STATIC_URL = '/static/' # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static/'), ] Where is it that I am providing two paths for the static files? -
How to specify the login_url to login for django generic views
login_required decorator directly taking url from settings.LOGIN_URL. In which how can i specify login url with parameter login_url. Is this possible to specify both login_url and TemplateView.as_view() in login_required decorator urlpatterns = [ url(r'^$', login_required(TemplateView.as_view(template_name='foo_index.html')) ] -
two forloop inside in one table row
I have 2 loops from views which is generates in my table. <tr style='height:19px;'> <th id="703183278R33" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">34</div> </th> <td class="s46"></td> <td class="s51" colspan="3">Subject</td> <td class="s51" colspan="4">Teacher</td> <td class="s51" colspan="6">Room and Schedule</td> <td class="s0"></td> </tr> {% for sensie in teacher %} <tr style='height:19px;'> <th id="703183278R34" style="height: 19px;" class="row-headers-background"> <div class="row-header-wrapper" style="line-height: 19px;">35</div> </th> <td class="s46"></td> <td class="s51" colspan="3">{{sensie.Subjects}}</td> <td class="s51" colspan="4">{{sensie.Employee_Users}}</td> {% endfor %} {% for room in roomsched %} <td class="s51" colspan="6">{{room.Classroom}}-{{room.Day_Name}}</td> </tr> {% endfor %} how do i make it so that it gets formatted in table properly? just like this Subject Teacher Room and Schedule math example-Teacher room1-mwf -
I want to do different actions on clicking different buttons, the code i have written is not working?
#Template# <form action="" method="POST"> {% csrf_token %} <div class="col"><p>Firstname: {{i.fname}}</p></div> <div class="col"><p>Lastname: {{i.lname}}</p></div> <div class="col"><p>Email: {{i.email}}</p></div> <div class="col"><p>City: {{i.city}}</p></div> <div class="col"><p>Pin: {{i.pin}}</p></div> {% csrf_token %} <input type="hidden" name="Approve" value="{{ i.fname }}"> <input class="btn btn-success mx-2" type="submit" value="Approve"> <input type="hidden" name="Reject" value="{{ i.id }}"> <input class="btn btn-danger mx-2" type="submit" value="Reject"> </form> #Views.py# def adminp(request): if 'Reject' in request.POST and request.method=="POST": print("Went into reject") p=booking.objects.filter(id=request.POST.get('Reject','')).delete() elif 'Approve' in request.POST and request.POST.method=="POST": print("went into approve") x=booking.objects.all() print(x) params={'pro': x} return render(request,'dbms/adminpanel.html',params) How do i resolve the above code? In views.py always the request goes in reject itself also onclicking approve ,help please. -
What libraries should I use to develop custom shopping malls with 'react' and 'react native'?
I'm studying 'Django', 'React' and 'React-Native'. I want to develop a custom shopping mall with my personal portfolio. ex) spreadshirt https://www.spreadshirt.com/create-your-own The features I want to develop are: Image overlay Text overlay Color change Save and edit your history Because I'm studying 'React' and 'React-Native', I want to develop using 'React' and 'React-Native'. What libraries should I use to develop custom shopping malls with 'react' and 'react native'? -
Call a method for each model linstance
I have a Category model. I want to make a directory for the category everytime I create a new category. I have a method in my model called create_directory. class Category(models.Model): category_title = models.CharField(max_length=200) category_image = models.ImageField(upload_to="category") category_description = models.TextField() slug = models.SlugField(max_length=200, unique=True, default=1) def create_directory(self): gallery_path = os.path.abspath( os.path.join(settings.MEDIA_ROOT, Category.slug)) if not os.path.isdir(gallery_path): os.mkdir(gallery_path) class Meta: verbose_name_plural = "Categories" unique_together = ("category_title", "slug") def __str__(self): return self.category_title I want to call create_directory each time I create a category in the Admin panel. -
Custom activation email not working in Django
The goal is custom email with activation token. Currently, this setup works to click through to a url, but not with the activation link. The first template is the html content and the second is the message content. from_email = '<info@domain>' #this is the custom template htmly = get_template('activation.html') #this is just the template of the message message = render_to_string('activation_email.html', { 'user':user, 'token': account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) d = { 'username': username, 'url': reverse('activate', kwargs={'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))), 'uid':urlsafe_base64_encode(force_bytes(user.pk))}))} subject = 'Email activation' html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email, [request.user.email]) msg.attach_alternative(html_content, "text/html") msg.send() The error that I get is: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments If I try to send it as one template, i.e. both the message and my custom html in the message. My html renders as a string. This is the email that I'm trying to send. The activation_email has the message below and activation.html has the custom email html template. activation_email.html {% autoescape off %} Hi {{ user.username }}, Email confirmation: http://domain{% url 'activate' uidb64=uid token=token %} {% endautoescape %} url.py path('activate/<uidb64>/<token>/', views.activate, name='activate'), -
Deploying a Django app via Apache on Windows Server
I am moving to Python/Django from .NET for my upcoming project. Traditionally, using IIS is easy for us due to Windows Authentication and impersonation. However, without IIS, it is a totally new world for us as we have to deal with Kerberos directly. So far i have managed to deployed a Django app on Apache2.4 on my Windows Server VM. I am trying to get the client web browser to negotiate with my Apache web server to no avail. I have also tried to look into mod_auth_kerb, however it seems that it is mainly compatible with Linux: also checked out mod_spnego with little success. I would like to find out how I can acquire the user’s ID (so that i can make use of it for Oracle Kerberos login) when he access the website hosted on Apache. Thanks -
How to limit the amount of tags allowed in django-taggit?
I am using the django-taggit module for tagging posts on my website, however I want to limit the amount of tags allowed to only 3. I have read the documentation, and have been able to find nothing. Here is my model for Posts class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() #... other fields here tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) And now here is the views class PostListView(SelectRelatedMixin,TagMixin,ListView): model = Post hit_count = True template_name = 'mainapp/post_list.html' selected_related = ("user","group") paginate_by = 10 context_object_name = 'posts' queryset = models.Post.objects.all() def get(self,request,): posts = Post.objects.all().order_by('-published_date') users = User.objects.exclude(id=request.user.id) count= User.objects.all().count() friend, created = Friend.objects.get_or_create(current_user=request.user) friends = friend.users.all() group = Group.objects.all() args = { 'users':users, 'friends':friends, 'posts':posts, 'group':group,'count':count } return render(request, self.template_name, args) def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') Here is the form class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','group','image','file','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False self.fields['file'].required = False So I want to know how I can limit the amount of tags the user can enter for the post -
Should there be separate Django app for each user type in a Django project?
I have got multiple user types in my Django project(around 4 to 5). I am stuck with the code layout. Is it a good design to have a separate Django app for each user type? As each user will be redirected to different interface after login and each user will have different tasks to perform. Also i am thinking to make one common app for common functionality like the login, logout and also its models.py file will contain all the common models used by other apps? Please suggest the best code design for such case. -
django Meta class Fieldas and relation with database
i m begineer in django language and having difficulty in understanding django Meta class which is written inside another class hope someone could help me understanding it clear class UserRegistrationForm(UserCreationForm): email=forms.EmailField() class Meta: model=User fields=['username','email','password1','password2'] what are Meta fields and how is Meta class related to database ?? why this Meta class is used here? please help i m getting stuck for long time.. -
Trying to send an array to django database but get an error say Method not allow
I'm new to Django. I'm working on a app were the user type in an the name of the activities and the times.It than display it as a graph. When the user save it, the data will end up being in a json format through serialization. My problem right now is that it only save the last value of the user input and not all the input. Im trying to store an array into Django database. Found multiple answer but none help. I figure to maybe make a httprequest to send the value but any alternative will due. view.py from django.shortcuts import render from django.core import serializers from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_protect from page.templates.forms import ActivitiesForm from page.models import Activities from .serializers import ActivitiesSerializer from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.response import Response @api_view() def page_list(request): if request.method == 'GET': activities = Activities.objects.all() serializer = ActivitiesSerializer(activities, many=True) return Response(serializer.data) elif request.method == 'POST': # data = JSONParser().parse(request) serializer = ActivitiesSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) @csrf_protect def page_detail(request, pk): try: activities = Activities.objects.get(pk=pk) except Activities.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = ActivitiesSerializer(activities) return … -
Is perfoming calculations part of the backend?
Good night, I'm making a system using Django on the back end. I came up with a theoretical question, I am performing some calculations between existing inputs using JavaScript, and the values of those inputs I save in the database with Django. My question is, are these calculations I make between inputs part of the Backend? Or just the moment I use Django to save them? Thanks if you can help me! -
How can I list specific elements of all objects in Django model?
I know how to get post information from my model and display it like so: view: def post_view(request, pk): post = get_object_or_404(Listing, pk=pk) return render(request, 'post_view.html', {'post': post}) html: {% extends 'base.html' %} {% block content %} <div class="post"> {% if user.is_authenticated %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.street_address|linebreaksbr }}</p> <p>{{ post.city|linebreaksbr }}, {{ post.state|linebreaksbr }}</p> <p>{{ post.price|linebreaksbr }}</p> <p>{{ post.description|linebreaksbr }}</p> </div> {% endblock %} Now I need to make a new page called "listings." I've created a url and view already for this. I need my listings page to output post.thumbnail, post.title, and post.price for every object in my database with the is_live boolean set to True. Here is my current code: view: def listings(request): return render(request, 'listings.html') html: {% extends 'base.html' %} {% block title %}Listings{% endblock %} {% block content %} This is the listings page. {% endblock %} model: from django.db import models class Listing(models.Model): thumbnail = models.ImageField() title = models.CharField(max_length=255) description = models.TextField() street_address = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) price = models.FloatField() image1 = models.ImageField() image2 = models.ImageField() image3 = models.ImageField() is_live = models.BooleanField(default=False) class Meta: db_table = "listings" … -
Django - manage.py collectstatic saving to the wrong folder
When I run python manage.py collectstatic it saves to a folder called staticfiles I must have done something to make this happen, but I've searched for staticfiles and found no reference to it except 'django.contrib.staticfiles'. Here is my settings.py: INSTALLED_APPS = [ #some apps 'django.contrib.staticfiles', #some more apps 'tz_detect', ] # some more code STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(VENV_PATH, 'media_root') Expected outcome was for when python manage.py collectstatic is run, that an assets folder would be created, but this never happens. The staticfiles folder in addition to files from static folder also contains a tz_detect folder (from static assets from 3rd party package), an admin folder, and a staticfiles.json -
Django reverse for uid and token for activation email
I'm trying to send a custom email to activate a user's account. However, I cannot figure out how to do it. This method works with a regular URL link, but I can't seem to get the reverse right with the token and uid. from_email = '<info@domain>' #this is the custom template htmly = get_template('activation.html') #this is just the template of the message message = render_to_string('activation_email.html', { 'user':user, 'token': account_activation_token.make_token(user), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), }) d = { 'username': username, 'url': reverse('activate', kwargs={'token':force_text(urlsafe_base64_encode(force_bytes(user.pk))), 'uid':urlsafe_base64_encode(force_bytes(user.pk))}))} subject = 'Email activation' html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, message, from_email, [request.user.email]) msg.attach_alternative(html_content, "text/html") msg.send() The error that I get is: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments If I try to send it as one template, i.e. both the message and my custom html in the message. My html renders as a string. This is the email that I'm trying to send. The activation_email has the message below and activation.html has the custom email html template. activation_email.html {% autoescape off %} Hi {{ user.username }}, Email confirmation: http://domain{% url 'activate' uidb64=uid token=token %} {% endautoescape %} -
How do I add a reverse field value into the django serializer data set Part 2
I previously asked a similar question: How do I add a reverse field value into the django serializer data set But oddly, what worked for the first model doesn't work for the second. Here are my models: class ae(models.Model): opp_own = models.CharField(max_length = 50) class statement_line(models.Model): ae = models.ForeignKey(ae, on_delete=models.PROTECT) pay_date = models.DateField(null=True) approve_date = models.DateField() opp_name = models.CharField(max_length = 50) type = models.CharField(max_length = 10) document_number = models.CharField(null=True,max_length = 50,) ct_id = models.CharField(max_length = 50,validators=[ RegexValidator(regex='^CT', message='this didn\'t come from salesforce' )]) amt = models.FloatField() cur = models.CharField(default='USD',max_length = 3) class draws(models.Model): ae = models.ForeignKey(ae, on_delete=models.PROTECT) draw_type = models.CharField(choices=[('incentive pay','incentive pay'),('recoverable draw','recoverable draw')], max_length = 50) amt = models.FloatField() usd_amt = models.FloatField() cur = models.CharField(choices=[('USD','USD'),('EUR','EUR'),('AUD','AUD'),('IND','IND'),('GBP','GBP')],default='USD', max_length = 3) owe_date = models.DateField() sl = models.ForeignKey(statement_line, on_delete=models.PROTECT, null = True) This works fine: class drawsSerializer2(serializers.ModelSerializer): opp_own = serializers.SerializerMethodField() class Meta: model = draws fields = ['id','ae_id', 'ae','owe_date','draw_type','usd_amt','amt', 'opp_own'] extra_kwargs = { 'ae': {'write_only': True} } def get_opp_own(self, obj): return obj.ae.opp_own goods = draws.objects.filter(sl_id__isnull=True).order_by('-owe_date') serializer = drawsSerializer2(goods,many=True) serializer.data But inexplicably, this doesn't: class statement_lineSerializer2(serializers.ModelSerializer): opp_own = serializers.SerializerMethodField() class Meta: model = statement_line fields = ['id','ae_id','ae','pay_date','opp_name','type','document_number','ct_id','amt','cur','opp_own'] extra_kwargs = { 'ae': {'write_only': True} } def get_opp_own(self, obj): return obj.ae.opp_own goods2 = statement_line.objects.filter(pay_date__isnull=True).order_by('-approve_date') sl = … -
Why is my dlete button not deleting my database object? Django
I cobbled together a delete button and edited my view, it isn't working. Can someone help me fix it? I've moved some code around and tried some things but I can't get it to work. I need someone to show me what I'm doing wrong. My view: def post_edit(request, pk): post = get_object_or_404(Listing, pk=pk) if request.method == "POST": form = ListingForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('post_view', pk=post.pk) else: form = ListingForm(instance=post) if request.POST.get('delete'): post.delete() return redirect('listings') return render(request, 'post_edit.html', {'form': form}) My html: {% extends 'base.html' %} {% block title %}Post Edit{% endblock %} {% block content %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">logout</a></p> <h1>Edit listing:</h1> <p>The listing will only be viewable to users if "Is Live" is checked.</p> <form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> <p>Click the button below to delete this listing. No second warning is given, once you click delete it will be removed.</p> <button type="delete" class="delete btn btn-default">delete</button> </form> {% endblock %}