Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use mounted Azure Blob Storage Container in Azure App Service
I was able to mount azure blob storage on my local machine (Ubuntu 18.04) using blobfuse, just as documented here. To use it in an Azure App Service I found this, describing an option to mount Azure Storage using the Azure Portal interface. This does it for me... But how can I access the mounted storage from within my Django app? Is the mounted Storage accessible as directory via the filesystem? -
if (cart[idstr] != undefined) got error in this line
I have an error in != undefined and inneerhtml if (cart[idstr] != undefined) name = document.getElementById('name' + idstr).innerHTML; -
Non-UTF-8 code starting with '\x90' - django
After installing the django package successfully for particular project in pycharm, while I am trying to startproject from pycharm terminal, it's giving below error: (venv) C:\Users\user123\PycharmProjects\>django-admin startproject mysite File "C:\Users\user123\PycharmProjects\project_name\venv\Scripts\django-admin.exe", line 1 SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Users\user123\PycharmProjects\1project_name\venv\Scripts\django-admin.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details Do I need to make any changes in the installed package file to make it work? Please help.. -
Multiple Django servers to manage "collectstatic" to s3
I have two ec2 instances with Django and both of them set up Boto3, Django Storage, and Django Compressor packages to manage static files to upload to S3 bucket with some compressed files. Here I have a question. Do I need to execute collectstatic command at each server to upload static files and compressed files So that there are overwritten static files and two different compressed files created from different servers? Is this proper way of uploading static and compressed files from multiple servers? Or is there a better practice for this? -
How To Create A List Of Querysets
My Users take Classes (many-many) and classes have teachers (many-many). Im looping through a Users Classes and getting all the Teachers. I then store the Teachers Queryset in a variable. In my template I loop through my Classes and print the Class name, then within each Class I loop through and print the Teachers names. My problem is that the variable Im using to hold the Teachers is overridden every time my for loop loops. How can I store a list of Querysets which can be iterated in my template, printing the appropriate Teachers for each Class (this is my second problem, figuring out how to print the correct Teachers to match the Class)? users_classes = request.user.student.classes.all() for class in users_classes: teachers = class.teachers.all() {% for class in user.student.classes.all %} <h3 class="account-heading">{{ class.name }}</h2> {% for teacher in context.teachers %} <tr> <td>{{ teacher.name }}</td> </tr> {% endfor %} {% endfor %} Thank you. -
Unable to import 'django.urls'
Help please! am new to django please i have installed django in virtual environment i created on my desktop. but whenever i create a django project and open up the folder in vs code in the url.py file and the wsgi.py files there is a red underline in the import statements. and when i hover over it it says unable to import the package name this is from the wsgi.py file. it says unable to import django.core.wsgi i have not written any code so there are no errors yet but vscode shows a red underline on the from import statements from django.core.wsgi import get_wsgi_application also in the urls.py file it does the same thing from django.contrib import admin from django.urls import path i have tried uninstalling and installing django again but it didn't work. it still does the samething ps. i have not written any code in the django project prior to this but no doubt this will surely give me an error -
how can i filter the Json response by only passing the Year parameter to the DateTime field using DateFilter in Djangorestframework
i need a json response just by entering the year in parameter instead of date Note : i have around 25 columns of data in db so looking for simple solution Thanks models.py: '''class indicator(models.Model): fiscalyearend = models.DateField(db_column='FiscalYearEnd') serializers.py: class IndicatorSerializer(serializers.ModelSerializer): class Meta: model = indicator fields = ['fiscalyearend'] views.py filters: class indicatorDataBaseListView1Filter(filters.FilterSet): fiscalyearend = filters.DateFilter('fiscalyearend',label=('With start date'),lookup_expr='contains') view class indicatorView1(generics.ListAPIView): serializer_class = KeyperformanceindicatorSerializer queryset = Indicator.objects.all() #vice versa for get_queryset method filter_backends = (DjangoFilterBackend,OrderingFilter,SearchFilter) filterset_class = indicatorDataBaseListView1Filter''' url : localhost:8000/indicator/?fiscalyearend=2019 json output : enter a valid date my current date formate is 2019-01-01 i need to filter the json just by entering the year in the url instead of entire date -
Connecting mongodb database with django project
I want to connect my database on Atlas(Mlab) with my django project. I have python 3.7, django,djongo installed successfully. I am facing an error : django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I am sharing my settings.py (database section) file for your reference: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'ReminderSystemDbTest', 'HOST': 'mongodb+srv://jigarjoshiuser:joshipinakin@cluster0.mhzxu.gcp.mongodb.net/ReminderSystemDbTest?retryWrites=true&w=majority', 'USER': 'jigarjoshiuser', 'PASSWORD': 'joshipinakin', } #mongodb+srv://jigarjoshiuser:joshipinakin@databaseconnectivtiy.mhzxu.gcp.mongodb.net/ReminderSystemDbTest?retryWrites=true&w=majority } } I am sharing my manage.py file for reference : def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'db_connectivity.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() my wsgi file is: import os from django.core.wsgi import get_wsgi_application import sys sys.path.append("F:/connecting_database/db_connectivity") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'db_connectivity.settings') application = get_wsgi_application() Hierarchy is : CONNECTING_DATABASE-> db_connectivity db_connectivity pycache __init.py settings.py urls.py wsgi.py db.sqlite3 manage.py -
How to check images before storing in database in Django?
i created a simple architect related web app in Django. In which users can upload an image that related to architect stuff. I want some security in my web app that users can upload only those images that related to architect work. How to prevent users to upload images that are just spam or not related to content. which technique should I use here? I don't think that I should trust users that they are uploading. first I want to validate their images if it is related to the website content then store it in my database. How I can do this. -
"This field is required" in Django REST framework nested serializer
I have 2 seralizers, class AssetTypeChoiceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) class Meta: model = AssetTypeChoice fields = [ 'id', 'probe', 'choice', 'choice_name' ] read_only_fields = ('probe',) and a parent serializer class ProbeSerializer(serializers.ModelSerializer): asset_type_choices = AssetTypeChoiceSerializer(many=True) class Meta: model = Probe fields = [ 'id', 'city', 'street', 'neighborhood', 'rooms_from', 'rooms_to', 'price_from', 'price_to', 'asset_type_choices' ] def create(self, validated_data): asset_type_choices = validated_data.pop('asset_type_choices') probe = Probe.objects.create(**validated_data) for choice in asset_type_choices: AssetTypeChoice.objects.create(**choice, probe=probe) return probe everytime im posting to create a new probe im getting an error { "asset_type_choices": [ "This field is required." ] } when I remove AssetTypeChoiceSerializer and trying to post im succeding to create a new probe. this is my raw when im posting: { "city": "test", "street": "", "neighborhood": "", "rooms_from": 0, "rooms_to": 0, "price_from": 0, "price_to": 0, "asset_type_choices":[ { "id":1, "choice": 1, "choice_name":"All" }, { "id":2, "choice": 1, "choice_name":"All" } ]} What am I doing wrong? -
get count of distinct django sqlite3
I want to get count of a query set after selecting distinct of another field . My code: module_attempts_count = Subquery(ModuleProgressAttempt.objects.filter( module_progress__module__id=OuterRef('id')).values('module_progress__user').distinct().values('module_progress__module__id') .annotate(count=Count('id')).values('count')) real_instances = VirtualClassRoomModule.objects.filter( id__in=[vc.id for vc in vc_classrooms]).annotate( attendees_count=module_attempts_count, ) Im annotating a count field into the queryset . For evaluating the count i want the ModuleProgressAttempt of the current item with module_progress__user distinctly . One user should only be counted once . Postgres supports distinct('module_progress__user'). I want it to work in all databases. Current solution takes the total count without considering the distinct user . -
Is there any option to set already selected files in file input HTML
Developing an Admin console application to upload multiple images in Django application. Event creation & image uploading are working fine, when user updating the existing event. Able to list all image in the div, but not able to link with input file. Form submission failed due to input file missing. As per document due to security reason we are not able to update the input file values. How can we achieve this, please guide me. -
django model form create meta dynamically
I want to create one form that can be used with two different urls: 1. '/new/' 2. '/new/<int:category_pk>/' Both urls got to the same view that passes the request to the form: from .forms import ListingForm class ListingCreateView(FormView): form_class = ListingForm category = None def get_form(self): return self.form_class(request=self.request) The ModelForm should see if the argument 'category_pk' is passed and decide wether to display the 'category' field or not. from category.models import Category from .models import Listing FIELDS = ['title', 'category', 'quantity', 'unit', 'description'] class ListingForm(forms.ModelForm): request = None category = None def __init__(self, *args, request=None, **kwargs): self.request = request category_pk = request.resolver_match.kwargs.get('category_pk') if category_pk: self.category = Category.objects.get(pk=category_pk) self.Meta.fields.remove('category') super().__init__(*args, **kwargs) def save(self, commit=True): self.instance.user = self.request.user if self.category: self.instance.category = self.category return forms.ModelForm.save(self, commit=commit) class Meta: model = Listing fields = FIELDS How can i switch Meta.fields dynamically? -
How to Update Current Datetime using UpdateView in Django
Wants to update current Datetime using UpdateView class UpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['date_commit'] -
Limit to a single block when looping through Wagtail paragraph streamfield Items?
I have added 4 paragraph blocks in a streamfields. When looping over the paragraph block, it show all 4 paragraph in separate tags. How can I only limit it to the first paragraph block? I tried using this solution: {% if forloop.counter0 == 0 %} <p>{{block.value}}</p> {% endif %} But the problem was that its only possible when the paragraph field is placed in the first order. For example, there can be 3 images before the first paragraph which makes the possible solution void. blog/models.py class BlogPage(Page): body = StreamField([ ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body') ] blog_page.html {% for block in page.body %} {% if block.block_type == 'paragraph' %} <p>{{block.value.0}}</p> <!-- Another attempt at trying to get single paragraph --> {% endfor %} -
Use a custom manager in a ModelSerializer
After hours of searching, I finally decided to ask the community. So, I have 2 models, (vehicle and trace) and a manager to get validated traces from vehicle. class Vehicle(models.Model): field1 = models.TextField() field2 = models.DateField() class Meta: db_table = "vehicle" managed = False class Trace(models.Model): objects = models.Manager() validated = ValidatedTraceManager() vehicle = models.ForeignKey( Vehicle, db_column="vehicle", related_name="traces", on_delete=models.DO_NOTHING ) validation_required = models.BooleanField() class Meta: db_table = "trace" managed = False class ValidatedTraceManager(models.Manager): def get_queryset(self): return Trace.objects.filter( models.Q(validation_required__isnull=True) | models.Q(validation_required=False) ) I use serializer to convert vehicle instance to Json to send them into Response. Here is the serializers: class VehicleSerializer(serializers.ModelSerializer): color = ColorSerializer() traces = TraceSerializer(many=True) class Meta: model = Vehicle fields = ["field1", "field2", "traces"] class TraceSerializer(serializers.ModelSerializer): class Meta: model = Trace fields = ["date", "mileage"] The questions is, How can I use "validated" manager in VehicleSerializer to get traces instead of "objects" manager?? I precise that i want to keep "objects" as default manager for model Trace. -
Django raises RelatedObjectDoesNotExist when forms.DateField with widget DateInput is defined on the Form class
When Forms.DateField with widget DateInput is defined on the Form class I am getting an exception. When I remove the line dateCreated = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), initial=datetime.date.today) update works as expected. Any hint appreciated. Exception RelatedObjectDoesNotExist at /kitchen/stockreceipt/update/2 Item has no article. In .../models.py in clean article = Article.objects.filter(pk=self.article.id).values_list('onStock', 'unit') … ▼ Local vars Variable Value self Error in formatting: RelatedObjectDoesNotExist: Item has no article. models.py class StockReceipt(models.Model): dateCreated = models.DateField(default=datetime.date.today) class Article(models.Model): ... class Item(models.Model): stockReceipt = models.ForeignKey(StockReceipt, blank=True, null=True, on_delete=models.CASCADE,) article = models.ForeignKey(Article, on_delete=models.CASCADE) views.py class StockReceiptUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView): model = StockReceipt form_class = StockReceiptForm template_name = 'kitchen/stockreceipt/edit.html' def get_context_data(self, **kwargs): context = super(StockReceiptUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['items'] = StockReceiptFormSet(self.request.POST, instance=self.object) else: context['items'] = StockReceiptFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): form.instance.userCreated = self.request.user self.object = form.save() # print(self.object, self.object.id) if items.is_valid(): items.instance = self.object # items.stockReceipt = self.object.id items.save() return super(StockReceiptUpdateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('kitchen:updateStockReceipt', kwargs={'pk': self.object.pk}) forms.py class StockReceiptForm(forms.ModelForm): dateCreated = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), initial=datetime.date.today) class Meta: model = StockReceipt exclude = ["userCreated"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.disable_csrf = False self.helper.field_template = 'bootstrap3/layout/inline_field.html' # self.helper.template = 'bootstrap/table_inline_formset.html' self.helper.layout = Layout( Row( Column('dateCreated', … -
Stop automatically a task (Viewflow, Django)
I've splited the flow and assigned several tasks to different users. How can I stop all the tasks after a certain time and collect the available responses? -
How to overwrite the send_product_alerts method in django oscar under the customer app?
django-oscar 2.0.2 I am trying to overwrite the alerts section in Django oscar under the customer App utils.py , i want to customize the methods send_alert_confirmation, send_product_alerts, to add request in the context of site. As on the production, i am working with multiple domains, setup using the sites framework, When I add stock and pricing for a product, then when a alert is sent after a product comes in stock, i am getting a error that, You're using the Django "sites framework" without having set the SITE_ID setting. Create a site in your database and set the SITE_ID setting or pass a request to Site.objects.get_current() to fix this error. I have customized the views and models, but how to i overwrite this methods(send_alert_confirmation,send_product_alerts) to add request in Site. ctx = { 'alert': alert, # 'site': Site.objects.get_current(), #old 'site': Site.objects.get_current(request), #new 'hurry': hurry_mode, } Also do i need to, pass a request to Site.objects.get_current(), everywhere oscar has used this or not ?, because I checked this same code is used to attach site in order views and mixins also, but there I am not getting error for passing a request in site object. Also, I have added the CurrentSiteMiddleware that … -
Elastic Beanstalk - Daphne is not serving static files
Following this guide https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 to set up a django project that uses websockets. Before I made the traffic go through Daphne, the static files were being served, but now I get on the console that the files are not found. 01_env.config option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: dashboard.settings PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elasticbeanstalk:container:python: WSGIPath: dashboard/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": /static/: "static/" aws:elbv2:listener:80: ListenerEnabled: 'true' Protocol: HTTP aws:elbv2:listener:5000: ListenerEnabled: 'true' Protocol: HTTP 02_setup.config container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' 04_celery_tasks: command: "cat .ebextensions/celery_configuration.txt > /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 05_celery_tasks_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/run_supervised_celeryd.sh" leader_only: true 03_proxy.config files: "/etc/httpd/conf.d/proxy.conf": mode: "000644" owner: root group: root content: | ProxyPass /websockets/ ws://127.0.0.1:5000/websockets/ ProxyPassReverse /websockets/ ws://127.0.0.1:5000/websockets/ ProxyPass / http://127.0.0.1:5000/ ProxyPassReverse / http://127.0.0.1:5000/ settings.py ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Running Daphne using: daphne -b 0.0.0.0 -p 5000 dashboard.asgi:application -
Protecting API endpoints in Django RF
I have a Django Rest framework backend and React frontend project running at server and let website name is www.test.com. Anyone can access the website urls using Postman or other tools and upload contents with token once the are registered. So anyone can crash the database easily. How can I protect it so that only those who visit my website can access content and it won't be available to API management softwares like Postman ? Should I change ALLOWED_HOSTS=['www.test.com'] in settings.py module ? -
Django site separate front-end (Azure) and back-end(Heroku)
I have a Django app in Herouku, I wondering if is possible to use Azure as a front-end and keep Heroku for the back-end. Thank you -
Django Model.object.get returns only one attribute
I am trying to return an object from a database in Django. So I have this line in my views.py: single_appointment = Appointment.objects.get(id=int(app_id)) app_id is passed into the view as an argument. I seem to be able to access the database, but the only problem is that if I print the single_appointment in the console, it prints just one attribute of the appointment object. How do I get the whole object so I can access its attributes? -
Getting Data From Models Connected By An Intermediate Model
I have the following relationships: class BaseModule(models.Model): task_type = models.CharField(max_length=200) topic = models.CharField(max_length=200) # packages contain many modules class ModulePackage(models.Model): name = models.CharField(max_length=200) individual_modules = models.ManyToManyField(BaseModule, blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) individual_modules = models.ManyToManyField(BaseModule, blank=True) module_packages = models.ManyToManyField(ModulePackage, blank=True) When a Student is logged in and goes to their profile page I can print a list of the Student's Packages but cannot figure out how to print a list of BaseModules contained within each Package. I know I would need to get this data in view. I would need to loop through a Students Packages and obtain the BaseModules that each has. Then pass this data to my template. Ive spend a long time Googling and looking through SO but cant find anything on this. Thank you. -
Getting a 404 for a view that doesn't have a "get_object_or_404" function
So I am creating a simple product catalog view: @login_required(login_url='login') def catalog(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'store/catalog.html', {'category': category, 'categories': categories, 'products': products}) However, after creating this view, whenever I navigate to any of my other pages but 'Home'... a 404 is raised...Why is this. The DEBUG says: "Raised by: store.views.catalog" Views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.contrib.auth.decorators import login_required from .models import Category, Product # Create your views here. @login_required(login_url='login') def home(request): context = {} return render(request, 'store/home.html', context) @login_required(login_url='login') def catalog(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'store/catalog.html', {'category': category, 'categories': categories, 'products': products}) def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) return render(request, 'store/detail.html', {'product': product}) @login_required(login_url='login') def order(request): context = {} return render(request, 'store/order.html', context) def dashboard(request): return render(request, 'store/dashboard.html') def customer(request): return render(request, 'store/customer.html') urls.py: from django.urls import path from . import views urlpatterns = [ path('home/', views.home, name='home'), path('catalog/', views.catalog, name='catalog'), path('<slug:category_slug>/', views.catalog, name="catalog_list_by_category"), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('order/', views.order, name="order"), path('dashboard/', views.dashboard, name="dashboard"), path('customer/', views.customer, …