Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
how to clean two fields in one clean method django
hi i want to clean data of more than one field at a time class PC(models.Model): name = models.CharField(max_length=20) price = models.IntegerField() quantity = models.IntegerField() guarantee = models.IntegerField() forms.py class PcForm(forms.ModelForm): class Meta: model = PC fields '__all__' clean(self): cleaned_data = super().clean() price = cleaned_data.get('price') if price > 1000: raise forms.ValidationError('some massege') qnt = cleaned_data.get('quantity') if qnt > 3: raise forms.ValidationError('some massege') return cleaned_data i want to display both errors together when if price > 1000 and quantity > 3 raise both the error? but now display nothing !? thanks -
Calculated field is not getting saved in database in django admin models
I recalculated field total_amount in total_amount() method. This working fine in django admin but updated value of total_amount is not getting saved in database column. This is my models.py class Orders(models.Model): order_id = models.IntegerField(primary_key=True) order_item = models.ForeignKey('Product', models.DO_NOTHING, db_column='order_item', blank=True, null=True, related_name='ordered_item') order_status = models.CharField(max_length=100, blank=True, null=True) delivery_address = models.TextField(blank=True, null=True) customer = models.ForeignKey('User', models.DO_NOTHING, db_column='customer', blank=True, null=True) quantity = models.IntegerField() rate = models.ForeignKey('Product', models.DO_NOTHING, db_column='rate', blank=True, null=True) total_amount = models.DecimalField(blank=True, null=True,decimal_places=2,max_digits=10) def total_amount(self): rate = Product.objects.get(pk=self.order_item.product_id) self.total_amount = rate.price * self.quantity return self.total_amount class Meta: managed = False db_table = 'orders' The value i got from total_amount() method is not updating in database. this is my admin.py class OrderAdmin(admin.ModelAdmin): list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer', 'quantity','unit_rate','total_amount') exclude = ['rate'] readonly_fields = ('unit_rate','total_amount',) def unit_rate(self,obj): rate = Product.objects.get(pk=obj.order_item.product_id) return rate.price admin.site.register(Orders,OrderAdmin) -
How to stop DjangoJSONEncoder from truncating microseconds datetime objects?
I have a dictionary with a datetime object inside it and when I try to json dump it, Django truncates the microseconds: > dikt {'date': datetime.datetime(2020, 6, 22, 11, 36, 25, 763835, tzinfo=<DstTzInfo 'Africa/Nairobi' EAT+3:00:00 STD>)} > json.dumps(dikt, cls=DjangoJSONEncoder) '{"date": "2020-06-22T11:36:25.763+03:00"}' How can I preserve all the 6 microsecond digits? -
Cronjob on AWS Elastic Beanstalk Django App
Im having issue on running my cron jobs from Django EB. When i deployed it shows no error but the cronjob is not running. the import_incontact_statelogs.py is a script that should dump a set of data to my database. Here's my config file inside .ebextension -----Cronjob.config-------------- files: "/usr/local/bin/check_leader_only_instance.sh": mode: "000755" owner: root group: root content: | #!/bin/bash INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null` REGION=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document 2>/dev/null | jq -r .region` # Find the Auto Scaling Group name from the Elastic Beanstalk environment ASG=`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" \ --region $REGION --output json | jq -r '.[][] | select(.Key=="aws:autoscaling:groupName") | .Value'` # Find the first instance in the Auto Scaling Group FIRST=`aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $ASG \ --region $REGION --output json | \ jq -r '.AutoScalingGroups[].Instances[] | select(.LifecycleState=="InService") | .InstanceId' | sort | head -1` # If the instance ids are the same exit 0 [ "$FIRST" = "$INSTANCE_ID" ] "/usr/local/bin/my_cron_script.sh": mode: "000755" owner: root group: root content: | #!/bin/bash /usr/local/bin/check_leader_only_instance.sh || exit source /opt/python/run/venv/bin/activate source /opt/python/current/env cd /opt/python/current/app python manage.py shell < automations/import_incontact_statelogs.py "/etc/cron.d/daily_cron": mode: "000644" owner: root group: root content: | */10 * * * * root /usr/local/bin/my_cron_script.sh commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true -
Django pass value of TabularInline field when Buttonclick
I have a Course model and pupils model. Pupils are a tabularInline in the Course admin Panel. I implemented in tabular.html a Button for every Line in front of the pupils: <input type="submit" value="pass" name="pass_arguments" onclick="location.href='{% url '...' %} The mission is to pass the first name and surname of the pupil when I click a Button. For instance: 7 Pupils. When i click the Button of Pupil 3, a new page opens where i can see the first name and surname in a new template. How can I pass the first name and surname as values? Thank you very much. I'm really struggling. -
Updating django model when changing
The model has a "content" field. When changing this model, it is necessary to look for the symbol "<a" in the "content" field and add the line "rel =" nofollow "into it (as if in a tag). I’m trying to do this with a function in the models.py file. Tell me how to do this ?