Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to set maximum quantity but getting error
I am trying to add maximum quantity.Here is my code : def post(self, request): product = request.POST.get('product') cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: cart[product] = quantity - 1 else: cart[product] = quantity + 1 else: cart[product] = 1 if cart[product] < 1: cart.pop(product) else: cart = {} cart[product] = 1 request.session['cart'] = cart return redirect("cart/") here when I try if quantity <= 2 i get this error <= not supported. So I think there will be better way to set maximum quantity. Can someone please help? -
could not enter into if condition: if request.method == 'POST':
I have used Django 2.2 to build a website, however the if condition: "if request.method == 'POST': " could not be hit in the if condition. view.py: def check_discilpine(request): if request.method == 'POST': discipline_name=request.POST.get('discipline_name') dropdown_semester=request.POST.get('dropdown_semester') dropdown_year = request.POST.get('dropdown_year') print("-----------------------------------------------") print(discipline_name, dropdown_semester, dropdown_year) return render(request,'specific-semester.html', context={'discipline_name': discipline_name, 'dropdown_semester': dropdown_semester, 'dropdown_year': dropdown_year}) html: <form method="post" action="{% url 'bms:content_checklist_for_discipine_info' %}"> {% csrf_token %} <div class="row"> <div class="px-3"> <div class="d-sm-flex align-items-xl-stretch justify-content-between mb-4"> <h1 class="h4 mb-0 text-gray-800">&nbsp;&nbsp;Creating Content Checklist for:</h1> <select id="dropdown_semester_0" name="dropdown_semester_0" > <option value="">--Dropdown January or July--</option> <option value="Dropdown_Jan">January</option> <option value="Dropdown_Jul">July</option> </select> <select id="dropdown_year_0" name="dropdown_year_0" > <option value="">--Calender year since 2020--</option> <option value="Dropdown_2021">2021</option> <option value="Dropdown_2022">2022</option> <option value="Dropdown_2023">2023</option> <option value="Dropdown_2024">2024</option> <option value="Dropdown_2025">2025</option> <option value="Dropdown_2026">2026</option> <option value="Dropdown_2027">2027</option> <option value="Dropdown_2028">2028</option> </select> </div> </div> </div> <div class="row"> <div class="px-3"> <div class="d-sm-flex align-items-xl-stretch justify-content-between mb-4"> <h1 class="h4 mb-0 text-gray-800">&nbsp;&nbsp;Content Checklist(s) for Discipline:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1> </div> </div> <select name="discipline"> {% for discipline in query_results %} <option value="{{ discipline.name }}" name="discipline_name">{{ discipline.name }}</option> {% endfor %} </select> </div> <br> <br> <div class="col"> <label class="radio-inline"> <input type="radio" name="optradio" value="notspecific" checked>&nbsp;Latest Available Semester </label> <label class="radio-inline"> <input type="radio" name="optradio" value="specific">&nbsp;Specific Semester </label> <select id="dropdown_semester" name="dropdown_semester" > <option value="">--Dropdown January or July--</option> <option value="Dropdown_Jan">January</option> <option value="Dropdown_Jul">July</option> </select> <select id="dropdown_year" name="dropdown_year" > <option value="">--Calender year … -
Heroku Slug Size Too Large due to Keras [closed]
I'm deploying my app to heroku however their free tier only allow < 500MB packages, I'm currently using tensorflow and it takes > 500 MB, I can downgrade it to lower version or use the tensorflow-cpu instead, however, I'm also using Keras, which requires at least tensorflow=2.2.0 (so size > 500MB). I want to be able to use Keras while the size of my packages < 500MB. I have looked into these two questions but somehow downgrading Keras causes a lot of imcompatible issues. Deploy python app to Heroku "Slug Size too large" Error "Keras requires TensorFlow 2.2 or higher" -
nested annotations django with OuterRef
I want to annotate a field based on another queryset. return real_instances.annotate( submitted_count=user_enrolments.filter(course_progresses__module_progresses__module__id=OuterRef('id')).annotate( submitted_attempt=Exists( AssignmentModuleProgress.objects .filter( Q(module_progress__module__id=OuterRef(OuterRef('id'))) Q(module_progress__user=OuterRef('user')) & Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__id=OuterRef("id")), is_submitted=True) )).filter(submitted_attempt=True).count(), Here i have a QuerySet by the name real_instances and i want to annotate a field submitted_count in it . user_enrolments is another queryset and im annotating another field in it by the name submitted_attemmpt to finally get my count . Here im having issue with OuterRef(OuterRef('pk')) which refers to the id of the real_instances object in iteration. Im getting the error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
How to pass Django filtered object to views( xls download)?
I am trying to pass the filter object to my view function which is responsible to download data into .xls format(Earlier I am directly using the Model name so I am getting all the records.). My requirement is when the user will apply any filter then that object data should be pass to download views. Please find the below code. filter.py class Shift ChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = AAChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name','Shift_timing'] function in views.py to download DB records: ###########for Downloading ############### from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgen_data(request): model=ShiftChange allgen = ShiftChange.objects.all() gene_filter = ShiftChangeFilter(request.GET,queryset=allgen ) allgene = gene_filter.qs print('download:',allgene) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Gene_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id', 'AConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = allgene.values_list('id', 'AConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time') for row in rows: row_num += 1 for col_num in … -
how to take the hostname or base url
how to get a running base url? in admin.py, new function/method def your_api(self, object_id): """ Function save your api """ # print(reverse('admin:index')) parameters = Parameter.objects.filter(agregator=object_id) concate_endpoint_api = '' for parameter in parameters: if parameter.flag == 'NO': concate_endpoint_api += '{}{}={}'.format(BASE_URL, parameter.keys, parameter.values if parameter.values else 'None') concate_endpoint_api += '&' return concate_endpoint_api example javascript windows.location.origin http://example.com or http://localhost or http://127.0.0.1:8000 -
How to have a form in a DetailView page in django?
I'm building a really simple twitter clone with django. I have a TweetDetailView like this: class TweetDetailView(LoginRequiredMixin,DetailView): model = Tweet context_object_name = 'tweet' template_name = "twitter/tweet.html" What I want is a form for commenting on a tweet that appears on the TweetDetailView page. Can a django DetailView handle forms? Or should I use a function based view for this detail page? Any help is appreciated. -
Django, How to paginate a JsonResponse?
I'm working on a Django and JavaScript project. I'm aware that without JavaScript APIs the pagination would be much easier, but now I'm too far down the rabit hole :) My views.py from django.http import JsonResponse def post_list(request): posts_list = Post.objects.all() posts = [p.serialize() for p in posts_list] return JsonResponse(posts, safe=False) My JavaScript fetch('/post_list') .then(response => response.json()) .then(posts => { print_post(posts); }); Then the print_post function does its magic and finishes by appending all posts to a div. My HTML <div id="to_attach_post_1"></div> So, all posts print nicely in one page. However, if I have hundreds of posts that would not look nice, right? so I have to paginate the posts, lets say every 10 posts, while still sending a JsonResponse with the posts. Does anyone know how to paginate this? -
Django Not Found: /virtual/Scripts/dashApp/static/main.css
I have looked through SO and this seems to be a common issue among new django users however none of what I have attempted has fixed my issue. after running dev server http://127.0.0.1:8000/ I get not found error in CMD window Not Found: /virtual/Scripts/dashApp/static/main.css Not Found: /virtual/Scripts/dashApp/static/main.js the relevant html in my app as below <link href= virtual/Scripts/dashApp/static/main.css rel="stylesheet"></head> <script type="text/javascript" src= virtual/Scripts/dashApp/static/main.js ></script> both the .css and .js file live in C:\Users\James\Desktop\Scripts\django\dealerDash\virtual\Scripts\dashApp\static my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR , 'static') I have tried wrapping virtual/Scripts/dashApp/static/main.css as "virtual/Scripts/dashApp/static/main.css " and /virtual/Scripts/dashApp/static/main.css but without joy.. -
Get the top n rows of each day from same table in Django
I am sure this is not a novel/new problem. I really tried to look into other solutions. However, I could not find how to solve this. I have a model like class Deal(models.Model): title = models.CharField(max_length=1500) viewCounter = models.SmallIntegerField(default=0) thumbsUpCounter = models.SmallIntegerField(default=0) createDateTime = models.DateTimeField(auto_now_add=True) Now I want to get top 10 (or less) deals ordering by thumbsUpCounter and viewCounter of every day. I tried to look into the Subquery and Outerref. However, I could not figure out how can I get the right results. ** I am using MySQL. Thanks in advance. -
Django url pattern to pass a date parameter [duplicate]
I'm passing date parameters "check_in" and check_out" from one view to another through URL. Right now, my url pattern defines them as string (ie, str:check_in), so I get something like this. http://127.0.0.1:8000/checkout/2020-12-16/2020-12-25 It works but it's not ideal; what if someone edited the url with other strings that are not dates? Is there a way for the url to throw an error if the pattern for a date is not respected or recognized? urls.py path('checkout/<str:check_in>/<str:check_out>', views.check_out, name='check_out') views.py def check_out(request, check_in, check_out): ... -
How can I let users add their email server account to a Django app?
I am making a CRM app using a Django framework and I want to make a functionality that allows users to add their email server account (IMAP/STMP) so that they can send emails to their customers, receive replies and get notifications of the replies from the app. The similar app is HubSpot which has a feature of connecting personal email. Any help would be much appreciated. -
Django bulk_create check for duplicate entry of multiple fields
I'm trying to use bulk_create for large dataset insert since i can't use get_or_create() because of N^N problem: users = User.objects.all() for user in users: seat_type = SeatType.objects.all()[random_entry] AnotherTable.objects.bulk_create( AnotherTable(user=user, seat_type=seat_type) , None, ignore_conflicts=True) The thing is i want to check for duplicate entry unique with 2 columns(user, seat_type) values For example: user |seat_type | ... ---------- | --------- | ... 1 |1 | ... 2 |2 | ... 3 |4 | ... 4 |1 | ... 1 |1 | ... 3 |4 | ... (1, 1) and (3, 4) is invalid when inserting But ignore_conflict only trigger on 1 unique column(which is not what i want which is unique value of 2 columns), i'm looking for something like defaults of get_or_create, My DataBase is MySQL -
Loaded django models dyanmically from the database
I know there is a way to generate the models classes from the database using the inspectdb command. But it need the models.py to store the generated models. How can I directly load the models to the memory and use it? -
Nginx cannot find my Django WSGI application bad gateway
I have been a while stuck trying to configure my Django rest framework WSGI API, but at the moment of configuring the SSL certificate on the nginx conf file everything stopped working, no matter what, I always receive a 502 Bad gateway right away when trying to connect to the API. I have to clarify, that if I set the config back to HTTP (No SSL), everything works just fine. I'm using gunicorn to run the WSGI Django App, and I'm running everything in docker containers, so far, I think docker configuration is OK, as everything works just fine when I config the nginx webserver for HTTP. the following is my current NGINX configuration file for HTTPS: user nginx; worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100M; upstream mysite_drf { server backend:8000; } server { listen 80; access_log /var/log/nginx/api_access.log; error_log /var/log/nginx/api_error.log; server_name mysite.com; location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; access_log /var/log/nginx/api_ssl_access.log; error_log /var/log/nginx/api_ssl_error.log; server_name mysite.com; location / { proxy_pass http://mysite_drf; proxy_ssl_session_reuse on; proxy_set_header Host $host; proxy_redirect off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 100M; } location /static/ { alias /mysite_drf/static/; } } … -
Why does my Django app in Azure not respond to pings?
I am trying to publish my web app to Azure, but it fails when I try to connect. The app service plan I am deploying to is B1 (basic tier) with a Linux OS. I only have one app on the plan. Azure launches my app inside of a docker container. I'm using one of the prebuilt docker container images that Azure allowed me to select when I created the app. It comes with Python installed. I configured it to run my startup.sh file. I publish the app with these two commands: az login az webapp up --resource-group myresourcegroup --location mylocation --plan ASP-myresourcegroup-blah --sku B1 --name mywebsite These commands succeed, but my app fails when I connect. My startup.sh file has two commands inside: pip install -r requirements.txt python manage.py runserver The logs show the startup commands run and complete successfully, and that the website started successfully and is listening on port 8000, but then when Azure tries to ping my web app on that very same port, it says that it didn't get a response. Here are the logs (notice they are out of timestamp order... this is how they appeared in the log stream): 2020-12-16T02:20:04.585Z INFO - Waiting … -
Django tasks done associated with a project
I want to obtain the percentage of tasks performed associated with a project my model class Srv(models.Model): srv_year = models.CharField(max_length=4) slug = AutoSlugField(populate_from = 'srv_year', always_update = True) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null = True, blank = True) project_title = models.CharField(max_length=200, unique = True) slug = AutoSlugField(populate_from = 'project_title', always_update = True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null = True, blank = True) todo_title = models.CharField(max_length=200) slug = AutoSlugField(populate_from = 'todo_title', always_update = True, null = True) My view class index(ListView): model = Srv template_name = 'srv_list.html' ordering = ['srv_year'] def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['get_percentage_done'] = Todo.objects.filter(state = True).count() * 100 / Todo.objects.all().count() return context But with this context['get_percentage_done'] = Todo.objects.filter(state = True).count() * 100 / Todo.objects.all().count() I get all the system tasks -
django.db.models has no attribute "PublishedManager"
I'm following along in a book and came across an error I can't seem to solve on my own. Im trying to add a model manager so I can search only published blog posts. In my blog app, I first added the custom manager class as shown below: class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') I then added the following lines to my Post model. class Post(models.Model): objects = models.Manager() #default manager published = PublishedManager() #new manager The error I am getting is: AttributeError: module 'django.db.models' has no attribute 'PublishedManager' Any help greatly appreciated, I have struggling trying to figure out what is wrong for quite a while now! -
Is it possible to use the same Django models/views/etc with two different databases?
I have a Django application and I want to host it using 2 databases - one for test data and the other with real data, with the database path defined by the url accessing the site - ie test.mysite.com versus mysite.com. I looked through the Django docs at using multiple databases and routers, but those examples and others use the databases to split up the apps. For example, all data from the Customer model goes in the customer db, and all data from the User model goes in the user db as defined in settings.py. Is there a way to use one django app and configure two databases, with the db selection based on the url? Perhaps the best solution is to set up 2 virtual environments, one for mysite.com, and the other for test.mysite.com, and let apache's virtual hosts be the "router". As the app(s) evolve, I can clone the sites from the master git repo. Thanks for your thoughts! Mark -
Django Query across multiple model relationships
I'm trying to make a query for a set of instances in the ActivityPartsModel filtered by a group. When I try to run the following. I am left with an Attribute Error: "'QuerySet' object has no attribute 'activity'" activities = GroupActivityModel.objects.filter(group=id) parts = ActivityPartModel.objects.filter(activity=activities.activity.all()) print(parts) How would I go about filtering ActivityPartModel with a GroupModel ID/instance class ActivityModel(models.Model): activityName = models.CharField(max_length=100) description = models.CharField(max_length=200) workCenter = models.ForeignKey(Group, on_delete=models.PROTECT) history = HistoricalRecords() class ActivityPartModel(models.Model): activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT) part = models.ForeignKey(PartModel, on_delete=models.PROTECT) quantity = models.IntegerField(default=1) increment = models.BooleanField(default=False) # TRUE/FALSE used to represent parts ActivityPartModel/produced order = models.IntegerField(blank=False, default=100_000) location = models.TextField(max_length=50, null=True) history = HistoricalRecords() class GroupModel(models.Model): groupName = models.CharField(max_length=50) class GroupActivityModel(models.Model): group = models.ForeignKey(GroupModel, on_delete=models.PROTECT) activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT) order = models.IntegerField(blank=False, default=100_000) groupName = models.CharField(max_length=50) -
Django: checking is_null in values() queryset
I have this queryset: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', number_of_children=Count('children') ) It does the job. But I'm really only using it to check if an object has children (I don't really care about how many it has). Is there a way to use isnull here? I've tried: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', 'children__isnull' ) and: output = self.filter(parent=task, user=user).values( 'label', 'minutes_allotted', 'days_to_complete', 'pk', is_not_parent='children_isnull' ) but neither were correct. -
JSON API - Passing an iterable object from Python file to Java Script File (Django)
Project3 CS50's Web Programming with Python and JavaScript Harvard EDX It was supposed to give me back a nested loop, however, it doesn't happen. It was also supposed to show a stack of divs in the html file. Each one containing sender, subjet and button 'archive' for each element in the loop. One email per div. What happened ??? -
How to restart Dramatiq in Windows on code update or server restart?
I am using Django-Dramatiq with Dramatiq and RabbitMQ. I have it all working, but I am not sure the proper way to deploy to a Windows Server. If the server restarts, how do I make sure that the workers start again? If I deploy new code changes, what is the best way to stop and start the workers again to get the changes? -
adding a new field age in admin page
i have a family_member model in django that has a set of attributes, i want to calculate age based on date_of_birth, so basically i want to add a column next to date_of_birth with age, and what i've done models.py class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=models.PROTECT) dependant_child_age_range = models.ForeignKey(DependantChildAgeRange, null=True, blank=True, on_delete=models.PROTECT) care_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) income = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True, help_text='''Excluding: 1. Maintenance 2. FTB-A & FTB-B 3. CRA but incl. ES(1) for all payments and FTB-A & FTB-B''') rent_percentage = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MaxValueValidator(100), ]) @property def age(self): from math import floor return floor( (datetime.today().date() - self.date_of_birth).days / 365.25) admin.py class FamilyMemberInline(admin.TabularInline): def formfield_for_foreignkey(self, db_field, request, **kwargs): action = request.META['PATH_INFO'].strip('/').split('/')[-1] if action == 'change': transaction_id = request.META['PATH_INFO'].strip('/').split('/')[-2] if db_field.name == "family_group": kwargs["queryset"] = FamilyGroup.objects.filter(transaction=transaction_id) return super(FamilyMemberInline, self).formfield_for_foreignkey(db_field, request, **kwargs) model = FamilyMember extra = 0 def sufficient_info_provided (self, obj): return obj.sufficient_information_provided sufficient_info_provided.boolean = True def get_age(self, obj): return obj.age readonly_fields = ['sufficient_info_provided','get_age', ] but now i get this error :`unsupported operand type(s) for -: 'datetime.date' and 'NoneType' i've tried to include If statment in … -
How do I fix bad credential error in django
I have created a contact form that is suppose to send that message via email as well as maintain those messages in database. I have added the following in settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') And the following code in views.py from django.core.mail import send_mail from django.conf import settings def contact(request): if request.method == 'POST': name = request.POST.get("name") email = request.POST.get("email") desc = request.POST.get("desc") instance = Contact(name=name, email=email, desc=desc) instance.save() desc = request.POST['desc'] send_mail('Contact Form', desc, settings.EMAIL_HOST_USER, ['********@gmail.com'], fail_silently=False) Its not giving any errors in command prompt. However its giving the following error when I am submitting the form SMTPAuthenticationError at /contact/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s1sm259896wrv.97 - gsmtp')