Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Background images for static files in django don't display
am customizing a html template called dataserv in django i have been stack for a while now since i cant load background images in css what i have tried so far #subheader.about {background: url("./images/about_bg.jpg") center center no-repeat; padding:100px 25px;} #subheader.about {background: url("../images/about_bg.jpg") center center no-repeat; padding:100px 25px;} #subheader.about {background: url("/static/images/about_bg.jpg") center center no-repeat; padding:100px 25px;} #subheader.about {background: url("localhost:8000/static/images/about_bg.jpg") center center no-repeat; padding:100px 25px;} and many other suggestions still they dont work any one with can help please The strange thing is that all other static files like normal images,videos work except for the background image url -
deploy react with django and nginx
https://github.com/hiagokroton/django-rest-framework-react-tutorial-master I am starting deploy of an application with React and Django Rest, I configured Nginx as follows: server { listen 80 default_server; server_name 18.220.194.77; root /var/www/frontend/build; # React build location location / { try_files $uri $uri/ /index.html; } } I configured React as it was running locally, changing the ip to the AWS instance: // App.js import React, { Component } from 'react'; class App extends Component { state = { todos: [] }; async componentDidMount() { try { const res = await fetch('http://18.220.194.77:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } } React and Nginx are working on AWS: http://18.220.194.77/ To test, I ran Django 'python manage.py runserver 0.0.0.0:8000' Performing system checks... System check identified no issues (0 silenced). November 09, 2018 - 10:50:12 Django version 2.1.3, using settings 'todo_api.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [09/Nov/2018 10:50:13] "GET /api/ HTTP/1.1" 200 268 How do I find the problem? And I run Django with Gunicorn to serve React. -
Django: transaction.atomic in CreateView, form_valid()
Does it make sense to have transaction.atomic for form_valid in my CreateView? @transaction.atomic def form_valid(self, form): self.instance = form.save(commit=False) self.instance.event = self.request.event # When the super method is called the instance # is saved because it's a model form super().form_valid(form) return HttpResponseRedirect(self.get_success_url()) -
i want to use this api to test refresh token to resend access token. What are the changes i need to do in this code. thanks in advance
def login(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) -
filter datatable by date and number seprately in one table
hey i want to filter my table i have two options filter by date and filter by number when i filter by date its work fine and also when i delete filter by date script and try to filter by cheque date it will work perfectly but the problem is that it does not work when i use both scripts means at that time it filter by date but not by cheque number...its giving me error cheque date is not null but if i set any cheque date and then filter by number than it will filter only the selected date in between result not search entire table.. i want user search seprately does not depend on each other <script> $(document).ready(function(){ //use a special class name or id for the table //using find I'm getting all tr elements in the table //using not(':eq(0)') I'm ignoring the first tr element //using each I'm iterating through the selected elements $('table').find('tr').not(':eq(0)').each(function(i){ //using children('td:eq(0)') I'm getting the first td element inside the tr $(this).children('td:eq(0)').addClass('sno').text(i+1); }); }); </script> <script> $(document).ready(function(){ $("#divChqDate").hide(); $("#divCheque").hide(); var table = $('#datatable').DataTable({ }); /* Initialise datatables */ var oTable = $('#datatable').dataTable(); $("#sea").click(function() { //Creating of our own filtering function $.fn.DataTable.ext.search.push( function(oSettings, … -
Using value of an attribute of django object in Javascript function
I have a model named VisitorInfo in models.py which is as follows: class VisitorInfo(models.Model): #To maintain clarity i am not showing all the fields. visitor_id = models.CharField(max_length=120) pages_visited = models.ManyToManyField(Page,blank=True) time_zone = models.CharField(max_length=120, null= True, blank=True) ip = models.CharField(max_length=120, null= True, blank=True) device_type = models.CharField(max_length=120, null=True) Following is the view where i am using this model. class Live_Now(LoginRequiredMixin, TemplateView): template_name = 'dashboard/live_now.html' def get_context_data(self, **kwargs): context = super(Live_Now, self).get_context_data(**kwargs) search = self.request.GET.get('q') if search: if VisitorInfo.objects.filter(Q_filter).filter(active=True).count() >0: context['list_no'] = VisitorInfo.objects.filter(Q_filter).filter(active=True) else: context['list_no'] = "N" return context What i need to do as soon as live_now.html page loads and Live_Now view runs, a new tab will open with following url. url = 54.161.109.227:5000/visitor_id I know that to open a new tab i have to write down script in live_now.html which is as follows. <script type='text/javascript> window.open(url); // Above written url </script> But how do i fetch visitor_id of the visitor at runtime. Fetching visitor_id is the task fo python function and opening new tab is the function of javascript. How do i pass value of python variable in javascript program ? For time being i am fetching visitor_id of first visitor in visitors and i have written the following function to … -
Django : How to import a data from csv to database without using form?
I'm very new to Django, actually very new to coding too. I know it's a silly question, but I have no idea how to make this. I wanted to import some of data from local csv file and store to database (mine is mysql) without create an upload form (almost of tutorials I've found from google). I'm very confused of MVC model e.g. where's the part of handling csv should stand? view or model? and also I have to create a function to cut undesired fields from csv. where should I put that code in ? Here's my model from __future__ import unicode_literals import csv, io from django.conf import settings from django.db import models #from django_countries.fields import CountryField class ASN(models.Model): num = models.IntegerField(primary_key=True) owner = models.CharField(max_length=50, null=True) # Using countryfield to convert from country code to name countryCode = models.CharField(max_length=5) name = models.CharField(max_length=100, null=True) #countryName = CountryField() def __str__(self): return str(self.owner) + " " + str(self.num) + " " + str(self.countryCode) class Host(models.Model): name = models.CharField(max_length=20) id = models.IntegerField(primary_key=True) def __str__(self): return str(self.id) + " " + str(self.name) class Peer(models.Model): router_ip = models.CharField(max_length=20, primary_key=True) bgp_state = models.IntegerField(default=0) as_num = models.ForeignKey('ASN', on_delete=models.CASCADE) host_id = models.ForeignKey('Host', on_delete=models.CASCADE) def __str__(self): return str(self.host_id) + … -
count aggregation on jsondata->field using django ORM query
I have a model like from jsonfield import JSONField class data(model): content=JSONField() ....... My sample DB entry for the model data would be data1 : id =1, content = {"email":"abc@gmail.com"} data2 : id =2, content = {"email":"cdf@gmail.com"} data3 : id =3, content ={"email":"abc@gmail.com"} data4 : id = 4, content ={"email":"sfg@gmail.com"} data5 : id = 5, content ={"email":"abc@gmail.com"} data6 : id = 6, content ={"email":"sfg@gmail.com"} I need to get find the non-unique "email" values and list of ids like "abc@gmail.com" : [1,3,5] "sfg@gmail.com : [4,6] I'm using django 1.11 and python 2.7 and postgres9.3 My query was lists = data.objects.filter(....).extra(select={'email':"content->>'email'"}).values('email','id') the results i got is {"email":"abc@gmail.com","id":1} {"email":"cdf@gmail.com","id":2} {"email":"abc@gmail.com","id":3} {"email":"sfg@gmail.com","id":4} {"email":"abc@gmail.com","id":5} {"email":"sfg@gmail.com","id":6} Which includes unique and non-unique values, which is not what is required Is there a possibility to query only unique values from JSON field using Django. Tried distinct() but it fails as both 'id' and 'email' in in the values part anyhow processed it further as for d in l: if d['email'] not in temp: temp[d['email']]=[d['id']] else: temp[d['email']].append(d['id']) Got results as all values including unique and non-unique as below "abc@gmail.com" : [1,3,5] "sfg@gmail.com" : [4,6] "cdf@gmail.com" : [2] ## not desired Is there any way that would process this data … -
How to create a custom CharField accepting null value but the COLUMN stay NOT NULL in database?
HELP. I need to write a custom CharField whose only difference with CharField is the COLUMN will stay NOT NULL during table creating or altering(migrating) with or without setting null=True. I've checked https://docs.djangoproject.com/en/2.1/howto/custom-model-fields/#custom-database-types . Overwriting db_type may be close, but it only affect table creating and querying and isn't respected by makemigrations. Please tell me what part should I overwrite to affect the migrating. Thanks a lot. I've been reading the source code for an hour but don't have any idea. Sent from cellphone. Sorry for the format. -
Django - I want my view to return a single JSON blob representing all objects, instead of a list of JSON blobs for each object
I have a Django Model/Serializer/View. They return everything in a list like [json1, json2, json3 ... ] but what I need is to return everything in a single JSON object like: {"attr1": [obj1.attr1, obj2.attr1 ... ], "attr2": [obj1.attr2, obj2.attr2 ... ]} I've been having trouble accomplishing this. I have included my model, view and serializer below. class CustomModel(models.Model): class Meta: managed = False db_table = database_namespace('table') ordering = ('pkfield', 'attr1', 'attr2') attr1 = models.IntegerField(db_column='attr1') attr2 = models.IntegerField(db_column='attr2') pkfield = models.IntegerField(primary_key=True, db_column='pkfield') class CustomView(viewsets.ModelViewSet): schema = AutoSchema( manual_fields=[ #SOME FILTER STUFF IS HERE - NOT RELEVANT ] ) queryset = CustomModel.objects.all() serializer_class = CustomSerializer filter_class = CustomFilter #NOT RELEVANT TO QUESTION class CustomSerializer(serializers.ModelSerializer): datasource = serializers.SerializerMethodField() class Meta: model = CustomModel fields = ('datasource',) # not relevant to question def get_results(self, obj): return serializers.ListSerializer(obj).data def get_datasource(self, obj): return {"attr1":[obj.attr1], "attr2":[obj.attr2], "pkfield":[obj.pkfield]} So yeah obviously what I have here doesn't do what I want (view just returns a list of JSON objects instead of a single one comprising all of them), but I don't know how to change this to do what I need. How do I define a behavior so that the view returns a merged block of all objects? -
trying to get list of list from django in javascript as data for csv but quotes shown in html number
<script type="text/javascript"> /* csv_list: list of list got from django index function (views.py) eg:[['abc','1'],['xyz','0']] */ var data = {{csv_list}}; function genrate_csv() { var csv = 'Tweet, Polarity\n'; data.forEach(function(row) { csv += row.join(','); csv += "\n"; }); console.log(csv); var new_elm = document.createElement('a'); new_elm.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv); new_elm.target = '_blank'; new_elm.download = 'data.csv'; new_elm.click(); } </script> error showing html code for quote django code: (views.py) def index(request): if request.method=="POST" and request.POST.get('query') != "": tweet_list = script.tweets(request.POST.get('query'),request.POST.get('numtweets')) pos,neg,net,csv_list = script.analysis(tweet_list) context = { 'tweet_list' : tweet_list, 'csv_list' : csv_list, #passed the list of list 't': len(tweet_list) } return render(request,"index.html",context) -
Django 2.1.2: Generic detail view SchoolDetailView must be called with either an object pk or a slug in the URLconf
I am new in django and didn't understand what is pk or slug. What is going on? models.py: class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name Template Page: <a class="navbar-brand" href="{% url 'basic_app:list'%}">Schools</a> urls.py: path('',views.SchoolDetailView.as_view(),name='list'), views.py: class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'basic_app/school_detail.html' -
How to filter based on any letter typed in autocomplete (Dango)
The process for autocomplete in Django works fine. My issue is that i want to filter not only by first letter in a model field first_name but for any letter a first_name might have. For example imagine that I stored in the column first_name the below values in my table Profile: Louna Lola Linda Mola Rouna By typing L the search returns Louna,Lola,Linda. I want by typing na the search to return Louna and Rouna Any ideas? My class: class ProfileAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! # if not self.request.user.is_authenticated(): # return Profile.objects.none() qs = Profile.objects.all() if self.q: qs = qs.filter(first_name__istartswith=self.q) return qs My model: class Profile(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) created_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return self.first_name+ " " +self.last_name My form: from django import forms from .models import Profile from dal import autocomplete from django.forms import ModelChoiceField class ProfileForm(forms.ModelForm): first_name = forms.ModelChoiceField(queryset=Profile.objects.all(),widget=autocomplete.ModelSelect2(url='profile-autocomplete')) class Meta: model = Profile fields = ('__all__') My template: {% load static %} {% block content %} <div> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" /> </form> </div> {% endblock %} {% block footer %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' … -
Django Serializer POST data not fully passed to serializer
I have the following serializer definition: class TestSerializer(serializers.ModelSerializer): contexts = serializers.SerializerMethodField() class Meta: model = Test fields = ( "id", "contexts" ) def get_contexts(self, obj): return ... def create(self, data): print('CREATE') print(data) return super().create(data) def update(self, instance, validated_data): print('UPDATE') print(validated_data) return super().update(instance, validated_data) and in a viewset the usage of such serializer_class = TestSerializer queryset = Test.objects.all() Note that the contexts field is not a database field. When accessing the endpoint with a GET I receive the information correctly with { "id": 1, "contexts": [{...}] } But when sending the same data back as a POST then there's two issues. First serializer doesn't seem to be able to correlate the correct dataset since I always end up in the create method leading to the error duplicate key value violates unique constraint and when printing the data in the create method the contexts are not present at all. -
Passing data from template to python code in Django
I am building a web app using Django framework. How do I accept data selection from the user on a drop down in a template(HTML) and pass the data selected to my main python logic code(util.py) ? -
retrieving Django queryset in conditions' order
i'm trying to make a query that gives me the results in the order that i have the conditions in. I tried the following: icons = icons.filter( Q(name__iexact=word) | Q(name__istartswith=word) | Q(words__text__icontains=word) | Q(name__icontains=word) ).distinct() and also exact_icons = icons.filter(Q(name__iexact=word)).distinct() start_with_icons = icons.filter(Q(name__istartswith=word)).distinct() contains_icons = icons.filter( Q(words__text__icontains=word) | Q(name__icontains=word) ).distinct() icons = exact_icons | start_with_icons | contains_icons so i would like to first get the results that match exactly, then the ones that start with and only at end the ones that contain the word, but neither of the alternatives above seem to work. Any ideas how can i accomplish this? Thanks -
How can I Overide the django Rest 404 handler so I can hve dynamic 404 pages
I have tried this link https://stackoverflow.com/a/42036696/6473175 but it doesnt seem to work I get a 500 server error page when DEBUG=False when DEBUG=True it loads my custom 404,html. I was looking to do something like this below. def handler404(request): domain = request.META['HTTP_HOST'] if domain == "mydomain1": return render(request, 'index.html', status=404) else: return render(request, '404.html', status=404) -
Preserve data when using TimeStampedModel from django_extensions
I have many django models, some have fields for record creation and updation date and time like this date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) and some models do not have this. I am thinking to use TimeStampedModel provided by django_extendsions. I don't want to lose my data, how can i use django_extension.db.models.TimeStampedModel and also the new fields have same data as that of old fields. -
Django-admin one of the field must be filled in django-models
Hello I have model like class mymodel(models.Model): a = models.CharField(blank=True, null=True, max_length=255) b = models.CharField(blank=True, null=True, max_length=255) c = models.CharField(blank=False, null=False, max_length=255) Since I'm using the django admin as a back-end controller of the data stored in my model I want to make either one of them to not be null for example the user must either fill a or either fill b or both to be filled, but if both are empty must throw an error -
Docker with mysql and django. Connection to mysql is refused despite any attempts
So far I have tried everything I could find on the internet - but nothing seems to help. This is my docker-compose.yml file: version: '3.3' services: ivs_fraud: build: context: . args: GIT_SSH_KEY: ${GIT_SSH_KEY} image: ivs_fraud:latest container_name: fraud depends_on: - ivsdb links: - ivsdb networks: - database_network networks: database_network: driver: bridge And I have a link / dependency to ivsdb service which is defined in another docker-compose-dev.yml file: version: '3.3' services: ivsdb: image: mysql container_name: ivsdb networks: - database_network ports: - ${DEFAULT_DB_PORT}:3306 restart: always environment: MYSQL_DATABASE: ${DEFAULT_DB_NAME} MYSQL_USER: ${DEFAULT_DB_USER} MYSQL_PASSWORD: ${DEFAULT_DB_PASS} MYSQL_ROOT_PASSWORD: ${DEFAULT_DB_ROOT_PASS} This is my .env file (Django reads this .env file and creates a connection according to it): DEFAULT_DB_NAME=ivsdb DEFAULT_DB_HOST=ivsdb DEFAULT_DB_PORT=10001 DEFAULT_DB_USER=root DEFAULT_DB_PASS=root DEFAULT_DB_ROOT_PASS=root And i keep getting: (2003, 'Can\'t connect to MySQL server on \'ivsdb\' (111 "Connection refused")') There are several modifications that i have tried with no success: Move everything into one docker-compose file Get rid of "networks" entry completely Change hosts to ivsdb / 127.0.0.1 / localhost / 0.0.0.0 Things that work: Djago service runs well Mysql service runs well. I can connect to it using command line: mysql -uroot -proot -P10001 --protocol=tcp or mysql -uroot -proot -P10001 -h127.0.0.1 (IP adress enforces tcp protocol) Looks like … -
How to use join query in Django?
I have 2 table which are Author and Book. In author table, I have 'id' and 'name' field. In book table, I have 'book_id' and 'author_id'(foreign key). Here are my sql statement.It works in my database. select "Author"."Name",count("BookId") from "Author" join "Book" on "Book"."AuthorId" = "Author"."Id" group by "Author"."Name" Now I want to get the count of book.id which is group by AuthorId that can get the AuthorName from Author table. What should i do? -
shared imports cause NameError when imported by other modules
I have a modular application, where each module ended up sharing somethings such as APIView from rest framework among others. Instead of repeating the imports in multiple views.py files, I thought of just importing them in one file and importing that file instead. Is that a good practice in the first place? Regardless, I am curious to know why the following raises NameError:APIView not defined. File structure: app conf __init__.py sharedimports.py base.py production.py development.py __init_.py urls.py members views.py So, in sharedimports.py I have: from rest_framework.views import APIView then in members/views.py from agrigo.conf.commonimports import * class index(APIView): I was under the impression the * imports all objects into members/views.py -
Annotate Queryset with logarithm of field value in Django
I've researched available django aggregation functions and noticed that logarithm is missing there. So, my question is: how can I use logarithm in annotating the Queryset? I cannot take logarithm after Queryset evaluation, because I need to annotate not exactly with logarithm, but rather with an expression containing it, for example for some models User and Task I need to annotate User with F('task__cost') / Log('task__solved_count'). UPD: It'd be great if I could do it without using database-specific functions (for Postgres), but that solution is possible too. -
Overriding CreateAPIView, accessing request user
how can I save created_by as request user? Note that this field is not defined in the serializer class User(models.Model): email = models.EmailField(...) name = models.CharField(...) created_by = models.ForeignKey('User') class UserSerializer(serializer.ModelSerializer): class Meta: model = User fields = ['email', 'name'] class CreateUserApiView(CreateAPIView): model = User serializer_class = CreateRequesterSerializer def create(self, request, *args, **kwargs): # how can I save `created_by` as request user? return super(CreateUserApiView, self).create(request, *args, **kwargs) -
How to make Vue.js post hased password to Django REST API AbstractBaseUser custom model?
I'm struggled with create users as Vue.js to Django REST Framework. First of all, I made my own custom user model with AbstractBaseUser. and migrated well, It is able to communication with mysql, vue.js too. the python manage.py createsuperuser works well too. So the password field created as hashed string automatically whenever I try to use createsupersuser and at the ~/admin domain too. However when I'm trying to send POST method in Vue.js to user model, It's just putted raw(non hashed) password in it, and not follow my Django default model set up like is_admin = False, is_active = True. These boolean fields would be set always 'False' by Vue axios method Here is my user model. ./Users/models.py # Abstracted User fields with options class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( max_length=20, null=False, blank=False, unique=True, error_messages={'unique': _('이미 존재하는 아이디 입니다. (The account is already existed.)')}, ) full_name = models.CharField( _('first_name' + 'last_name'), max_length=30, default='', ) email = models.EmailField( _('email address'), ) organization = models.CharField( max_length=50, null=True, blank=True, ) phone = models.CharField( max_length=16, null=True, blank=True, ) is_staff = models.BooleanField( _('is_staff'), default=False, ) is_active = models.BooleanField( _('is_active'), default=True, ) created_date = models.DateTimeField( _('date joined'), auto_now_add=True, ) updated_date = models.DateTimeField( auto_now=True, ) # User …