Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dynamic report generation based on user selection django
I have a 3 tier application (Front end angular, backend django and mssql) i have come across bit of a situation now where we have to build the reports based on users selection. we have multiple table's and columns, and stored procedures to get required output. for example, in report we have name place dob rank branch subject and many more. so user selects required feilds, not all, he might select only name and dob.or more. and we are taking it from different tables multiple stored procedures for those query. How do we fetch the user requested data from database and pass it to frontend through django -
Email send django returning error when details comes from database
I have A FUNCTION TO SEND MAIL IN django helper file my function is givenm below def mail_send(data): result = {} getTemplate = EmailTemplate.objects.filter(pk=data['type']).first() if getTemplate != None: templates = Template(getTemplate.template) config = EmailConfiguration.objects.filter(pk=1).first() context = Context( { 'name': data['name'], 'password': data['password'], 'site_name': config.site_name } ) msg_plain = 'Login Details ' + data['name'] + ' / ' + data['password'] msg_html = templates.render(context) EMAIL_USE_TLS = config.tls EMAIL_HOST = config.host EMAIL_HOST_USER = config.from_email EMAIL_HOST_PASSWORD = config.password EMAIL_PORT = config.port mail = send_mail( data['msg'], msg_plain, EMAIL_HOST_USER, [data['email']], fail_silently=False, html_message=msg_html, ) else: result['msg'] = 'Template Not Found .Unable to send Email..' result['status'] = False its returning me the error like : [Errno 111] Connection refused but when i put all this setting in settings.py its working fine with me but i dont want this i want to come from database and send a mail please suggest me i am stuck here from last day .i am newbe in django so its getting verry difficult to me -
how to know all django reverse lookups pointing to a model
I have a model A, and several models (B, C and D), all of them with a foreign field pointing to A. I want to implement a method to collect all records in B, C, and D related to each record in A, through the reverse look ups set in foreign keys in B, C and D. The problem is that the amount of models with a foreign key pointing to A can change, so I want to make the method dynamic, so I need to know the models and their fields pointing at A, and their related_name. Is there a way to obtain this information? -
Is there any way to query UUID in graphQL-ariadne
I am new to GraphQL and I am using ariadne. Sorry if this sounds dubious but is it possible to create a type UUID in ariadne and query the same. If so, then how. Also how do I create a custom type in ariadne. -
django - database - migrating from sqlite3 to postgresql on server and local
Two databases were setup for my django app on server (Ubuntu 18.04), sqlite is for development, PostgreSQL is for production. It is probably a stupid idea in the first place: because of an environment variable error, sqlite was still being used in production and user has been uploading data (files and pictures) for a while. I now need to change the database to PostgreSQL on the server without losing the data. I found some solutions on google but none is suitable, I'm trying to get as much help as I can. Thanks guys! -
Problem setting initial Django ModelForm field value
I’m trying to set the default value in the form (the field is the date for publishing the article “public”), but when loading the form on the page, the field is empty. I tried to set the default value in the "header" field (any value, not necessarily today's date) - also does not appear. form: from main.models import Article from datetime import datetime class AddArticleForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddArticleForm, self).__init__(*args, **kwargs) self.fields['publish'].initial = datetime.now() class Meta: model = Article fields = ('title', 'author', 'body', 'publish', 'status') labels = { 'body': 'Text' } widgets = { 'title': forms.TextInput(attrs={'class': 'md-form'}), 'author': forms.TextInput(attrs={'class': 'md-form'}), 'body': forms.Textarea(attrs={'class': 'md-textarea', 'rows': 3}), 'publish': forms.DateTimeInput(attrs={'class': 'md-form'}), 'status': forms.Select(attrs={'class': 'custom-select'}) } views: def add_article(request): form = AddArticleForm(request.POST) if form.is_valid(): form.save() return redirect('/articles/') args = { 'form': form } return render(request, 'html/add_article.html', args) html: ... <form action="." method="post" class="add-article"> {% csrf_token %} {% for field in form %} <div class="md-form"> {% if field.name != 'status' and field.name != 'publish' %} <label for="{{ field.name }}">{{ field.label }}</label> {{ field }} {% else %} <label for="{{ field.name }}"></label> {{ field }} {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-pink btn-block">Share</button> </form> ... enter image description here -
Django - Does user have to stay on website after pressing "Submit" button in form - for POST request to be processed?
I have a form that lets a user upload a csv file and has a submit button. Does the user need to stay on the webpage after pressing the submit button, "while page is reloading", in order to ensure that rows from the csv are added to the database? Or can user immediately leave the page after pressing submit button, and the rows from csv will still be added to database? Here is my views.py file: import pandas as pd from .models import Contact def upload_contacts(request): template = "contact_upload.html" prompt = { 'order': 'Order of the CSV should be first_name, last_name' } if request.method == "GET": return render(request, template, prompt) your_file = request.FILES['file'] df = pd.read_csv(your_file) if your_file.name.endswith('.csv'): for index, row in df.iterrows(): created = Contact.objects.update_or_create( first_name = row[0], last_name = row[1] ) else: messages.error(request, 'This is not a CSV file, please try another file.') context = {} return render(request, template, context) -
Django getlist() bug?
I did not received any error but I know that the in the database save record is incorrect, is it a bug in getlist()? or did i miss something in code? please tell me why wrong record save in the database def corevalues(request): coregradelevel = request.GET.get('coregradelevel') coreperiod = request.GET.get('coreperiod') marking = StudentBehaviorMarking.objects.all() teacher = request.GET.get('teacher') corevalues = CoreValues.objects.all().order_by('Display_Sequence') corevaluesdescription = CoreValuesDescription.objects.values('id','Description').distinct('Description').order_by('Description') corevaluesperiod = CoreValuesDescription.objects.filter(grading_Period=coreperiod).order_by('Display_Sequence') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') gradelevel = EducationLevel.objects.filter(id__in = coregradelevel).distinct().order_by('id') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher = teacher).filter(GradeLevel = gradelevel.values_list('Description'))\ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by('Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher = teacher).filter(GradeLevel__in = gradelevel.values_list('id')) this is my html code <table class="tblcore"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> {% endfor … -
How to change resetting password of django
I am learning to use django and my question is if it is possible to change the system to reset the users' password, the default system of sending a link by mail I do not want to use it, my idea is to send a code to reset the password , but I don't know how it should be done and if possible, I would also need to know if it's safe. What I want is for the user who wants to recover his password to go to the recovery section, fill in his email and choose to send and enable a field to put the code that was sent to the mail. I don't know how I should do it or is there a package for this? Thank you very much people greetings. -
IntegrityError at /add-to-cart/test2/ NOT NULL constraint failed: core_order.items_id
The problem might be in views.py file in add_to_cart() method. this method is using 3 classes from models.py Here is my views.py file from django.shortcuts import render from .models import Item, Order, OrderItem from django.views.generic import ListView, DetailView from django.shortcuts import reverse, get_object_or_404, redirect from django.utils import timezone class HomeView(ListView): model = Item template_name = 'home-page.html' class ItemView(DetailView): model = Item template_name = 'product.html' def checkout(request): context = { 'items': Item.objects.all() } return render(request, 'checkout-page.html', context) def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.create(item=item) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("core:product", slug=slug) my models.py file. the Order class id is creating the problem. Exception Value: NOT NULL constraint failed: core_order.items_id Exception Type: IntegrityError from django.conf import settings from django.db import models from django.shortcuts import reverse, get_object_or_404, redirect Categoty_choice = ( ('s', 'Shirt'), ('sw', 'Sport Wear'), ('o', 'Outwear') ) Label_choice = ( ('p', 'primary'), ('s', 'secondary'), ('d', 'danger') ) class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=Categoty_choice, max_length=2) label = models.CharField(choices=Label_choice, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title … -
python: Which is more cryptographically secure random
I have found the following ways to get cryptographically secure random string in python using secrets. Using token_urlsafe import secrets secrets.token_urlsafe(50) # Note 50 is bytes. base64 uses 6bits for a character so (50 x 8)/6 = 67 's9HXAIOVizuJS8tdF6r3KA35XEcEcATIzTKeyvat8oIZf6WeR_e-nbvPv4W0fg-nLgI' Using Choice #django: Method used by get_random_secret_key() allowed_chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)' length=50 ''.join(secrets.choice(allowed_chars) for i in range(length)) 'z%+9t$d-nu)&%v@f)by@$$lk*h=%hma3r(lx0nud7^7@)*6ls2' Also why django prefers to use secrets.choice -
Recommend A Technology Stack for Building a Web Based Music Streaming Platform Similar to Spotify Web Player
I am junior developer and I am trying to get an idea/recommendation for a technology stack that I will use to develop a music streaming web application MVP (minimum viable product) for my entrepreneurship class at my University. I chose this entrepreneurship class because I wanted to focus on improving my web development skills and improve my resume by adding projects. and it gave me a perfect opportunity. So in the first day of class, our professor brought in 3 companies/startups and asked us to team up in groups of 4 and work on this project for the whole semester. Since the music app required a software developer, I chose the music streaming app. I can't tell you guys what makes this music streaming platform different or tell you its unique value proposition as compared to other giants like Spotify and Apple Music because of a contract. But that shouldn't really trouble with recommending a tech stack to use. The CEO already has some investors and has already given his mock design to a software development company to develop the mobile app. So he has asked me to help him out with building the web player. I am trying to … -
Django : New values are added to mysql table , but not shown in html template until server restart
Im using python 3.8 amd django 3 I have two users - (admin and worker) When worker add (food) in foods table, the food list template shows the newly added item (for worker). But at the same time in another browser, if admin refresh the food list page, the new value is not displayed until server restart . Is there any fix for it. Im not using any models. Thank you -
This queryset contains a reference to an outer query and may only be used in a subquery
model ProductFilter has products ManyToManyField. I need to get attribute to_export from product.filters of the highest priority (ProductFilter.priority field) I figured out this filters = ProductFilter.objects.filter(products__in=[OuterRef('pk')]).order_by('priority') Product.objects.annotate(filter_to_export=Subquery(filters.values('to_export')[:1])) But it raises ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Do you know why? -
How to get a QuerySet's object's attributes
I am trying to filter a QS like this: context['tfquestions'] = TF_Question.objects.filter(receiver__in=sub_list) I would like the sub_list to be the .role() of subordinates like this: sub_list = self.request.user.subordinates.all() # want to get the `.role()` field of each object in this QS -
Periodically run a function in Django by celery and cronjob
I am trying to run a function periodically and to do that, setup the celery. But something is wrong because the function is not running in the end. I guess, did a mistake somewhere in road, but couldn't find it. So let me explain the steps in my Django project. project's src folder I setup redis. # REDIS related settings REDIS_HOST = 'localhost' REDIS_PORT = '6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' and celery.py in src dir. import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') app = Celery('src') app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(settings.INSTALLED_APPS) app.conf.beat_schedule = { 'create-tasks-histories': { 'task': 'myApp.views.historyFunction', 'schedule': crontab(hour=12, minute=7, day_of_week="wed") }, } in view.py def historyFunction(request): print("periodic function") return Response() then I run the command $ celery -A src beat So checking the terminal that running the django app. But no print() So what's wrong in here? And what is best way to run a function periodically? I also tried this out too... in views.py from celery.schedules import crontab from celery.task … -
ProgrammingError at / operator does not exist: date = boolean
I made a website with django and mysql and when I tried to deploy it to heroku, the deployment was successful but if I try to access my website I get this error: 2020-03-04T02:41:33.999463+00:00 app[web.1]: Internal Server Error: / 2020-03-04T02:41:33.999471+00:00 app[web.1]: Traceback (most recent call last): 2020-03-04T02:41:33.999472+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute 2020-03-04T02:41:33.999472+00:00 app[web.1]: return self.cursor.execute(sql, params) 2020-03-04T02:41:33.999473+00:00 app[web.1]: psycopg2.errors.UndefinedFunction: operator does not exist: date = boolean 2020-03-04T02:41:33.999473+00:00 app[web.1]: LINE 1: ...ng_createdeal" WHERE "booking_createdeal"."available" = true 2020-03-04T02:41:33.999474+00:00 app[web.1]: ^ 2020-03-04T02:41:33.999474+00:00 app[web.1]: HINT: No operator matches the given name and argument types. You might need to add explicit type casts. 2020-03-04T02:41:33.999475+00:00 app[web.1]: 2020-03-04T02:41:33.999475+00:00 app[web.1]: 2020-03-04T02:41:33.999476+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2020-03-04T02:41:33.999476+00:00 app[web.1]: 2020-03-04T02:41:33.999477+00:00 app[web.1]: Traceback (most recent call last): 2020-03-04T02:41:33.999477+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner 2020-03-04T02:41:33.999478+00:00 app[web.1]: response = get_response(request) 2020-03-04T02:41:33.999478+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response 2020-03-04T02:41:33.999479+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2020-03-04T02:41:33.999479+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response 2020-03-04T02:41:33.999480+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2020-03-04T02:41:33.999480+00:00 app[web.1]: File "/app/booking/views.py", line 20, in index 2020-03-04T02:41:33.999481+00:00 app[web.1]: return render(request, 'base.html', {'all_deals': all_deals, 'description': description}) 2020-03-04T02:41:33.999481+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render 2020-03-04T02:41:33.999482+00:00 app[web.1]: content = loader.render_to_string(template_name, context, … -
Lookup by object chosen from related set in Django
I have two models Product and ProductFilter. The ProductFilter has priority = IntegerField(...) field and active = BooleanField(...). class ProductFilter(..): products = ManyToManyField('Product....) I want to filter products with the active = True field for their ProductFilter with the highest priority. I can choose product_filter with the highest priority: product.filters.all().order_by('priority').last() But this needs a for loop which multiplies number of queries. Is it possible to do that in one Query? Maybe somehow aggregate/annotate the product_filter with the highest priority as active_filter and then Product.objects.annotate(active_filter=Somehow annotate).filter(active_filter__active=True) -
Django - How to access internal API from views?
I have created an API with some endpoints like: www.domain.com/api/items www.domain.com/api/items/1 www.domain.com/api/items/available Now I want to be able to do those same queries from my views to populate my HTML. I've been reading that you can do it using: requests.get('localhost/api/items') But I'm wondering if there is a way of doing it internally, like maybe calling the viewset directly, or something similar. Thanks! -
Passing django objects.values() into Django Rest Framework Serializer
I'm trying to get the same output as my django query but the actual output differs when Django Rest Framework serves it. Added the following to my serializer but all kept leaving out the cart_assessments__risk_type out of the output. How do I make my serializer output match my django query output? models.py: class TrainAssessment(models.Model): train_name = models.CharField(max_length=30) class CartAssessment(models.Model): train_assessment = models.ForeignKey(TrainAssessment, on_delete=models.CASCADE, related_name='cart_assessments') risk_type = models.CharField(max_length=30) query: queryset = TrainAssessment.objects.values('cart_assessments__risk_type').annotate(cart_count=Count('cart_assessments__risk_type')).order_by('-cart_count').annotate(train_count=Count('id', distinct=True)) Output of Django Query that I want for my serializer: {'cart_assessments__risk_type': '', 'cart_count': 55, 'train_count': 14} {'cart_assessments__risk_type': 'door', 'cart_count': 22, 'train_count': 13} {'cart_assessments__risk_type': 'wheel', 'cart_count': 8, 'train_count': 8} {'cart_assessments__risk_type': 'frame', 'cart_count': 1, 'train_count': 1} {'cart_assessments__risk_type': 'floors', 'cart_count': 1, 'train_count': 1} {'cart_assessments__risk_type': 'windows', 'cart_count': 1, 'train_count': 1} {'cart_assessments__risk_type': 'straphanger', 'cart_count': 1, 'train_count': 1} views.py class SubwayTrainDetailsViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): queryset = TrainAssessment.objects.values('cart_assessments__risk_type').annotate(cart_count=Count('cart_assessments__risk_type')).order_by('-cart_count').annotate(train_count=Count('id', distinct=True)) serializer_class = serializers.SubwayTrainDetailsViewSetSerializer serializers.py class SubwayTrainDetailsViewSetSerializer(serializers.ModelSerializer): train_count = serializers.IntegerField() cart_count = serializers.IntegerField() cart_assessments = serializers.RelatedField(source="cartassessment.risk_type", read_only=True) class Meta: model = TrainAssessment fields = ('id', 'cart_assessments', 'train_count', 'cart_count') Actual Output missing 'cart_assessments__risk_type' from Django Rest Framework: [ {"train_count": 14, "cart_count": 55}, {"train_count": 13, "cart_count": 22}, {"train_count": 8, "cart_count": 8}, {"train_count": 1, "cart_count": 1}, {"train_count": 1, "cart_count": 1}, {"train_count": 1, "cart_count": 1}, {"train_count": 1,"cart_count": 1} ] How can I … -
Django - External URL Link
I am new to Python and Django, and I have just created a website. Basically I would like to have a page on the website that displays our company partners. I have created an app 'partners' and in the model, I have 'website' as one of the fields. On the partners html file, I have a button that users can click and this will take them to the partner's website in a new tab. I tried to link the website in the following way: {{ partner.website }} However this ends up like: www.mydomain.com/partners/www.partnerwebsite.com I just want the partner website (www.partnerwebsite.com) to open in a new tab. Any help appreciated. If there is already another post on this, please redirect me. -
Django Channels session is not persistent. disconnect -> logged out
I have a websocket-router: application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url("ws/", Consumer) ] ) ) ) }) I am logging in a user by sending a command to the websocket. The user gets logged in like this: if cmd == 'login': user = await database_sync_to_async(authenticate)(consumer.scope, email=request['eMail'], password=request['pass']) if user is not None: # login the user to this session. await login(consumer.scope, user, backend='allauth.account.auth_backends.AuthenticationBackend') # save the session consumer.scope['session'].modified = True await database_sync_to_async(consumer.scope['session'].save)() Every time, the websocket-connection gets disconnected, the user is not logged in anymore. I thought, the session gets saved by consumer.scope['session'].save() but it doesn´t work. The session is not persistent. How can I solve this problem? -
Testing method that returns relation model attribute
I have the following models: class Course(Base): title = models.CharField('Título', max_length=200) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) def get_category(self): return self.subcategory.category class SubCategory(Base): title = models.CharField('Título', max_length=80) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Category(Base): title = models.CharField('Título', max_length=80) How can I test the get_category method? I'm trying to do that but the test don't pass on coverage report. -
Importing data from text file to Django database
I have some data in a pipe-delimited text file that I would like to import into a simple Django database. My Django model is as follows: class Info(models.Model): ID = models.IntegerField() name = models.CharField() date = models.DateField() price = models.IntegerField() def __str__(self): return self.date + "" + self.price and the text file is as follows: 1 | 47891 2 | John Smith 3 | 1/1/2019 | 10.94 1 | 67154 2 | Harry Jones 3 | 2/1/2019 | 3.72 3 | 2/1/2019 | 8.94 ... And so on. So, 1 is on the same line as an ID number, 2 is the same line as the corresponding name, and then 3 is the same line as the corresponding date and price; the latter of which there may be multiple. I am trying to find a way to import this information into my database so that each row has an ID, name, date and price. I am unsure firstly of the best format for the text file; should I convert it to a CSV file? And how can I extract the relevant information for the database? -
Django 2.2.9 - unexpected results from timedelta()
Please forgive me if this has already been asked I am following a course online, albeit 3 years old, so somethings have been updated since then However datetime seems to be roughly the same from what I can see. The problem arises when we use timedelta to filter all the sales in the last month I have added some test sales over the weeks and when I tried to filter it down to the last 48 hours, nothing with a bit of testing i went back 12 days (as of this question and a list of items sold back on the 20th February showed up but nothing sooner. I went into the admin and updated one of them and refreshed the page. and it disappeared completely Can anyone provide any insight as to what i am missing? If you need more information please say: Models.py from decimal import Decimal import datetime from django.conf import settings from django.db import models from django.db.models import Count, Sum, Avg from django.db.models.signals import pre_save, post_save from django.urls import reverse from django.utils import timezone from addresses.models import Address from billing.models import BillingProfile from carts.models import Cart from ecommerce.utils import unique_order_id_generator from products.models import Product ORDER_STATUS_CHOICES = …