Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS grid in landing django project
Right now I'm on the final stage of my landing project. Trying to understand css grid, but a little bit confused with the my previous code. Here is my image: IMAGE source I would like to center horizontaly and verticaly icons and text with the title in the white background box. Will be very thankful for the help <!DOCTYPE html> {% load static %} <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home page</title> <link rel="stylesheet" href="{% static 'style.css' %}"> <script src="https://kit.fontawesome.com/5476287230.js" crossorigin="anonymous"></script> </head> <body> <div class="social-menu"> <ul> <li><a href="https://www.instagram.com/kseniia_ifbb_latvia"><i class="fab fa-instagram"></i></a></li> <li><a href="https://www.tiktok.com/@kseniiasherr"><i class="fab fa-tiktok"></i></a></li> <li><a href="https://www.facebook.com/profile.php?id=100009190064504"><i class="fab fa-facebook"></i></a></li> </ul> </div> <div class="title"> <h1>ЧТО ВЫ ПОЛУЧАЕТЕ?</h1> </div> <div id="background"></div> <div class="icons"> <li><i class="fas fa-utensils"></i></li> <li><i class="fas fa-dumbbell"></i></li> <li><i class="fas fa-clock"></i></li> <li><i class="fas fa-heartbeat"></i></li> </div> <div class="icons-text"> <li> <h1>План питания с учетом Ваших вкусовых потребностей</h1> </li> <li> <h1>Тренировки для любого уровня подготовки</h1> </li> <li> <h1>Максимально быстрые результаты</h1> </li> <li> <h1>Тело, о котором Вы могли только мечтать</h1> </li> </div> </body> </html> and: body { background: url(https://images.unsplash.com/photo-1534258936925-c58bed479fcb?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=889&q=80) no-repeat center center fixed; background-size: cover; margin: 0; } #background { position: fixed; top: 35%; width: 100%; height: 20%; background-color: white; z-index: -1; opacity: 0.8; } .social-menu ul { position: absolute; top: 25%; left: … -
How to combine two columns in one in Django?
How to combine two columns in one in Django? What is equivalent to "select col1 | col 2 as bothcols from tbl ..." ? -
python django how save a input field under a associate user
I am trying to save a todo text under a associat user How to do that i attach my models.py file, forms.py file and views.py file. Please Help meenter image description here -
how top pass data to javascript in django
I am looking for a way to pass data to the index.js script from django view. Sample simple view: def map_display(request): data = [ {'lat': 52.20415533, 'lng': 21.01427746}, {'lat': 52.20418, 'lng': 21.014386}, ] data = json.dumps(data) return render(request, 'index.html', {"data": data} ) How to pas list data to flightPlanCoordinates variable? index.js function initMap() { const map = new google.maps.Map(document.getElementById("map"), { zoom: 3, center: { lat: 0, lng: -180 }, mapTypeId: "terrain", }); const flightPlanCoordinates = {{ data}}; # <--- pass here const flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2, }); flightPath.setMap(map); } index.html <html> <head> <title>Simple Polylines</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <link href= "{% static 'css/style.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'js/index.js' %}" ></script> </head> <body> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=........=initMap&libraries=&v=weekly" async ></script> </body> </html> -
Why do I get "CommandError: App 'app_name' does not have migrations." when using Heroku?
So I have deployed my Django project to Heroku, and now trying to migrate the database. I have everything working fine in my local sever. Then I tried to run the commands in heroku, as below. heroku run python manage.py makemigrations app_name'. This worked fine. Migrations for 'app_name': contents\migrations\0001_initial.py - Create model Book - Create model Category - Create model Content Then of course, I tried : heroku run python manage.py migrate app_name. But then I got this error CommandError: App 'app_name' does not have migrations. I've done some research for possible issues, none of which were relevant to mine. For example I do have __init__.py in the migrations folder inside app_name directory. Also, I've tried heroku run python manage.py migrate as well as heroku run python manage.py migrate app_name. I'm very confused. What do you think is the problem? Thanks in advance. :) -
Django Crispy Form & <select> tag
Is it possible to use crispy-form for < select > tags? "|as_crispy_field" doesn't help here <select id="food" name="food"> <option value="" selected="selected">---------</option> {% for object in form.fields.food.choices %} <option value="{{ object.0 }}" class="{{ object.1 }}">{{ object.2 }}</option> {% endfor %} </select> -
AttributeError: Got AttributeError when attempting to get a value for field
**job model** class JobPost(models.Model): creater = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=255) job_type = models.ForeignKey( JobType, on_delete=models.CASCADE) job_loc = models.ForeignKey(JobLocation, on_delete=models.CASCADE) cmpny_name = models.ForeignKey( Company, related_name='company', on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) job_description = models.CharField(max_length=255) salary = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.job_type) company serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' post serializer class PostSerializer(serializers.ModelSerializer): # job_loc = JoblocationSerializer(many=True) companies = CompanySerializer(source='company', many=True) class Meta: model = JobPost fields = '__all__' error i am getting AttributeError: Got AttributeError when attempting to get a value for field companies on serializer PostSerializer. The serializer field might be named incorrectly and not match any attribute or key on the JobPost instance. Original exception text was: 'JobPost' object has no attribute 'company'. -
Change field type from a parent model with _meta.get_field()
I have the following model which inherits from user and has a signal to be created. However, I want to change the email field on the User model from email to string. Here is my model: class Seeker(User): birthdate = models.DateField(null=True, blank=True) phone_number = models.CharField(blank=True, max_length=30) open_for_job = models.BooleanField(default=False) latitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) longitude = models.DecimalField( max_digits=9, decimal_places=6, null=True, blank=True ) class Meta: db_table = "seeker_table" def __str__(self): """ :return: Firebase UID related to Seeker """ return self.username def create_seeker(sender, instance, created, **kwargs): """ :param instance: Current context User instance :param created: Boolean value for User creation :param kwargs: Any :return: New Seeker instance """ if created: Seeker.objects.create( user_ptr_id=instance.id, username=instance.username, password=instance.password, email=instance.email, first_name=instance.first_name, last_name=instance.last_name, is_active=instance.is_active, is_superuser=instance.is_superuser, is_staff=instance.is_staff, date_joined=instance.date_joined, ) signals.post_save.connect( create_seeker, sender=User, weak=False, dispatch_uid="create_seekers" ) Is it possible? And how can I do that? -
Django Restframework - Multiple models for SearchFilter
Using Django 3.2 with Restframework. Iam trying for search filter and create a API with restframework which would output the searched term with its whole object. I had a little success on that with official doc. But from that I can only search in a single Model and not as globally. Is there any existing document, blog on how to use multiple Models together? Or any working example. Or this the existing code for the single, how to extend it to all models? views.py class SearchView(generics.ListAPIView): queryset = MasterUser.objects.all() serializer_class = MasterUserSerializer filter_backends = [SearchFilter] search_fields = ['firstname', 'email', 'lastname'] serializer.py class MasterUserSerializer(serializers.ModelSerializer): class Meta: model = MasterUser fields = "__all__" -
Django & elixir combination
I am actually studying microservices architecture and I am thinking to use Django & elixir for two different backend services : Django for authentification and business logic. Elixir for real-time comunications My biggest concern is how to implement authentification & authorization in this context ?? -
How can I link the author of a post to his profile page with django?
[error in cmd][1] [its showing like this][2]gur.com/cD6dO.png urls.py pageviews.py page -
How can I make Django template correctly in Bootstrap5 nav-tabs?
Hi I'm new to stackoverflow. I want some help to make Django templates correctly appear in Bootstrap5 nav-tab. I embedded Django HTML template in Bootstrap5 nav-tab as following, but it doesn't apper up when I render the page. I want each tab to contain dynamically generated HTMLs by Django and to correctly show them. Does anyone have an idea to make this work? Any helps would be apprciated. Thanks! <div class="container"> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Abstract</a> <a class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Questions</a> <a class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" href="#nav-contact" role="tab" aria-controls="nav-contact" aria-selected="false">FAQ</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> ... </div> <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab"> <div class="mb-3"> {% for item in question_list %} {{ item.question_id }} {% endfor %} </div> </div> <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">...</div> </div> </div> -
display already created Mysql database table with Django
I am very beginner in Django. I have just questions. I search and watched a lot of videos about Django and there tutors were creating classes for database then run it and boom, in the database and in the table there were columns. What if I already have a table and I just want to display . Is this possible ? So my goal is to display my table from database with pagination and then possibility to make querying. if there is any example of it can you show me ? Maybe something like github project or anything that helps me . Thank you in advance. Have a good day. -
How to make time slots for appointment, that admin can update every day or few days forward. Django
Im working on barber app. Admin is a barber who write time slots for every day or few days forward. Time slots can be string or integer, but i need to have exactly date that client can appointment. -
Django signals not triggered when a model object is created
I am using Django signals to trigger a task (sending mass emails to subscribers using django celery package)when an admin post a blogpost is created from Django admin. But the signal is not triggered. I have a print statement inside the signal which is not printing ie the signal is not recived after a new blog is created. My apps are set like this. My blog model: class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) .................../ My tasks file from django.core.mail import send_mail from travel_crm.settings import EMAIL_HOST_USER @shared_task def send_mails(self,*args, **kwargs): subscribers = self.kwargs['subscribers'] blog = self.kwargs['blog'] for abc in subscribers: emailad = abc.email send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ", EMAIL_HOST_USER, [emailad], fail_silently=False) My signals.py file from .tasks import send_mails from apps.blogs.models import BlogPost,Subscribers from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=BlogPost) def email_task(sender, instance, created, **kwargs): print(123456789) if created: print(123456789) subscribers = Subscribers.objects.all() blog = BlogPost.objects.latest('date_created') print(blog) # task = send_mails(subscribers, blog) # task.delay() send_mails.delay(subscribers,blog) My init file from __future__ import absolute_import, unicode_literals from apps.blogs.celery_files.celery import app as celery_app __all__ = ('celery_app',) -
error in my view function in Django 'decimal.Decimal' object is not iterable
Please give some help or some hint why i am getting this error in my view function def EmployeeRateView(request): msg = '' try: fromDate = request.POST.get('fromdate') except: msg = "Pleas enter valid date" if request.method == 'POST': RateData = EmployeeRate.objects.filter(Site=request.user.SuperVisor.Site,DateFrom=fromDate) return render(request,"employeerate.html",{"EmployeeRate":RateData,"msg":msg}) else: print("get") rate = Rate.objects.filter(Site=request.user.SuperVisor.Site) EmpDetails = EmployeeRegistration.objects.filter(Site=request.user.SuperVisor.Site,Status="Working") for employee in EmpDetails: for get in rate: print("date",get.fromDate) if(employee.Site==get.Site and employee.Category==get.Category and employee.Department==get.Department): try: check = EmployeeRate.objects.get(EmpId=employee.EmpId,DateFrom=get.fromDate) print("found",check.EmpId,check.Name,get.fromDate) except: print("not found",check.EmpId,check.Name,get.fromDate) rate = get.Basic+get.Da print(rate) print("basic",get.Basic,"da",get.Da,"rate",rate) EmployeeRate.objects.create(EmpId=employee.EmpId, Name=employee.Name, Site=employee.Site, Basic=get.Basic, Da=get.Da,Rate=rate, Hra=get.Hra, Ca=get.Ca, SplAllow=get.SplAllow, CanteenAllow=get.CanteenAllow, DateFrom=get.fromDate) context = {'EmployeeRate':EmployeeRate.objects.filter(Site=request.user.SuperVisor.Site).order_by('Name'),'msg':msg} return render(request,"employeerate.html",context) Here is my error in my terminal as well as in my browser Basically i am trying to save or create some data in EmployeRate model based on filter and condition. But at the end it giving me this type of error. I can't able to understand why it is showing like this. -
Django file uploader throwing error "cannot pickle '_io.BufferedRandom' object" while uploading more thank 2.5mb of image using celery
i am trying to upload image files in Django, i am sending the upload task into the task queue using celery, but when I upload image files larger than 2.5mb it crashes with this error cannot pickle '_io.BufferedRandom' object i have added some settings options to Django but that does not work. celery application settings FILE_UPLOAD_MAX_MEMORY_SIZE = 90005000 CELERY_BROKER_URL = os.environ.get('REDIS_TLS') CELERY_ACCEPT_CONTENT = ['pickle', 'application/json'] CELERY_TASK_SERIALIZER = 'pickle' CELERY_RESULT_BACKEND = 'django-db' is there any way I can solve this issue, a reminder when am uploading the image files using Django alone, it works regardless the size, so the issue is from celery not been able to work with file larger than 2.5MB -
I keep getting this error when I'm trying to open the 'update_item' page
Django Version: 3.2.5 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] error Traceback (most recent call last): File "C:\Users\BOLARINWA\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\BOLARINWA\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\BOLARINWA\websites\ecommerce\store\views.py", line 36, in updateItem data = json.loads('request.body') File "C:\Users\BOLARINWA\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads return _default_decoder.decode(s) File "C:\Users\BOLARINWA\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\BOLARINWA\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /update_item/ Exception Value: Expecting value: line 1 column 1 (char 0) -
DRF : XML output from a serializer
I'm currently working with an external API that requires the data to be POSTed in an XML format. Is there a way to extract XML from a Serializer using .data ? All of our APIs use JSON so I won't be updating our output renderer which is the suggestion from most other questions. Do I have hand write the parser or can I leverage DRF to do it ? -
How do I add ffmpeg on Heroku for my Django Application?
I'm trying to separate the audio from a video file (.mp4). Moviepy was not working on my local server, So I decided to use ffmpeg. However, when I deploy my app to Heroku, I'm not sure what buildpacks I would need. Thanks! -
How to retrieve session data before reset in password change view?
I have override Django PasswordChangeView using Ajax (JQuery Form pluggin) and it works except all session variables are reset. Reading Django documentation, I understand it is the "normal behavior" but I need to reinitialize some session data ; if not, it would have no real interest changing password using Ajax... At start, I thought that call update_session_auth_hash function was responsible for that behavior but it seems not to be true as in form_valid function, request.user is set but request.session data are reset, even before fom is saved... So my question is WHEN/WHERE I can retrieve session variable to be re-set when PasswordChangeView is called? class PasswordChangeView(auth_views.PasswordChangeView): def form_valid(self, form): print('request.user',self.request.user) # return connected user print('request.session.get("selected_database")',self.request.session.get("selected_database")) # return None self.object = form.save() update_session_auth_hash(self.request, self.object) # prevent user’s auth session to be invalidated and user have to log in again print('request.session.get("selected_database")',self.request.session.get("selected_database")) # return None return JsonResponse ({'data': form.is_valid()},status = 200) -
I am using drf, The main problem is that my view returns a empty json
My main is that my view returns a empty json. I want my blogs with respective foreign_key user_id. My models.py file from django.db import models # from django.contrib.auth.models import User from django.utils import timezone from datetime import datetime from .validators import validate_allfile_extension from restfapp.models import CustomUser CHOICE_GENDER = (('Male', 1), ('Female', 2), ('other', 3)) class Blog(models.Model): title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.DateTimeField(default=datetime.now) image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.title My views.py file @api_view(['GET', 'POST']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def blog(request): if request.method == 'GET': blogs_by_user_id = Blog.objects.filter(user_id=request.user.id).all() serializer = AddBlogSerializer(blogs_by_user_id, many=True) json_data = JSONRenderer().render(serializer.data) return Response(json_data, status=200) My Response: "[{},{},{},{},{}]" It gives me empty json i want my blogs with respective foreign_key user_id. Can anyone solve my issue. It gives me empty json i want my blogs with respective foreign_key user_id. Can anyone solve my issue. It gives me empty json i want my blogs with respective foreign_key user_id. Can anyone solve my issue. It gives me empty json i want my blogs with respective foreign_key user_id. Can anyone solve my issue. It gives me empty json i want my … -
where to run heroku ps:scale web=1?
where to run the command heroku ps:scale web=1 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" on this error., -
AWS Elastic Beanstalk Django project 502 nginx/1.20.0
i've followed all the steps in the following document: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html When i do eb status command, i see the following info: Environment details for: django-env Application name: django-tutorial Region: us-west-2 Deployed Version: app-09b8-210715_122829 Environment ID: e-dq7pvpab6p Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.2 Tier: WebServer-Standard-1.0 CNAME: django-env.eba-tqcfewzi.us-west-2.elasticbeanstalk.com Updated: 2021-07-15 09:29:05.341000+00:00 Status: Ready Health: Red And when i try to browse the url (CNAME) Im getting 502 nginx/1.20.0: Am i missing any configurations? I new to AWS. Thanks in advance! -
Django Login Message with LoginView
I am a bit confused on why my LoginView message is not pulling the users login name. I have tried a few different ways and it either will say 'Welcome Anonymous User' or 'Welcome' (not adding anything). I have tried a few different methods and the results are the same each way I try to solve it. My code is as follows: class MyLoginView(LoginView): template_name = 'registration/login.html' success_message = 'Welcome' def form_valid(self, form): """Add message here""" messages.add_message(self.request, messages.INFO, f"{self.success_message} {self.request.user}") return super().form_valid(form) This one will say 'Welcome AnonymousUser', if I change the code to {self.request.user.username} it just will say 'Welcome' also have tried class MyLoginView(LoginView): template_name = 'registration/login.html' def form_valid(self, form): messages.success(self.request, f'Welcome {self.request.user}') return super().form_valid(form) This one will flash the message of 'Welcome Anonymous User'. If I change the code to f'Welcome {self.request.user.username}' then the message displayed is just 'Welcome' I am not really sure why these aren't working so any help would be greatly appreciated