Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Storing values in django template
in my random_numbers.py i have this: from django import template from random import randint register = template.Library() @register.simple_tag() def randomNumber(): return randint(1, 250) I basically want to call a random number in the Django template, store it, then compare. I tried using javascript and wrote this: {% load random_numbers %} <script> var random_number = "{% randomNumber %}" console.log(random_number); document.getElementById("random").innerHTML = random_number; </script> But I'm not sure how to collect the js variable in the Django template, can anyone help with this or show me another approach? -
Create view with more models
hi everyone I have a doubt with the use of forms and models. I have to create a code that creates records in multiple tables and I don't know how to do it. my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user. I'm a beginner I still have to learn the mechanism well =) forms.py from django import forms from .models import Schede, DatiGruppi, Gruppi class CreaSchedaForm(forms.ModelForm): nome_scheda = forms.CharField( required = True, label ='Nome scheda', widget = forms.TextInput( attrs = { 'class': 'form-control', 'placeholder' : 'nome scheda', 'autocomplete' : 'off' } ) ) data_inizio = forms.DateField( label='Data inizio', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data inizio' } ) ) data_fine = forms.DateField( label='Data fine', widget = forms.DateInput( attrs= { 'type': 'date', 'class': 'form-control', 'placeholder' : 'data fine' } ) ) class Meta: model = Schede fields = ['nome_scheda','data_inizio','data_fine'] class CreaDtGruppoForm(forms.ModelForm): giorni_settimana = forms.ChoiceField( choices = DatiGruppi.giorni_settimana_scelta ) dati_gruppo = forms.ModelChoiceField( queryset = Gruppi.objects.all(), empty_label = "-", required = True ) class Meta: model = DatiGruppi fields = ['giorni_settimana', 'dati_gruppo'] views.py @login_required … -
form validation redirection problems
Hi i am adding comments on a post using django, im saving the information directly in the database , this operates successfuly, but after submitting the post it suppose to redirect on the same page with the comment but, the form keep on resubmitting help please? views.py class PostDetailView(DetailView): def get(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments': comments } return render(request, 'my_news/post_detail.html', context ) def post(self, request, slug, *args, **kwargs): post = Post.objects.get(slug=slug) form = CommentForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.name = request.user new_post.post= post new_post.save() comments = Comment.objects.filter(post=post).order_by('-date_created') context = { 'post':post, 'form': form, 'comments':comments } return render(request, 'my_news/post_detail.html', context ) -
how to use tag url in js admin django "django.jQuery"
I have a js app using ajax, but it's being called in admin, example js django.jQuery.ajax({ type: 'post', // url: "{% url 'emails_checkout' %}", url: '{% url "emails_checkout" %}', data: { 'template': evt.editor.getData() }, but url rendering is real url plus string in http /admin/shop/post/1/change/%7B%%20url%20%22emails_checkout%22%20%%7D HTTP/1.1" 500 12622 how to use the tag {% url '' %} correting -
Could you help me please how i can put an empty file in django rest framework
I am using django rest framework my problem is that i can post image successfully but i want to post an empty image using put method only. Following is my code: My models.py file class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="") user = models.ForeignKey(User, on_delete=models.CASCADE) My serializers.py file class BlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(required=False, error_messages={'invalid': "Please upload Image, Video or Audio file"}) # user_id = serializers.SerializerMethodField('get_user_id') id = serializers.SerializerMethodField('get_id') date = serializers.SerializerMethodField('get_date') time = serializers.SerializerMethodField('get_time') class Meta: model = Blog # fields = ["id","title","author","description","image","date","time","user_id",] fields = ["id","title","author","description","image","date","time",] # Adding additional fields to a modelserializer using SerializerMethodField def get_user_id(self, user_id): user_id = self.context['request'].user.id return user_id def get_id(self, blog): id = blog.id return id def get_date(self, blog): date = blog.date return date def get_time(self, blog): time = blog.time return time My views.py file @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do … -
Pycopg2_binary is not installing in windows python 3.9
Am trying to install pycopg2_binary-2.9.1 on windows, currently am using python 3.9 and am getting this error: Error: psycopg2_binary-2.9.1-cp38-cp38-win_amd64.whl is not a supported wheel on this platform Can someone help me? -
How to use TrigramSimilarity in filtered Queryset?
I have three interconnected model: adresses/models.py: class Town(models.Model): name = models.CharField(max_length=200, db_index=True, unique=True) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('home:home_by_town', args=[self.slug]) class Street(models.Model): town = models.ForeignKey(Town, default=id(1), related_name='streets') name = models.CharField(max_length=200, db_index=True) def get_absolute_url(self): return reverse('home:home_by_town', args=[self.slug]) providers/models.py: class Provider(models.Model): location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers') name = models.CharField(max_length=200, db_index=True) I have implemented a search for providers that serve the streets: def search_results(request, town_slug=None): regions = Region.objects.filter(is_active=True) town = None towns = Town.objects.filter(is_active=True) streets = Street.objects.all() if town_slug: town = get_object_or_404(Town, slug=town_slug) streets = Street.objects.filter(town=town) streets_list = list(str(p.name) for p in streets) form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Provider.objects.prefetch_related('location').annotate( similarity=TrigramSimilarity('location__name', query), min=Min('tariffs__price'), ).filter(similarity__gt=0.87).distinct().order_by('-similarity') # tariffs__tariff_details__price return render(request, 'home/search_results.html', locals()) else: form = SearchForm() return render(request, 'home/search_results.html', locals()) This all works fine, because we are looking for objects in all street location__name records and I would be happy with the result, but I do not understand how to put my filtered list of streets by city in the TrigramSimilarity method streets = Street.objects.filter (town = town) I want my search result to work in this performance: results = Provider.objects.prefetch_related('location').annotate( similarity=TrigramSimilarity(streets, query), … -
Toggle Django field as read-only/editable in template
I have created a BooleanField for 'dhcp_client' in my models.py file. The functionality I am looking for is that when I click on the DHCP Client check box it allows me to render 'southbound_ip', and 'southbound_subnet' as an editable field or a read-only field while the user is viewing the template 'edit_network.html'. Thus far I have been unsuccessful in my attempts to link a jQuery function to a Django form field. All help is greatly appreciated. models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True) broadcast = models.BooleanField() channel = models.CharField(max_length = 3, choices = channel_ghz_choices, default = '2.4') channel_bonding = models.CharField(max_length = 3) channel_width = models.CharField(max_length = 4, choices = channel_width_choices, default = '20') transmit_power = models.CharField(max_length = 3) enable_wireless = models.BooleanField() wifi = models.CharField(max_length = 128) wifi_password = models.CharField(max_length = 128) paid_vpn = models.BooleanField() vpn_choice = models.CharField(max_length = 20, choices = vpn_choices, default = 'openvpn') vpn_location = models.CharField(max_length = 36) ip_address = models.CharField(max_length = 16) subnet_mask = models.CharField(max_length = 16) northbound_gateway = models.CharField(max_length = 16) dns_server = models.CharField(max_length = 16) dhcp_client = models.BooleanField() southbound_ip = models.CharField(max_length = 16) southbound_subnet = models.CharField(max_length = 16) ip_range = models.CharField(max_length = 16) range_subnet = models.CharField(max_length = 16) range_gateway = … -
Why does my django app fail to deploy to heroku while "building wheel for psycopg2"?
I am trying to deploy my django app and I'm following Corey Schafer's youtube tutorial. I am at around minute 16:00 and I'm running into an error which does not occur in the video. I have googled the specific error but couldn't figure out a solution that worked for me. When I "git push heroku master" in my project's directory, I get the following console output: Enumerating objects: 937, done. Counting objects: 100% (937/937), done. Delta compression using up to 4 threads Compressing objects: 100% (711/711), done. Writing objects: 100% (937/937), 400.51 KiB | 3.08 MiB/s, done. Total 937 (delta 620), reused 271 (delta 173) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Django==3.1.7 remote: Downloading Django-3.1.7-py3-none-any.whl (7.8 MB) remote: Collecting djangorestframework==3.12.4 remote: Downloading djangorestframework-3.12.4-py3-none-any.whl (957 kB) remote: Collecting boto3==1.9.96 remote: … -
Django loses value if choices is dynamic
I have a following problem. Let's say w have a model with column date defined like this: date = models.DateField(verbose_name="Fueling Date", choices=generate_dates()) Definition of generate_dates() functions is like this: def generate_dates(days_in_past=10): """ Generate list of dates from today to *days_in_past* days into past. Generated elements of the list are in format required by django models. Each element is 2-element tuple: (datetime.date, datetime.date) :param days_in_past: Int number of days into past. :return: List of tuples consist of two datetime.date elements. Len of generated list equals *days_in_past* + 1 (because of today's day). """ dates = pd.date_range( start=pd.Timestamp(datetime.datetime.today()).date() - pd.offsets.Day(days_in_past), end=pd.Timestamp(datetime.datetime.today()).date(), freq="D").tolist()[::-1] dates = [(x.date(), x.date()) for x in dates] return dates Function generate_dates returns list of last x dates (so its dynamic, every day it moves one day forward). I see in django admin, that if I have old insertion of this model (old means older than the latest date returned by generate_dates function), for values in column date there is no date displayed. In database it is stored, so there is no data leakage, but django displays for this "----" instead of real date. Once I change generate_dates to return list of dates that contains the old one (I extend … -
Django unique foreign key , on_delete keep the object
I am having some problems with the below code. Is there anyway to let the shitjet object exist after deleting the foreign key reference. from django.db import models from django.contrib.auth import get_user_model class from_thirty_five_to_fourty_one(models.Model): kodi = models.CharField(max_length=100, null=False, blank=False,unique=True) # kodi = models.CharField(max_length=100,null=False,blank=False,unique=True) ngjyra = models.CharField(max_length=100,blank=True,null=True) thirty_five = models.DecimalField(max_digits=200,decimal_places=0) thirty_six = models.DecimalField(max_digits=200,decimal_places=0) thirty_seven = models.DecimalField(max_digits=200,decimal_places=0) thirty_eight = models.DecimalField(max_digits=200,decimal_places=0) thirty_nine = models.DecimalField(max_digits=200,decimal_places=0) forty = models.DecimalField(max_digits=200,decimal_places=0) forty_one = models.DecimalField(max_digits=200,decimal_places=0) def __getitem__(self, key): return getattr(self, key) def __str__(self): return self.kodi class all_products(models.Model): kodi = models.ForeignKey(from_thirty_five_to_fourty_one,to_field='kodi',on_delete=models.CASCADE) choices = [ ("35_41", "35_41"), ('39_45', '39_45'), ] kategoria = models.CharField( max_length=10, choices=choices, blank=False, null=False) def __getitem__(self, key): return getattr(self, key) def __str__(self): return self.kodi def get_kodi(): return get_user_model().objects.get_or_create(kodi='deleted')[0] class shitjet(models.Model): kodi = models.ForeignKey(all_products,to_field='kodi',on_delete=models.SET_NULL ,null=True) numri = models.DecimalField(max_digits=100,decimal_places=0) cmimi = models.DecimalField(max_digits=100,decimal_places=0) created_at = models.DateTimeField(auto_now_add=True) class Meta: models.UniqueConstraint(fields=['kodi'],name='deleted') I have tried different on_delete options but nothing has worked so far. And no adding the unique=True didnt fix it either , keeps giving the same error. Below you can see the error i get. Any help or suggestion would be appreciated. django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: shoe_shop.shitjet.kodi: (fields.E311) 'all_products.kodi' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or … -
select with join using django models
I use django-rest-framework. I have models: class CategoryModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=64) class ProductModel(models.Model): id = models.IntegerField(primary_key=True) article = models.CharField(max_length=64, null=True) categories = models.ManyToManyField(CategoryModel) How i can select all products contained category = 596 and join category data (name)? Next wished SQL query: SELECT * FROM feed_productmodel JOIN feed_productmodel_categories ON feed_productmodel_categories.productmodel_id = feed_productmodel.id JOIN feed_categorymodel ON feed_categorymodel.id = feed_productmodel_categories.categorymodel_id WHERE feed_categorymodel.id = 596 -
Pagination data in vuejs by vue-pagination-2
I want to paginate data that comes from django api server. my problem is I don't know how to change api next page in vue-pagination-2 package. This html template: <tr v-for="(item, key) in users" :key="key"> <td>{{ item.username }}</td> </tr> <pagination v-model="page" :perPage="perPage" :records="count" @paginate="users"/> and my script section: export default { data() { return { page: 1, count: 0, perPage: 10, users: [], } }, methods: { fetchData() { Api.get(USERS).then((resp) => { this.count = resp.data.count; return this.users = resp.data.results; }).catch(() => { loginRedirect(this.$router) }); } }, mounted() { this.fetchData(); } } and response I got: count: 11 next: "http://192.168.1.10:8000/api/v1/users/?page=2" previous: null results: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} -
How to gracefully exit and remove docker-compose services after issuing CTRL-C?
I have a docker-compose service that runs django using gunicorn in an entrypoint shell script. When I issue CTRL-C after the docker-compose stack has been started, the web and nginx services do not gracefully exit and are not deleted. How do I configure the docker environment so that the services are removed when a CTRL-C is issued? I have tried using stop_signal: SIGINT but the result is the same. Any ideas? docker-compose log after CTRL-C issued ^CGracefully stopping... (press Ctrl+C again to force) Killing nginx ... done Killing web ... done docker containers after CTRL-C is issued CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4b2f7db95c90 nginx:alpine "/docker-entrypoint.…" 5 minutes ago Exited (137) 5 minutes ago nginx cdf3084a8382 myimage "./docker-entrypoint…" 5 minutes ago Exited (137) 5 minutes ago web Dockerfile # # Use poetry to build wheel and install dependencies into a virtual environment. # This will store the dependencies during compile docker stage. # In run stage copy the virtual environment to the final image. This will reduce the # image size. # # Install poetry using pip, to allow version pinning. Use --ignore-installed to avoid # dependency conflicts with poetry. # # --------------------------------------------------------------------------------------- ## # base: Configure python … -
django not switching to Postres when deploying to Heroku
I deployed my django app with Heroku and I am having troubles with connecting to Postgres. If I run python manage.py createsuperuser after running heroku ps:exec --app produceit (so I am inside the Heroku instance's terminal), it says that I successfully created a superuser but nothing is written into Heroku Postgress DB...so I can't login into neither /admin nor my app. I therefore run heroku ps:exec --app produceit python manage.py shell from mywebsite.settings import DATABASES and it seems like the settings.py has the variable DATABASE still connected to sqlite (see pic) Funny enough, if I hardcode an admin into Heroku's Postgres DB, loging and then create an instance of one of my models from the app itself (like I create a blog's post)...it actually writes into Postgres and I see it on the Front End. So basically it's like the app is working on Postgress BUT the terminal is running on SQLite. What can I do? My settings are below """ Django settings for mywebsite project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # … -
Django RF and Gunicorn - extrange behavior in response time
SETUP: Azure cloud Virtual M. nº1: (Debian 8 cores) Docker with application (API) Django Rest with Gunicorn (17 sync workers) Virtual M nº2: (Debian 4 cores) DB MySQL Note: The APi receives a user call from a user, makes 4 django ORM queries to MySQL (Only selects) and returns OK or error. We are launching 220 requests per second from an Apache JMeter for an unlimited time. These calls are 100% successful and take an average of 1200 ms, We control the workload of the 8 CPUs and they work at + -50% Until here everything is perfect, according to our requirements. Trouble: After an X Time and suddenly, the response time almost triples reaching 4000 ms on average. and the CPUs go to 100% (htop showing half of each bar red) (Calls are still 100% successful) Our analysis after hundreds of structured tests: Time X usually depends on the time that has elapsed since the last time it failed(triplication of time), normally it is half that time. Example 1: If at this moment it is failing (that is, it takes 4000 ms) and I stop the test for 2 minutes, the test starts well and fails again after a … -
django drf variations for products ecommerce
i am building an eCommerce Website, and i stuck on productvariations. and i need help. serializers.py """ def get_variations(self, obj): data = [] bar = Barcode.objects.select_related('product').filter(product_id=obj.pk) for b in bar.iterator(): main_variation = b.product_variation.first() rest_variations = b.product_variation.exclude(pk=main_variation.pk) dic = {main_variation.headline:[{i.headline:{"code":i.barcode_set.first().code}} for i in rest_variations]} data.append(dic) return data """ i get data like this: all i want to do is for green create variation with code: janika128green and for 5inch code:janika1285inch and for both code: janika128green5inch is there any way to do it? -
Django session. sum with conditions return 0
this is a data: product1:{ 'quantity': 1, 'regular_price': Decimal('1200.00'), 'shipping_cost': '300.00', 'shop': 'ca097a5b-4ca6-420a-955a-71a417afed5a', } product2:{ 'quantity': 2, 'regular_price': Decimal('200.00'), 'shipping_cost': '300.00', 'shop': 'ca097a5b-4ca6-420a-955a-71a417afed5a', } product3:{ 'quantity': 1, 'regular_price': Decimal('550.00'), 'shipping_cost': '300.00', 'shop': 'ca097c5b-4ba6-520a-955a-71a417afse2b', } this is a function: def get_shipping_price(self): return sum(Decimal(item['shipping_cost']) for item in self.cart.values() if item['shop'] not in item.values()) I want to sum the shipping price of the product, only if the shop does not exist in the cart, if instead there is already a product of this shop, consider it 0 -
Is the server running on host "localhost" (127.0.0.1) - Reposting
Please do not close my question again if you are not sure that the answer provide to others fit my case. I am deploying a django app for the first time to Heroku. I used the following: heroku run python manage.py migrate and it returns : Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? In my settings.py i have : DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } and at the bottom : try: from .local_settings import * except ImportError: pass in the local_settings.py I have : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newapp_development', 'USER': 'postgres', 'PASSWORD': '#####', 'HOST': 'localhost', 'PORT': '5432', } } Do you know why is the error message please ? Also, note that local_settings is added to . gitignore. I did a few search on search engine and the responses that i found did not work for me … -
how to display error message in django formset with ajax
i'm trying to submitting django formset using ajax call , but the problem is i cant iterate the error fields and give each error to its form and field ! class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) full_name = models.CharField(max_length=150) dob = models.DateField(max_length=14) city = models.ForeignKey(City,on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information') ] and also i've used ModelForm class VistorForm(forms.ModelForm): city = forms.ModelChoiceField( queryset=City.objects.all()) class Meta: model = Vistor fields = [ 'full_name','dob','city' ] VistorFormSet = modelformset_factory(Vistor,form=VistorForm,extra=1,can_delete=True) non_fields_error defined as __all__ in ajax call error messages @login_required def add_vistor(request): formset = VistorFormSet(queryset=Vistor.objects.none()) if request.is_ajax() and request.method == 'POST': formset = VistorFormSet(request.POST) if formset.is_valid(): for form in formset: obj = form.save(commit=False) if form.cleaned_data !={}: obj.admin = request.user obj.save() formset = VistorFormSet(queryset=City.objects.none()) return JsonResponse({'success':'success'}) else: return JsonResponse({'success':False,'error_msg':formset.errors,'error_code':'invalid'}) return render(request,'vistors/add_vistor.html',{'formset':formset}) my html + js //for adding new form $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#form').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); //ajax submit form const form = document.getElementById('post-form') form.addEventListener("submit",submitHandler); function submitHandler(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url 'vistors:add_vistor' %}', data : $('#post-form').serialize(), dataType: 'json', success: successFunction, }); } function successFunction(data) { console.log(data.success=='success') if (data.success=='success') { alertify.success("added") form.reset(); } else if(data.error_code=='invalid'){ console.log(data.error_msg.length) for(var i=0; i < data.error_msg.length;i++){ console.log(data.error_msg) if(key == 'full_name'){ document.getElementById('full_name_error').removeAttribute('hidden') document.getElementById('full_name_error').innerHTML = data.error_msg[key][0] } … -
How to use binding in Django Raw SQL
How can I use a single variable to binding in more than one filter in Django SQL? What I want: I defined the variable: date I want to use the same information in the SQL WHERE Clausures: CUR_DATE, ACHIEVED_DATE def kpiMonitoring(self): with connections['db'].cursor()as cursor: import time date = time.strftime('%Y%m%d') cursor.execute(""" SELECT * FROM TABLE1 WHERE CUR_DATE = date AND ACHIEVED_DATE = date """,[date]) row = dictfetchall(cursor) cursor.close() return row I can do it by this way, but this solution is not scalable: def kpiMonitoring(self): with connections['db'].cursor()as cursor: import time date = time.strftime('%Y%m%d') date2 = date cursor.execute(""" SELECT * FROM TABLE1 WHERE CUR_DATE = %s AND ACHIEVED_DATE = %s """,[date, date2]) row = dictfetchall(cursor) cursor.close() return row Is there another way to do it? -
wsgi directory in gunicorn service file not recognised
I want some help to fix this issue. myproject.wsgi in gunicorn is not recognised. Content of gunicorn file is: -
How i put empty file in database using django rest framework
Hi everyone my filefield posted successfully and successfully save in database but i want to put my filefield empty in database. How i can do this in Django Rest framework. My models.py file: This my model file class Blog(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length = 50) author = models.TextField(max_length = 50) description = models.TextField() date = models.DateField(auto_now=True) time = models.TimeField(default=timezone.now) image = models.FileField(null=True, verbose_name="", validators=[validate_allfile_extension]) # time = models.DateTimeField(default=datetime.now) # image = models.ImageField(null=True, verbose_name="", validators=[validate_allfile_extension]) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title MY serializers.py file: THis is my serializers file include with model Blog class UpdateBlogSerializer(serializers.ModelSerializer): title = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide title"} ) author = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide author"}) description = serializers.CharField(max_length=128, required=True, error_messages={'blank': "Please provide description"}) image = serializers.FileField(required=False) # user_id = serializers.SerializerMethodField('get_user_id') id = serializers.SerializerMethodField('get_id') date = serializers.SerializerMethodField('get_date') time = serializers.SerializerMethodField('get_time') class Meta: model = Blog # fields = ["id","title","author","description","image","date","time","user_id",] fields = ["id","title","author","description","image","date","time",] # Adding additional fields to a modelserializer using SerializerMethodField def get_user_id(self, user_id): user_id = self.context['request'].user.id return user_id def get_id(self, blog): id = blog.id return id def get_date(self, blog): date = blog.date return date def get_time(self, blog): time = blog.time return time My views.py file: THis is my views file … -
Page not found (404) Request Method
i have created 2 apps under tubers, tubers is my project , my apps are travello and register, i have index.html file in travello where when user click it need to navigate to register form but unforunately i getting path error, i tried my to fix but i'm unable to understand it please help me out :) note: when i'm trying to go to register page through my html it is throwing me error but when i try it directly with /register it is showing me the form , i don't understand how to fix it :( -
After successful login , dashboard gives error user is null (cannot read property of null) , when I refresh the page it fetches the user information
Project is based on React-Django . I am new to react and I created login functionality and fetch user details functionality using react-redux, Here is the code for login here is the constant file export const USER_LOGIN_REQUEST = 'USER_LOGIN_REQUEST' export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS' export const USER_LOGIN_FAIL = 'USER_LOGIN_FAIL' export const USER_LOGOUT = 'USER_LOGOUT' Here is the reducer file import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; export const userLoginReducer = (state = {}, action) => { switch(action.type){ case USER_LOGIN_REQUEST: return {loading:true} case USER_LOGIN_SUCCESS: return {loading:false, userInfo: action.payload} case USER_LOGIN_FAIL: return {loading:false, error: action.payload} case USER_LOGOUT: return {} default: return state } } Here is user action file import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT, } from "../constants/userConstants"; import axios from 'axios' export const login = (username, password) => async (dispatch) => { try{ dispatch({ type:USER_LOGIN_REQUEST }) const config = { headers : { 'Content-type':'application/json' } } const { data } = await axios.post( '/api/user/login/', {'username':username, 'password':password}, config ) dispatch({ type :USER_LOGIN_SUCCESS, payload: data }) localStorage.setItem('userInfo', JSON.stringify(data)) }catch(error){ dispatch({ type : USER_LOGIN_FAIL, payload : error.response && error.response.data.detail? error.response.data.detail: error.message, }) } } export const logout = () => (dispatch) => { localStorage.removeItem('userInfo') dispatch({type:USER_LOGOUT}) } now the login interface import React, …