Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am getting error Uncaught TypeError: Cannot read property 'innerHTML' of nul in javascript [duplicate]
index:601 Uncaught TypeError: Cannot read property 'innerHTML' of null at updatePopover (index:601) at index:593 enter image description here -
how to post a model with a foreignkey using django rest framework with only one field?
I'm working on an API, django rest framework for the backend and react on the frontend. i only want to create a model and pass the foreignkey as a dropdown like in django rest framework but with reactjs i have many models the ones without foreignkeys are esly manipulated but i have some models with foreignkeys that i can get but can't POST even with postman i get: "name": [ "This field is required." ] i have seen many posts that has same issues but didn't understant gow to implement it here is a simple model with a foreign key models.py class SalleSport(models.Model): name = models.CharField( max_length=50) adresse = models.CharField( max_length=50) class Planning(models.Model): name = models.CharField(max_length=50) salle_sport = models.ForeignKey(SalleSport, verbose_name="Salle de sport", on_delete= models.CASCADE, null=True, blank=True) serializers.py class SalleSportSerialiser(serializers.ModelSerializer): class Meta: model = SalleSport fields= '__all__' as i want to create a Planning instance i tried many solution that didn't worked i'm gona put them as comments class PlanningSerialiser(serializers.ModelSerializer): # salle_sport = SalleSportSerialiser(read_only=False) class Meta: model = Planning fields= '__all__' # fields= ('id', 'name', 'salle_sport') # def create(self, validated_data): # salle_sport = validated_data.pop('salle_sport', None) # if author_data: # salle_sport = SalleSport.objects.get_or_create(**salle_sport)[0] # print('salle de sport',salle_sport) # validated_data['salle_sport'] = salle_sport # … -
Django models dependencies and transfer ownership
What I am trying to build is a app that can deal with honey production management. There are number of producers that produce honey pots and they can give their pots to a variety of stores that have their customers. One producer can give his production to many stores, and a store can have honey pots from many producers. Honey pots can be tracked by pot_id. The models.py looks like this: class Produser(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) class Store(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) produser= models.ManyToManyField(Produser) class Customer(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) store = = models.ForeignKey(Store, on_delete=models.CASCADE) class HoneyPot(models.Model): produced_date = models.DateField(auto_now=False) pot_id = models.CharField(max_length=25, blank=False) produser= models.ForeignKey(Produser, on_delete=models.CASCADE) store= models.ForeignKey(Store, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) I'm struggling to find how to modify the models in the way that one pot to be owned or by producer or a shop or a customer. As right now when a new pot is created store and customers are required fields. -
Multiple checkbox filtering javascript and Django
I am trying to use check boxes in order to filter my results at an html page. Through a django view a pass my data in a list, and then through a loop like this: </div> {% for r in rows %} <div class="res_show"> <div class="btitle"> <a href="/show_business/{{r.b_id}}/"><p style="text-align:left"><b>{{r.name}}</b></p></a> </div> <div class="baddress"> <p>{{r.address}}</p> </div> <div class="reviewstar"> {% if user.is_authenticated %} <a href="/apply_review/{{r.b_id}}/"><p style="text-align:left"><span class="fa fa-star checked"></span> {{r.stars}} ({{r.r_count}})</p></a> {% else %} <p style="text-align:left"><span class="fa fa-star checked"></span> {{r.stars}} ({{r.r_count}})</p> {% endif %} </div> <div class="b_category"> <p style="text-align: left"> <b>{{r.category}}</b></p> </div> <div class="diraddress"> <a href="/show_directions/{{r.id}}/"><p style="text-align:left">{{r.duration}}' {{r.distance}} χλμ <b>{{r.open}}</b></p></a> </div> <hr style="border:3px solid #333333"> </div> i want to use this class for filtering: <div class="b_category"> <p style="text-align: left"> <b>{{r.category}}</b></p> </div> Category has 4 possible values: cafe, bar, nigh_club, reastaurant I have found the following code but i can't figure out what i should change in order to work in my code: http://jsfiddle.net/x1av5809/ Category may contain more tha one values seperated by comma, for example bar or cafe, bar Thanks in advance -
NextJS: Axios is returning 401 error for authenticated pages where JWT tokens are set as HttpOnly cookie after login from django
I have set the access and refresh tokens as HttpOnly cookie from Django backend. In NextJS frontend, the login view works and it shows the HttpOnly cookies are present in the XHR tab. Therefore, it must work for any other authenticated views also. But when I make the request from any other pages with Axios it returns: Error: Request failed with status code 401 As far as I understand, the Django server attaches the httponly cookies to very requests. Therefore, my request to the server must have the cookies in it but the cookies are empty! It works with Postman very well but not in the browser. My NextJS page: export default function profilePage() { return ( <div className={styles.maincontainer}> <p>Hi</p> </div> );}; export async function getServerSideProps() { const url = 'http://127.0.0.1:8000/api/auth/profile/'; const headers = {'Content-Type': 'application/json'}; const resp = await axios.get(url, Headers=headers) const data = resp.json; console.log(data) return {} }; In my login page, the cookies are present in XHR tab: But still if I send request from any authenticated page, it is showing error 401! What is wrong? -
ConnectionTimeoutError AWS elasticsearch using Django elasticsearch-dsl
Not sure what's going on: I am trying to deploy and create the ES index python manage.py search_index --rebuild -f however I am getting this error: ConnectTimeoutError((<urllib3.connection.VerifiedHTTPSConnection object at 0x10e8790a0>, 'Connection to vpc-xxxxx.us-east-2.es.amazonaws.com timed out I have custom TCP listening to port 9200 in my security group. Also in my settings file: ELASTICSEARCH_DSL = { 'default': { 'hosts': https://vpc-xxxxx.us-east-2.es.amazonaws.com, }, } Any help is greatly appreciated. Thanks -
Django overriding default ModelForm error messages not working
I am new to django and I know there are many stack overflow questions and answers related with this topic, but none of the solutions seems to work for me. I am trying to override django's default error messages. I tried these to name a few of the solutions I tried. class MyForm(forms.ModelForm): class Meta: error_messages = { 'first_name': { 'required': _("First name is required."), }, } Also tried this class MyRequest(models.Model): first_name = models.CharField( max_length=254, blank=False, error_messages={ 'blank': 'my required msg..', } ) Is there any thing I need to do on the template side? -
No CSS in Admin panel in Azure App Service hosted Django APP
I cant figure out how to make Azure App Service use css for admin panel. In settings.py I included these: import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') But somehow css is still not working for the admin panel. How can I fix this? As far as I know Oryx which works under Azure App Service should automatically run python manage.py collectstatic Any ideas? -
Storing and retrieving default values for fields in a related model instance
I would like to store default values for a model instance in a related object; for example, given this code: class Contract(models.Model): user = models.ForeignKey(User) product = models.ForeignKey(Product) duration = models.IntegerField(null=True, help_text='Contract validity (days)') template = models.ForeignKey(ContractTemplate) class ContractTemplate(models.Model): name = models.CharField(max_length=100) duration = models.IntegerField(help_text='Contract validity (days)') I would like to store objects representing different common durations like: yearly_contract = ContractTemplate.object.create(name='yearly', duration=365) monthly_contract = ContractTemplate.object.create(name='monthly', duration=30) and return the default value from the linked template when the object contract does not specify the value: contract1 = Contract.objects.create(user=foo_user, foo_product, template=monthly_contract) # contract1.duration should return 365 contract2 = Contract.objects.create(user=foo_user, foo_product, duration=45, template=monthly_contract) # contract2.duration should return 45 So, what is the best way to achieve something like this? -
How to show wagtail parent and child pages in graphql?
I am new to wagtail and trying to understand it. I have come across a problem and i need some help. I have setup graphene and graphql. I am able to fetch all the data aswell but I need to fetch the parent page data plus the child page data. I have tried multiple options but nothing is working. This is my models.py from __future__ import unicode_literals from django.db import models from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.admin.edit_handlers import (FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel) from modelcluster.fields import ParentalKey # Create your models here. from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField, StreamField from wagtail.core import blocks as work_blocks from wagtail.search import index class WorkIndexPage(Page): pass class FullStackPage(Page): description = RichTextField(blank=True) def child_pages(self): return TechnologyPage.objects.all().child_of(self) content_panels = Page.content_panels + [ FieldPanel('description', classname="full"), ] subpage_types = ['work.TechnologyPage'] class TechnologyDetailOrderable(Orderable): page = ParentalKey("work.TechnologyPage", related_name="technologypage") software_title = models.CharField(max_length=255) description = RichTextField(blank=True) class TechnologyPage(Page): content_panels = Page.content_panels + [ MultiFieldPanel([ InlinePanel('technologypage', label="Technology Details"), ], heading="Technology or Framework details"), ] This is my schema.py from __future__ import unicode_literals import graphene from graphene_django import DjangoObjectType from about.models import AboutPage from work.models import FullStackPage, TechnologyPage from django.db import models from api import graphene_wagtail class AboutNode(DjangoObjectType): class Meta: model = … -
Hosting django/scrapyd webapp [closed]
Where can I host my django/scrapyd/channels/postgresql web app?, I have no idea which hosting service would do this easily. Thanks. -
Insecure deserialization in python
I am trying to mitigate this piece of code against insecure deserialization, but I am not sure of how to do it... Original code def get_user(self, cookieObject): decode = base64.b64decode(cookieObject.remember_me) user, sign = pickle.loads(decode) # Validate signature if sign == self.sign_user(user): return user My code def get_user(self, cookieObject): creds = [session.username, self.sign_user(session.user)] # Validate signature if cookieObject == base64.b64encode(pickle.dumps(creds)): return user -
(Django query parameter using for loop) Is there a more efficient code?
I'm a novice developer studying Jango. If you look at the last code, the room connected to the accommodation, The options associated with the room were chained to import objects. The problem is, The speed is slow when receiving a value from the request. For your information, I'm taking the option as a query parameter list. It takes more than 5 minutes from 5 values. Is there a more efficient code? Thank you. The code is below. class AccommodationListView(View): def get(self, request, category_id=0): city = request.GET.get('city', None) start_date = request.GET.get('startDate', None) end_date = request.GET.get('endDate', None) guest = request.GET.get('guest', None) ordering = request.GET.get('order', 'favored') rate = request.GET.get('rate', None) room_option = request.GET.getlist('roomOption', None) q = (Q(city__name=city) & Q(room__maximum_capacity__gte=guest) & Q(rate__gte=rate) & ~Q(room__unavailabledate__start_date__gte=start_date, room__unavailabledate__end_date__lte=end_date) ) if category_id: q &= Q(category_id=category_id) accommodations = Accommodation.objects\ .select_related( 'address', 'category', 'city', 'host',)\ .prefetch_related( 'accommodationimage_set', 'room_set', 'review_set', 'room_set', 'room_set__option')\ .filter(q)\ .annotate(count=Count('review'), price=Min('room__price')).distinct() if room_option: for r in room_option: accommodations = accommodations.filter(room__option__name=r) -
React Axios - download excel file from Django backend
I am trying to download excel file which is generated by Django backend: class GenerateExcel(APIView): def get(self, request): filename = 'File.xlsx' wb = Workbook() ws = wb.active ws.title = "Workbook" response = HttpResponse(save_virtual_workbook(wb), content_type='application/ms-excel') response["Content-Disposition"] = 'attachment; filename="' + filename + '"' return response If I send request with a postman I get success response and I can download the file via option Save Response -> Save to a file and it works fine. If I try to download it in my frontend with axios I am able to download the excel file but it has different size then the file from a postman and it is not possible to open the excel file. I receive the file is corrupted error. I am using redux so this code is in actions file: export const getYhrtaskgrpExcel = (fromDate, toDate) => async dispatch => { const url = `http://127.0.0.1/excel-report/`; try { dispatch({ type: GET_EXCEL_REQUEST }); const res = await axios.get(url, {responseType: 'arraybuffer'}) dispatch({ type: GET_EXCEL_SUCCESS, payload: res.data }); console.log('this is data: ', res.data); var FileSaver = require('file-saver'); var blob = new Blob([res.data], {type:'application/ms-excel'}); FileSaver.saveAs(blob, "excel.xlsx"); } catch (error) { dispatch({ type: GET_EXCEL_FAIL, payload: error.data }); } } -
How to use Logstash to import data to Django?
I have a Django application which acts as an bridge between multiple data resources using ETL and CRUD tasks; monitor a resource for new or updated data (input) ingest & transform the data using business logic store the transformed data in a PostgresSQL database use Django model signals to automatically queue CRUD operations to sync data with another external resource (output) execute all queued CRUD operations against the other external resource The amount of application coded dedicated to monitoring, ingesting, and transforming the incoming data is non-trivial. As ETL requirements grow and new input resources are added, I would like to minimize or eliminate the need for building more ETL-related application code. It seems like Logstash might be a good candidate for this, since it can monitor external resources and automatically extract and load data and pass it on to some other resource. On Google, I am seeing plenty of tutorials on how to use Logstash to import data from a database such as PostgreSQL and keep Logstash in sync with other relational databases. There are also plenty of tutorials on how to use Logstash to import Django logs to something like ElasticSearch. However I am not seeing any recommended … -
Calling serializer.save() on a list of serialisers Django
I'm trying to save objects for a list of serialised data in my views: myData1 = {...} myData2 = {...} mySerial1 = MySerializer(data=myData1) mySerial1.is_valid(raise_exception=True) mySerial2 = MySerializer(data=myData2) mySerial2.is_valid(raise_exception=True) saveList = [mySerial1, mySerial2] for serial in saveList: serial.save() Unfortunately I'm getting this error: AttributeError: 'function' object has no attribute 'save' Is there something I'm missing in how I try to save an object using serialised data? -
Return the total of a group with Jinja
I have an object to return by group and then display the number of grouped items. example : <table> <thead> <tr> <th>Name</th> <th>Total</th> </tr> </thead> <tbody>> {% set count = 0 %} {% for item in data.items|groupby(attribute="name") %} <tr> <td>{{ item.grouper }}</td> <td>{% for number in item.list %}{% set count = count + 1 %}{{ count }}{% endfor %}</td> </tr> {% endfor %} </tbody> </table> I also tried : <table> <thead> <tr> <th>Name</th> <th>Total</th> </tr> </thead> <tbody>> {% for item in data.items|groupby(attribute="name") %} <tr> <td>{{ item.grouper }}</td> <td>{% for number in item.list %}{{ loop.length }}{% endfor %}</td> </tr> {% endfor %} </tbody> </table> But the return for a total of 3 is: "111" or "333" and i want display "3", avez-vous une idée ? -
Filter by annotated array's length
class Language(models.Model): iso_code = models.CharField() class Publisher(models.Model) name = models.CharField() class Book(modle.Model): name = models.CharField() language = models.ForeignKey(Language) publisher = models.ForeignKey(Publisher, related_name='books') lang_ids = [1,2] qs = Publisher.objects.annotate( x=ArrayAgg( Case( When( books__language__in=lang_ids, then="books__name" ) ) ) ) I want to filter the qs as shown here - https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#len qs.filter(x__len=2) Why is it impossible to filter the qs this way? I am getting an error IndexError: tuple index out of range. Output field in ArrayAgg is ArrayField class ArrayAgg(OrderableAggMixin, Aggregate): function = 'ARRAY_AGG' template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)' allow_distinct = True @property def output_field(self): return ArrayField(self.source_expressions[0].output_field) def convert_value(self, value, expression, connection): if not value: return [] return value -
Can't login to Django admin panel
Made custom user, made custom user manager, can't log in into Django admin panel Tried (means don't offer it): manage.py synced manage.py createsuperuser checked that my users actually is staff and active set AUTHENTICATION_BACKENDS to 'django.contrib.auth.backends.ModelBackend' set AUTH_USER_MODEL = 'users.User' DB - postgres, im also using rest framework models.py from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models, transaction # Create your models here. class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, deviceId, **extra_fields): """ Create and save a User with the given email and password. """ if not deviceId: raise ValueError('The device id must be set') user = self.model(deviceId=deviceId, **extra_fields) user.save() return user def create_superuser(self, deviceId, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(deviceId, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): deviceId = models.TextField(max_length=255, unique=True, db_column='device_id') email = models.EmailField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, db_column='name') fcmToken = models.TextField(blank=True, null=True, db_column='fcm_token') picture = models.ImageField(upload_to='UserAvatars', null=True) pictureUrl = … -
importing data into django model
i'm having so many issues with timezones its insane. following this thread, i've written a python script that passes the contents of the input file into my django model, but given how much i'm struggling with this i'm wondering if the Models.object.create() function is a good way of loading the data in. for context, i'm using python2.7 and django 1.6.11. this is my models.py: ORDER_STATUS = ( ('NC', 'NoCar'), ('UC', 'UserCancelled'), ('CC', 'Completed') ) PAYMENT_METHOD = ( ('CA', 'cash'), ('CC', 'creditCard'), ) class Member(models.Model): member_hash = models.CharField(max_length=32) member_loc_lat = models.FloatField(max_length=20) member_loc_long = models.FloatField(max_length=20) # blank to be able to pass in null values, null to tell the DB to accept null values member_locality = models.TextField() member_display_name = models.TextField() member_created_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return self.member_id class Driver(models.Model): driver_hash = models.CharField(max_length=32, unique=False, null=True) # docs say null=True shouldn't be specified on CharField class Order(models.Model): # status and payment method defined above status = models.CharField(max_length=2, choices=ORDER_STATUS, default='NC', db_index=True) payment = models.CharField(max_length=2, choices=PAYMENT_METHOD, default='CA', db_index=True) order_id = models.CharField(max_length=32, primary_key=True) tips = models.BigIntegerField(unique=True) special_req = models.CharField(max_length=100) order_ended_time = models.DateTimeField(auto_now=False, auto_now_add=False) member = models.ForeignKey(Member, null=True, default=None) driver = models.ForeignKey(Driver, null=True, default=None) and this is the script, load.py, that loads my raw data into models.py: … -
Place (?) tooltip next to field-name Django
In my_model I have field1 and field2. In my form I would like to have a (?) tool-tip next to the label of field2 such that I can display some tooltips for it when users hover over the (?). I have found something which works in a html-file but I don't really know how to load the labels from the html file to the label class MyModelForm(forms.ModelForm): class Meta: model = my_model fields = ["field1","field2"] labels = {"field2":load_html("my_hmtl_file.html") Is there a better way to add this (?) tool-tip to a field(s)? -
How to sort queryset based on foreign key with no duplicates
I would like to feature the 5 most recently reviewed books on my website. I am trying to order the books based on the time they were reviewed. The problem is if a book has recently been reviewed more than once, it will appear more than once. How do I get 5 unique books from this query? (I tried adding .distinct() to the query and it didn't work!) reviewed = Book.objects.order_by('-review__date_posted')[:5] -
Real estate website in Django. How to build some functions?
I had a question about Django. I want to create a real estate website where people can publish their homes by themselves? So, How can I do this? What do you recommend me to do? -
How does deploying a project to a subdomain work?
I am familiar with deploying a Django project to its own domain, however I am not familiar with deploying to a subdomain (app.domain.com) where domain.com is pointing to another site. I can't seem to find any support in the docs on this, so do I just deploy this as usual or are there extra steps needed to ensure all my URLS are resolvable & the app functions as it should? -
how to create an ubuntu environment when using Docker on MAC computer with django
I am super new to Docker and i am trying to grasp a concept. Goal: I am trying to create this tech stack create a Ubuntu OS install python install django/DRF install postgresql install reactJS So far I have only been able to install python, django... Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code RUN pip install -r requirements.txt COPY . /django-docker/ Docker compose version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 My question is mainly on how do I install or add Ubuntu on the tech stack mentioned above or is it really necessary to have Ubuntu if i intend to deploy my tech stack to AWS in the future so other developers work on the same project quickly when they setup their machines?