Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
lambda self in function
i was going through a github project to get the current request user in django projects and i saw this codes and i didn't understand use of lambda in this code . Somebody please explain this . def _do_set_current_user(user_fun): setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user_fun, local)) class ThreadLocalUserMiddleware(object): .......... ................ _do_set_current_user(lambda self: getattr(request, 'user', None)) def get_current_user(): current_user = getattr(_thread_locals, USER_ATTR_NAME, None) if callable(current_user): return current_user() return current_user here i couldn't understand what is the use of user_fun.__get__(user_fun, local) in this line setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user_fun, local)). instead we can set the attr like this instead setattr(_thread_locals, USER_ATTR_NAME, user) here why its using lamda function why we cannot set the user object instead. somebody please explain -
How to check negative values on text box in angular 6 using form control
component.ts `this.companySettingsForm = this.formBuilder.group({ 'delivary_charge': ['', Validators.compose([Validators.required, ])], }); this.delivary_charge = this.companySettingsForm.controls['delivary_charge']; }` In Component.html i added min and max values, but it won't work component.html `<input pInputText #value type="number" [formControl]="surcharge" min="1" max="9999999999999" class="input-width">` -
create value to a model from another model's method
https://imgur.com/a/wVG5qrd Im trying to create a new table (Payslip model) that will contain the computed salary on an employee in a cutoff. I want Payslip.salary to get value from Employee.compute_pay() Given the example in the url link above, what should my views . py look like? Is this the best approach to this kind of process? or is there any library that can help with what i want to do here? -
How to filter generic foriegn key using django tasty pie? how to use generic relation using django tasty pie?
**Django tasty pie filter using generic foreign key ** class AResource(ModelResource): user = GenericForeignKeyField({ get_user_model():UserResource, ServiceUser : ServiceUserResource, }, "user") class Meta: filtering={"user": ALL_WITH_RELATIONS,} -
python 3 - requests, django-rest - simple get with token auth fails using module but works using curl
I have setup Django rest api with token authentication. When I curl the api using a token it works, but using the python requests module it gives me a connection refused error. The error suggests to me its not sending the token however I cannot see an issue the code and any examples I find all suggest that its correct. Is there something else in missing? curl statement: curl -X GET http://127.0.0.1:8100/api/inventory/ -H 'Authorization: Token ab5a......67273c850' [{"data":... python code: import requests, json token = 'ab5a......67273c850' headers = {'Authorization': 'Token {}'.format(token)} url = 'http://127.0.0.1:8100/api/inventory/' req = requests.get(url, headers=headers) error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 75, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python3.6/site-packages/requests/api.py", line 60, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 533, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.6/site-packages/requests/sessions.py", line 646, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.6/site-packages/requests/adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8100): Max retries exceeded with url: /api/inventory/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbe549ec320>: Failed to establish a new connection: [Errno 111] Connection refused',)) -
Disabling a Django ModelForm Field without explicit declaration
I have this code: class MyModel(models.Model): input_field = model.CharField(max_length=100) class MyModelForm(forms.ModelForm): input_field = forms.CharField(disabled=True) class Meta: model = MyModel I've also ready from the docs: When you explicitly instantiate a form field like this, it is important to understand how ModelForm and regular Form are related. ... Fields defined declaratively are left as-is, therefore any customizations made to Meta attributes such as widgets, labels, help_texts, or error_messages are ignored; these only apply to fields that are generated automatically. Similarly, fields defined declaratively do not draw their attributes like max_length or required from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field. Is it possible to pass kwargs to the Form Field in a way that lets me specify disabled=True without losing the benefits of the ModelForms introspection and customisation? Essential, can I have my cake and eat it? I'm aware that I can work around this by using widgets = {'input_field': widgets.TextInput(attrs={'readonly':'readonly'})} in the Meta class, but I'm interested if there's a better way available It's also not clear whether modifying the widgets attribute as above will "inherit" the default configuration that the … -
List all the values stored in another model in Django Admin
I have a small project that I need to create a system to record what a person has done each day during several time slots (e.g., "8:00-9:00", "10:00-11:00", "13:00-14:00"). I implemented the project in Django and use Django Admin to present the system. I created three models tmpDate, tmpHour, tmpDateHour in models.py. from datetime import datetime from datetime import date as datetimeDate class tmpDate(models.Model): date=models.DateField(default=datetime.now, blank=True) total_tmp_time=models.DecimalField(max_digits=10,decimal_places=1,default=0.0) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def __str__(self): return self.date class tmpHour(models.Model): start_time=models.TimeField() end_time=models.TimeField() create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def __str__(self): return str(self.create_time)+"-"+str(self.update_time) class tmpDateHour(models.Model): date=models.ForeignKey(tmpDate,on_delete=models.CASCADE) hour_time=models.ForeignKey(tmpHour,on_delete=models.CASCADE) tmp_length=models.DecimalField(max_digits=10,decimal_places=1,default=0.0) comment=models.CharField(max_length=200,null=True) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) The idea is that I create some timeslots in tmpHour (e.g., "8:00-9:00", "10:00-11:00", "13:00-14:00"). Once I create a new Date in the Admin of tmpDate, then all the time slots stored in tmpHour will populate the respective fields. Something like this However, I do not know how to do the setup in admin, I have the following setup in admin.py currently, class tmpDateHourInline(admin.TabularInline): model = tmpDateHour extra = 1 class tmpHourAdmin(admin.ModelAdmin): pass class tmpDateAdmin(admin.ModelAdmin): inlines=[tmpDateHourInline] admin.site.register(tmpDate,tmpDateAdmin) admin.site.register(tmpHour,tmpHourAdmin) Which gives me the following result. It requires me to manually select the time slots. How can I modify admin.py … -
Why can I not use the Django server for production?
I'm learning Django for the first time and I'm also relatively new to Python. On the Django documentation, it says, "You’ve started the Django development server, a lightweight Web server written purely in Python. [...] don’t use this server in anything resembling a production environment. It’s intended only for use while developing." Why shouldn't I use the Django server for production? Why do I need a separate server? I'm from a Node/Express background, and when I created an Express application, I could just deploy it to Heroku without doing too much. How will this be different for Django? -
request additional fields from related object in django queryset
say I've got two models, Parent and Child. Child model has a fk relation to Parent Class Child(models.Model): parent = models.ForeignKey('Parent', related_name='family') I want to write a queryset for Child and serialize it to geojson, however, I'd also like the queryset to include some additional fields from Parent beyond id. perhaps I'm not clear on select_related(). This offers functionally the same query with no additional fields from Parent: qs = Child.objects.filter(...).select_related('parent') props = { 'geoJson' : serializers.serialize('geojson', list(qs)), } if I make it .select_related('parent').values(...) for the fields I want, the view errs on req: 'dict' object has no attribute '_meta' .select_related('parent').only(...) throws: Field Child.parent cannot be both deferred and traversed using select_related at the same time what's the right way to structure that queryset to request extra fields from the related object? what am I misunderstanding about selected_related in queries? thanks .values() Traceback: File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/channels/handler.py" in process_exception_by_middleware 237. return super(AsgiHandler, self).process_exception_by_middleware(exception, request) File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File ".pyenv/versions/3.6.3/lib/python3.6/contextlib.py" in inner 52. return func(*args, **kwds) File "project/utils/helpers.py" in _decorated 29. … -
django.db.utils.IntegrityError: duplicate key value violates unique constraint
I have Country model from django.db import models class Country(models.Model): country = models.CharField(max_length = 20, primary_key=True) country_id = models.IntegerField() I uploaded some data in Country table for doing it i created custom management command from django.core.management.base import BaseCommand, CommandError from data.models import Country import json from .extract_country import extracting get_parsed_json = extracting() def store_data(): for key, value in get_parsed_json['api']['countries'].items(): country_id_field = key country_name = value One_country = Country.objects.create(country_id = country_id_field , country = country_name) One_country.save() print(One_country) class Command(BaseCommand): def handle(self, **options): extracting() store_data() Now i am trying to upload to the Country table extended data which contain the same countries and another but when i am trying to upload data i get the following error. Here is my full traceback Traceback (most recent call last): File "D:\Python\my_projects\forecast\lib\site-packages\django\db\backends\util s.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "data_co untry_name_04df4fc7_uniq" DETAIL: Key (country)=(Algeria) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\ __init__.py", line 381, in execute_from_command_line utility.execute() File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\ __init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\ base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\ base.py", … -
Dynamic buttons that filter objects Django
I want to ask is it possible to create buttons that will dynamic filter objects in Django? I will explain it on example Lets say we got object Company, this object got some fields like company_type (software house, corporation, e-commerce) and I would like to create buttons that would list these companies that user select (ex. user pressed button "Software house" and he receiving companies that their type equals = software house) I'm not asking for solution but how to do it? I've checked django's docs, google, stack over flow but I couldn't find the answear My files models.py from django.db import models from django.utils import timezone from django.core.validators import MinValueValidator from multiselectfield import MultiSelectField class company(models.Model): company_name = models.CharField(max_length=100, blank=False) COMPANY_TYPES = ( ('star', 'Startup'), ('sh', 'Software House'), ('ecom', 'E-commerce'), ('corp', 'Corporation'), ) company_types = models.CharField(max_length=4, choices=COMPANY_TYPES) company_workers = models.PositiveIntegerField(validators=[MinValueValidator(1)]) company_headquarters = models.CharField(max_length=100, blank=False) COMPANY_TECHNOLOGIES = ( ('php', 'PHP'), ('js', 'JavaScript'), ('ang', 'Angular'), ('java', 'Java'), ('ruby', 'Ruby'), ('ror', 'Ruby on Rails'), ('jee', 'Java EE'), ('python', 'Python'), ('django' , 'Django'), ) company_technologies = MultiSelectField(max_length=25, choices=COMPANY_TECHNOLOGIES, min_choices=1) company_about = models.TextField(max_length=500, blank=False) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.company_name views.py … -
two views in one page django
I am new on django and got a problem. I got 2 apps, one is slider which i get slider images and other one is products. I've featured product option in my product model which i want to show on index page. This is my views.py def index(request): allslides = SliderImage.objects.all() context = { 'allslides': allslides } return render(request, 'pages/index.html', context) def fproducts(request): fproducts = Product.objects.filter(is_featured=True) context = { 'fproducts': fproducts } return render(request, 'pages/index.html', context) I've made some research and it looks django doesn't allow 2 views in one page. That's my index.html <div id="homepageslider" class="flexslider"> <ul class="slides"> {% for s in allslides %} <li class=""><img src="{{ s.image.url }}" title="{{ s.alt }}"></li> {% endfor %} </ul> </div> <div class="container"> {% if fproducts %} {% for product in fproducts %} <div class="col-md-4 col-lg-3 col-sm-6 col-12 mb-4 px-1"> <div class="card"> <a href="{% url 'productdetail' product.id %}"><img src="{{ product.main_image.url }}" class="card-img-top" alt="..."></a> <div class="card-body"> <a href="{% url 'productdetail' product.id %}"><h5 class="card-title text-truncate">{{ product.title }}</h5></a> <a href="{% url 'productdetail' product.id %}"><p class="card-text">{{ product.kod }}</p></a> </div> </div> </div> {% endfor %} {% else %} <p>No Products</p> {% endif %} Thanks for help. -
Qualtrics- issue on API
The Qualtrics access token can be accessed from the account settings, but I can't, because it asks to upgrade my account and I don't want to do that because it is for a test purpose.I referred some websites and come up with a API url to get the access token.But it requires client ID and client secret. I couldn't find them in my account.If any one can help me where can I find them or giving another way to get the access token and API call url , it would be helpful. -
Icons in the template are not displayed - Bootstrap 4, Django (after adding amazon s3)
After adding all static files to amazon S3 my icons are not displayed (as in the picture below). I use the purchased Frond Endu Bootstrap4 and personally i did not add changes inside static files. Why my django application does not display icons? Any help will be appreciated. -
How to get MongoDB connection object in Django?
I want to get the MongoDB connection object just like we get mysql object from from django.db import connection How can we do that in Django so that i can perform raw queries ? I know we can do this with pymongo but i will be good if i can do that with django itself. -
Should I use a task queue (Celery), ayncio or neither for an API that polls other APIs
I have written an API with Django which purpose is to operate as a bridge between a website back-end and external services we use, so that the website doesn't have to handle many requests to external APIs (CRM, calendar events, email providers etc.). The API mainly polls other services, parses the results and forwards them to the website backend. I initially went for a Celery-based task queue, as it seemed to me like the right tool to offload that processing to another instance, but I'm starting to think it doesn't really fit the purpose. As the website expects synchronous responses, my code contains a lot of : results = my_task.delay().get() or results = chain(fetch_results.s(), parse_results.s()).delay().get() Which doesn't feel like the proper way to use Celery tasks. It is efficient when pulling dozens of requests and processing the results in parallel - a periodic refresh task for example - but adds a lot of overhead for simple requests (fetch - parse - forward), which represent most of the traffic. Should I go full synchronous for those "simple requests" and keep Celery tasks for specific scenarios ? Is there an alternative design (maybe involving asyncio) that would better suit the purpose of … -
How to filter django model based on other non related model
Please refer to the code below Transaction models class Transaction(models.Model) current_product_code = models.CharField(....) previous_product_code = models.CharField(....) @property def status(self): c_price = Product.objects.get(code=self.current_product_code).price p_price = Product.objects.get(code=self.previous_product_code).price if c_price == p_price: return "Due" elif c_price > p_price: return "Upgrade" else: return "Downgrade" Product model class Product(models.Model): code = models.CharField(....) price = models.DecimalField(....) My question: How can i obtain/filter transactions with upgrade/downgrade/due status. I am trying to create a custom admin filter which filter transaction based on their status but i fail what to put inside .filter() this method def queryset(self, request, queryset): value = self.value() if value == 'Upgrade': return queryset.filter(***** HERE *****) elif value == 'Downgrade': return queryset.filter(***** HERE *****) elif value == 'Unknown': return queryset.filter(***** HERE *****) return queryset -
Upload files from a website to social platform automatically
is there a way to upload files from website to social platform (facebook,twitter,reddit) etc i am making website using python django as backend anything will be helpfull it have to automatically like after certain time etc -
FK from model to external FK from another model in Django
I have model "Cities" in "external_app" app like this: class Cities(models.Model): CityName = models.CharField(max_length=50, blank=False, db_index=True) slug = models.SlugField(max_length=50, db_index=True, unique=True) I have second app, "Address_program" with few models: class CityRegions(models.Model): city = models.ForeignKey('external_app.Cities', default=0, verbose_name=' City', related_name='City_for_region') city_region = models.CharField(max_length=200, blank=False, default='', verbose_name='City region', unique=True) city_region_slug = models.SlugField(verbose_name='City region slug') and second model for sub-regions in region. Now I want to publish used cities in CityRegions model. I try to add FK for city field class RegionSquares(models.Model): city = models.ForeignKey(CityRegions, default=0, verbose_name='City', related_name='City_for_regionsquare', to_field='city') region = models.ForeignKey(CityRegions, default=0, verbose_name='City region',related_name='Region') region_square = models.CharField(max_length=200, blank=False, default='', verbose_name='City sub-region') region_square_slug = models.SlugField(verbose_name='City sub-region slug') when I try to make migrations I get error with message "(fields.E311) 'CityRegions.city' must set unique=True because it is referenced by a foreign key". When I set unique=True in CityRegions.City field and try to migrate I get error with message: "django.db.utils.IntegrityError: UNIQUE constraint failed..." Question is how to publish list of used in CityRegions model cities in RegionSquares model? I using Django 1.11 and python 2.7.10 -
When I try to write something in Django urls.py file, it doesn't show this in the browser
#code in urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name= 'index'), path('about/', views.about, name ='about'), ] #code in views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello") def about(request): return HttpResponse("about harry") Body I am doing this while watching a tutorial, and the same thing is working for him. Moreover, if mistakenly I write the wrong code and run, cmd shows the errors and on reloading the browser the server doesn't work more. Then I need to restart CMD and again run manage.py. Please tell me the reason and also the solution, Thanks. -
Unable to encode nepali words while generating pdf using xhtml2pdf library in django
I'm able to generate pdf using html2pdf library in django but unable to encode nepali words correctly as well as unable to display images in pdf.The pdf generated looks likeenter image description here , but i want pdf like enter image description here Any suggestions? views.py class GeneratePDF(LoginRequiredMixin, View): def get(self, request,regid, *args, **kwargs): template = get_template('invoice1.html') context = {} context['municipality'] = config.Municipality context['registrationid'] = regid reg = NewRegistration.objects.get(id=regid) context['registration'] = reg context['application_status'] = reg.applicationstatus_set.all() context['application'] = get_related_object_or_none(reg.application_set) context['houseowner'] = reg.houseownerinfo_set.all() houseowner_names = ", ".join(reg.getAllHouseownerNpNameAsList()) if houseowner_names == "": context['houseowner_name'] = u"{} ({})".format(reg.houseowner_name_np, reg.houseowner_name_en) else: context['houseowner_name'] = houseowner_names context['landowner'] = reg.landowner_set.all() context['applicant'] = get_related_object_or_none(reg.applicant_set) context['landinformation'] = get_related_object_or_none(reg.landinformation_set) charkillas = reg.charkilla_set.all() for ch in charkillas: if ch.ch_direction == "n": context['charkilla_n'] = ch elif ch.ch_direction == "e": context['charkilla_e'] = ch elif ch.ch_direction == "s": context['charkilla_s'] = ch elif ch.ch_direction == "w": context['charkilla_w'] = ch else: context['charkilla_other'] = ch context['designer'] = get_related_object_or_none(reg.designer_set) context['supervisors'] = reg.supervisor_set.all() context['contractors'] = reg.contractor_set.all() docs = reg.getAllDocs() context['docs'] = docs shuffle(docs) try: context['parallax_image'] = docs[0].attached_file.url except IndexError: context['parallax_image'] = '/media/appimg/upload_image.png' context['tech'] = get_related_object_or_none(reg.technicalregistration_set) context['far'] = get_related_object_or_none(reg.floorinformation_set) context['bylaws'] = reg.bylawsinformation_set.select_related("question").all() context['structural_datas'] = reg.structuralinformation_set.all() context['architectural_datas'] = reg.architecturalinformation_set.all() context['electrical_datas'] = reg.electricalinformation_set.all() context['san_and_plumb_datas'] = reg.sanitationandplumbinginformation_set.all() context['date_plinth'] = reg.getCertAttr('plinth', 'date_np') context['date_superstructure'] = reg.getCertAttr('superstructure', 'date_np') … -
The user is none and getting logged in django
I am creating a creating a signup and login where i am signing up and saving the credentials in the database and logging with the same credentials. Eventhough it is printing the username and password while authenticating it is saying user as none. Views.py -------- def Login(request): form = login_form(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password1") print (username,password) user = authenticate(request,username=username, password=password) print('user is', user) if user is not None and user.is_active: print ('entered loop') login(request,user) return redirect('/home/') else: print ("username and password are incorrect ") else: form = login_form() return render(request, 'Login.html', {'form': form}) settings.py: --------------- AUTHENTICATION_BACKENDS = ("django.contrib.auth.backends.ModelBackend", 'django.contrib.auth.backends.RemoteUserBackend',) AUTH_USER_MODEL = 'auth.User' urls.py: --------- urlpatterns = [ url('admin/', admin.site.urls), url('Provisioning/', include('django.contrib.auth.urls')), url(r'^signup/', views.signup,name='signup'), url(r'^Login/', views.Login,name='Login'), url(r'^Logout/', views.Logout,name='Logout'), models.py: ----------- class MyUserManager(BaseUserManager): def create_user(self, fname,lname,username, password): """ Creates and saves a User with the given username, date of birth and password. """ if not username: raise ValueError('Users must have an username') user = self.model(username=username,fname=fname,lname=lname) user.set_password(password) user.is_active = True user.save(using=self._db) print (user) return user def create_superuser(self, fname,lname,username, password,email=None): """ Creates and saves a superuser with the given username and password. """ user = self.create_user( fname=fname, lname=lname, username=username, password=password, ) user.is_admin = True user.is_superuser = True user.save(using=self._db) … -
How to access django python data in javascript
I wants to access the "pizzamenu.price" from "context:'pizzamenu': pizza," in javascript to change the price according to the selected size of pizza. But im new to django and i dont know how to access it in js. enter image description here -
Django - query aggregation by date and avg value
I have an app where a Gym is associated to many Tablets. A Tablet is associated to many Surveys (many-to-many), and a Survey has many Answers. An Answer has a numeric value, and it is associated with the Survey, a Gym and a Tablet. models.py class DateTimeModel(models.Model): creation_date = models.DateTimeField(verbose_name=_('Creation Date'), auto_now_add=True, db_index=True) edit_date = models.DateTimeField(verbose_name=_('Last Edit Date'), auto_now=True, db_index=True) ... class Gym(DateTimeModel): name = models.CharField(max_length=250) ... class Survey(DateTimeModel): text = models.CharField(max_length=500) valid_from = models.DateTimeField() valid_to = models.DateTimeField() gyms = models.ManyToManyField(Gym) ... class Answer(DateTimeModel): value = models.IntegerField() survey = models.ForeignKey(Survey, on_delete=models.CASCADE) gym = models.ForeignKey(Gym, on_delete=models.PROTECT) tablet = models.ForeignKey(Tablet, on_delete=models.SET_NULL, blank=True, null=True) ... I need to get the votes distribution by day for a specific gym. This is easily accomplished by: views.py class VotesDistributionByDayViewSet(APIView): @staticmethod def get(request, gym_id, survey_id): votes_by_date = Answer.objects.filter(gym_id=gym_id, survey_id=survey_id)\ .annotate(day=TruncDay('creation_date'))\ .values("day")\ .annotate(count=Count('gym_id'))\ .order_by('day') I also need to return the average value of all the answers of all the gyms by day. I tried the following query, which returns wrong results: avg_votes_by_date = Answer.objects.filter(~Q(gym_id=8), survey_id=survey_id)\ .annotate(day=TruncDay('creation_date'))\ .values("day")\ .annotate(avg=Avg('value'))\ .order_by('day') (note that I exclude gym with ID=8 for some reason, I don't think it's relevant) What am I doing wrong? -
Hey guys I wanna make a page where people can download stuff?
Hey guys I was making a page where people can download my stuff.I made a model of thta and It is succesfull in uploading that but the problem i swhen I click on the download button front end I t doesn,t download that stuff .Instead of that it downloads the copy of the page. Here,s the models.py class Upload(models.Model): image = models.ImageField(upload_to = 'images',) file = models.FileField(upload_to = 'images/%Y/%M/%d/') name = models.CharField(max_length = 200) def __str__(self): return self.name Here,s the views.py def upload(request): upload = Upload() return render(request,'app/download.html',{'upload':upload}) Here,s the html file {% block content %} <div class="container"> <div class="download"> <p style="text-align: center;"> <img src="{{upload.image}}" alt="Image containing link to you,r success"> </p> </div> <h2>Click on the button below</h2> <button class="btn btn-primary"><a href="{{upload.file.id}}" download>Yeah do it</a></button> </div> {% endblock %}