Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django change background color using button
I want to change background color, where user button touch. Info with color should be stored at my DB. HTML: <div class={{colors}}> where class = "card card success/info/warning flex-item" Buttons: <a href="{% url 'board:success_button' %}"><button type="button" class="btn btn-outline-success">Done!</button></a> <a href="{% url 'board:warning_button' %}"><button type="button" class="btn btn-outline-warning">In progress...</button></a> <a href="{% url 'board:danger_button' %}"><button type="button" class="btn btn-outline-danger">Canceled</button></a> urls.py: url(r'^$', views.success_button, name='success_button'), url(r'^$', views.warning_button, name='warning_button'), url(r'^$', views.danger_button, name='danger_button'), views.py: def success_button(request): color = Card.objects.create(colors="card card success flex-item") color.save() def warning_button(request): color = Card.objects.create(colors="card card info flex-item") color.save() def danger_button(request): color = Card.objects.create(colors="card card warning flex-item") color.save() models.py: colors = models.CharField(max_length=200) Description. Card have bootstrap background color - > success, info and warning. User touch info button, then background ( class ) change to card info and it storing at DB. Thanks in advance! -
Django Restful API App
I made a new API app to serve all the API requests for my web app. So I want to first do something simple and return a DataFrame object in the form of JSON. I am also using the Django Rest Framework Library. My urls.py from django.conf.urls import url, include from rest_framework import routers from api import views router = routers.SimpleRouter() router.register(r'test', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] My views.py: class UserViewSet(APIView): renderer_classes = (JSONRenderer, ) def get(self): queryset = NAV.objects.filter(fund__account_class=0, transmission=3).values('valuation_period_end_date').annotate( total_nav=Sum(F('outstanding_shares_par') * F('nav'))).order_by('valuation_period_end_date') df = read_frame(queryset, coerce_float=True) df.loc[:, 'valuation_period_end_date'] = pd.to_datetime(df.valuation_period_end_date) df.loc[:, 'timestamp'] = df.valuation_period_end_date.astype(np.int64) // 10 ** 6 df.loc[:, 'total_nav'] = df.total_nav return JsonResponse(df) But I get the error AssertionError:base_nameargument not specified, and could not automatically determine the name from the viewset, as it does not have a.querysetattribute. I am new to Django Restful API Framework and was wondering if I am doing this right? -
TypeError: Error when calling the metaclass bases
TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases StaffRestrictedMixin, StatisticsIndexView I have this type of error, but I can't fix it regardless the other similar questions. views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context class StatisticsSubmitView(StaffRestrictedMixin, StatisticsIndexView): model = Statistics() What do you suggest to fix that issue? -
Avoiding multiple AJAX calls on jquery sortable( )
I am new to JQuery. Basically I have a table which I can sort the rows. I want to save the new order in the backend, which I am able to do. However, I noticed that I am sending multiple Ajax calls depending on the number of times I sorted the table. The order is not saving properly in the backend. Here is my code. The variable order is where the new IDs are stored. I am sending it in my Django through the '/updateorder' route/ <script type="text/javascript"> $(document).ready(function(){ $("#sortable").sortable({ update: function (event, ui) { var order = $(this).sortable('toArray'); console.log(order); $(document).on("click", "button", function () { $.ajax({ data: {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, 'order[]': order}, type: 'POST', url: '/updateorder' }) }); } }).disableSelection(); $('button').on('click', function () { var r = $("#sortable").sortable("toArray"); var a = $("#sortable").sortable("serialize", { attribute: "id" }); console.log(r); }); }); </script> How can I avoid sending multiple Ajax calls when I click on the button? Also, what is the correct way to redirect to a different page after the logic is executed? Thanks for reading! PS: I am using python/django in the backend -
Passing an image from view to template
Basically, my django app needs to create an image in a view, and pass that to a template. This is easy for a string, but I can't find a way to do it with an image. I have read many stack overflow threads but none quite like mine, which is surprising. I was trying variations of this as my view: views.py: def index(request): while (True): #video_capture = cv2.VideoCapture(0) #ret, frame = video_capture.read() img = "D:/Desktop/Tap/bsnsFaces.jpg" frame = cv2.imread(img) facesNumber ="Found {0} faces!".format(len(faces)) return render(request, 'result.html', {'p': facesNumber}, {'img': frame})` With the {'img':frame} part at the end not being anywhere close to right. I tried a few things that I found on SO but nothing worked so far. I know that the image is static but eventually I want this to be a frame captured from a webcam so I can't solve this by using models (or can I?). Thanks in advance for any advice! -
serializers validation method is not validating list of objects for the first time
models.py class Customer(models.Model): name = models.CharField(max_length=128) email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=128) serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ("name", "email", "phone") extra_kwargs = { "email":{"required":True}, } def validate_email(self, email): qs = Customer.objects.filter(email__iexact=email) if qs.exists(): raise serializers.ValidationError("This email is already existed") return email def validate_phone(self, phone): qs = Customer.objects.filter(phone__iexact=phone) if qs.exists(): raise serializers.ValidationError("This Phone is already existed") return phone views.py class CustomerApi(SerializerMixin, APIView): ...... ......... def post(self, request): serializer = CustomerSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response( serializer.errors, status = status.HTTP_400_BAD_REQUEST ) json [ { "phone": "123", "name": "name1", "email": "123@ll.cc" }, { "phone": "123", "name": "nam32", "email": "123@ll.cc" } ] the above customer json list have two objects with same email and phone . But it is not validating the email and phone(validation methods are not working) when i create if for the first time. But once it get created, the second time when i try to create the customer with the same list, validation method is working as expected. i couldn't trace out the problem. -
Try to save data in form, but Django won't recognize User
I'm trying to save data input using a form, but I'm running into a problem where Django won't recognize the user. I always get this error message: "Cannot assign ">": "Post.user" must be a "User" instance." This is what I have so far in my models: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) My forms: from django import forms from firstapp.models import Post class IndexForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ('post',) And my views: from django.shortcuts import render, redirect from firstapp.forms import IndexForm from django.views.generic import TemplateView class HomePage(TemplateView): template_name = 'home/home.html' def get(self, request): form = IndexForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = IndexForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = IndexForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) Any idea what's going on? -
Unable to transfer Data from models to html using templates
View.py from django.shortcuts import render from django.http import HttpResponse from .models import Albums from django.template import loader def index(request): all_albums = Albums.objects.all(); template = loader.get_template('Ganaana/index.html'); context = { 'all_albums':all_albums, } return HttpResponse(template.render(context,request)) def define(request,Albums_id): return HttpResponse("<h1>Your Id is "+str(Albums_id)+"</h1>"); index.html <ul> <% for albums in all_albums %> <li><a href="/music/{{albums.id}}/">albums.artist</a></li> <% endfor %> </ul> I dont know what the error i used templates folder and put data in it i dont understand what the problem i import class correctly.. i dont understand? -
Django, show and hide details of items in a ListView with jQuery
I have a ListView in django which I'm trying to show/hide extra details for each item when a 'More info' button is pressed. The issue is with trying to get a unique identifier for each item in the django template that javascript can act on to hide/show a specific item details rather than all of them. The javascript bit definitely isn't right. <div class="quotes"> {% for quote in quotes_results %} <div> <h3>{{ quote.supplierName }}</h3> <div> </div> <a class="btn btn-cta-primary" href="{% url 'users:profile' price_id=quote.priceId %}">Proceed</a> <button class="btn btn-cta-secondary" id="button">More Info</button> </div> <div class="til" id="til{{ quote.priceId }}"> <p>test hide and show more details</p> </div> {% endfor %} </div> {% block inner_js %} <script type="text/javascript"> $(document).ready(function () { $('#button').click(function (priceId) { $('#till' + priceId).toggle() }) }) </script> {% endblock inner_js %} -
Model default values from another model
Is it possible to use default values stored in one model to populate the default values in another? My app has a form with approx 15 fields. Users often have to complete the form 20-30 times. About 2/3rds the data is identical each time, so what I'd like to do is prepopulate the form with default data so that the user only needs to edit 3-4 fields. The default values are different for each user so my thought is to capture the first form data in a 'defaults' table linked to the user, then use default to pre-populate the form every time thereafter. Is this a reasonable approach? Can it be done? Is there a better way? -
How to use a reg. form to pass a variable in the url and render results in django?
If I submit 'http://localhost:8000/item/2/' to the address bar, I get the desired result, which is a rendering of item_detail.html with its item variables filled. But when I try to pass the ‘2’ via a form, I only get the html without rendering (and instead displaying in the console upon a console.log. How can I use a form to get the initial result? And is there an easiest way to do this? I've added the code below... thanks. INDEX.HTML <form id="form"> Item Name:<br> <input id="entry" type="text"><br> <input type="submit" value="Submit"> </form> MAIN.JS var form=$("#form") $(document).on("submit", "#form", function (e) { e.preventDefault(); var term = $("#entry").val() var query="/item/"+term $.ajax({ type: 'GET', url: query, }).done(function(response) { console.log(response) }) }) URL.PY url(r'^item/(?P<id>\d+)/', views.item_detail, name='item_detail'), VIEWS.PY def item_detail(request, id): try: item = Item.objects.get(id=id) except Item.DoesNotExist: raise Http404("This item doesn't exist") return render(request, 'inventory/item_detail.html',{ 'item': item, }) MODELS.PY class Item(models.Model): title = models.CharField(max_length=200) description = models.TextField() amount = models.IntegerField() -
django display media files local server
I've been researching this for a while. I think there is a problem with my index.html file where i'd like to display the pic. There is user uploaded jpg files stored in: media\user\profile\id_1\pic.jpg media\user\profile\id_2\pic.jpg and so on... Would like to display the user's profile image only on their page when logged in. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") root urls.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('index.urls')), ] if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html <div class="image"> <img src="{{ Theusers.image.url }}"/> </div> I think the problem is in the index.html? -
How to update multiple rows in MySQL (CASE, WHEN, THEN) using python/Django
I asked this question yesterday but It didn’t really help me. I am asking it again hoping my question is more clear this time. I am trying to update multiple rows in MySQL by using WHEN, THEN, ELSE case. I am trying to achieve this using python and Django in the backend. Here is my code: UPDATE priority SET priority_order = CASE priority_order WHEN 4 THEN 8 WHEN 1 THEN 4 WHEN 3 THEN 2 ## More X amount of WHEN/THEN statements ELSE priority_order END The problem is that I do not know how many WHEN and THEN lines I have.. How can I construct such a statement so that I can execute this using cursor.execute( )? Yesterday, someone advised to build a list of expression and pass as an argument like: from django.db.models import Case, When # Make a list of When expressions when_list = [When(priority_number=2, then=3), When(priority_number=3, then=4)] # Use in a query of your choice, as an example: Model.objects.update( priority_number=Case( *when_list)) But seems like it does not work on Mysql. I think this only works on SQLLite. The *when_list is not being decoded as my query execute. Please help! -
Nginx-proxy with SSL TLS handshake error
I'm trying to setup Nginx-proxy docker container made by Jwilder in combination the Letsencrypt companion container for ssl. behing the proxy is currently a single website that uses caddy as its server. Operating system is Ubuntu 16.04 and in the firewall I have opened the Ports 80 and 443. without Nginx-proxy I can connect to the website through HTTPS. But with nginx-proxy,I am unable to connect to the website through HTTPS. When I connect to is get the error, ERR_CONNECTION_REFUSED. I am out of idea's as to what could cause the error. docker-compose yml file: version: '2' volumes: postgres_data: {} postgres_backup: {} caddy: {} services: nginx-proxy: image: jwilder/nginx-proxy ports: - "80:80" - "443:443" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - /path/to/certs:/etc/nginx/certs:rw - /etc/nginx/vhost.d - /usr/share/nginx/html labels: - com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy nginx-proxy-ssl-companion: image: jrcs/letsencrypt-nginx-proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro volumes_from: - nginx-proxy django: build: context: . dockerfile: ./compose/django/Dockerfile depends_on: - postgres - redis command: /gunicorn.sh env_file: .env postgres: build: ./compose/postgres volumes: - postgres_data:/var/lib/postgresql/data - postgres_backup:/backups env_file: .env caddy: build: ./compose/caddy depends_on: - django volumes: - caddy:/root/.caddy env_file: .env environment: - "VIRTUAL_HOST=www.mydomain.nl, mydomain.nl" expose: - 80 - 443 redis: image: redis:3.0 Logs: postgres_1 | LOG: database system was shut down at 2017-09-17 06:59:52 UTC postgres_1 | LOG: MultiXact member … -
Multiple Image Field in Django Model
I am using django-cms for a client project. I want to add a carousel of images that will display all those images in my template. How do I add this using a model and implement it into a form to use? class Show(models.Model): title = models.CharField(blank=True, max_length=300) header_image = models.ImageField(upload_to="", blank=True) starting_date = models.DateField(default=datetime.datetime.today, blank=True) poster = models.ImageField(upload_to="", blank=True) description = models.TextField(blank=True) is_TS_show = models.BooleanField(default=False, blank=True) show_slug = models.SlugField(max_length=100) def __str__(self): return self.title def save(self, *args, **kwargs): self.show_slug = slugify(self.title) super(Show, self).save(*args, **kwargs) def get_absolute_url(self): return "/show/%s/" % self.show_slug It's for a carousel so it will be maybe 4-5 pictures. -
Retrieve all objects related to a particular foreign key in django
i have the following models.py: //models.py(code snippet) class userresp(models.Model): uid=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True) resp=models.CharField(max_length=20) datetime=models.DateTimeField(default=timezone.now) def __unicode__(self): return u"{} {}".format(self.uid,self.datetime) class Meta: db_table="userresp" I want to retrieve all "resp" pertaining to the value of a particular uid=3. there are two records in the table userresp with uid=3. How di i do that? -
How can I run Angular 2 application from Django's server?
I need to run angular2 application from django's developement server with google app engine deployment. -
Django MySQL database error passing database query
I am trying to query a MySQL database using Django. I pieced this code together using several sources. Can someone explain what is wrong with how I am passing the query? I would appreciate suggestions or links about how to improve my code as well since I'm new to Python and Django. The error I get is: TypeError: query() takes exactly 1 argument (2 given) My class: (does database connection and displays result in a view) from helloservice.models import Snippet from helloservice.serializers import SnippetSerializer from rest_framework import generics from django.contrib.auth.models import User from helloservice.serializers import UserSerializer from rest_framework import permissions from helloservice.permissions import IsOwnerOrReadOnly from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework import renderers from rest_framework.response import Response from rest_framework import viewsets from rest_framework.decorators import detail_route #sudo pip install MySQL-python class DbConn(): hostname = 'jdbc:mysql://xxxxxx.us-east-1.rds.amazonaws.com:3306' username = 'rrrr' password = 'xxxx' database = 'yyyy' def query(q): myConnection = MySQLdb.connect( host=hostname, user=username, passwd=password, db=database ) cur=conn.cursor() cur.execute(q) return cur class UserViewSet(viewsets.ReadOnlyModelViewSet): conn= DbConn() cur=conn.query('SELECT * FROM pulse.customer WHERE userId = 103') #return cur.objects.values_list('loginName') print(cur.objects.values_list('loginName')) -
Django dynamic form
Please consider the following two models: class Addresses(models.Model): address_id = models.AutoField(primary_key=True) postalcode = models.CharField("Postal Code", max_length=10) parish = models.CharField("Parish", max_length=50) locality = models.CharField("Locality", max_length=50) street = models.CharField("Street", max_length=200, blank=True) def __str__(self): return '%s %s' % (self.locality, self.street) class Meta: ordering = ['postalcode', 'parish', 'locality', 'street'] unique_together = ("locality", “street”) class Members(model.Model): name = models.CharField("Name", max_length=100) postalcode = models.CharField("Postal Code", max_length=10) parish = models.CharField("Parish", max_length=50) locality = models.CharField("Locality", max_length=50) street = models.CharField("Street", max_length=200) block = models.CharField("Number/Block/Apartment", max_length=30) … def __str__(self): return self.name class Meta: ordering = ["name"] I would like to build a Members form that: Limits the choices for postalcode, parish, locality and street to model Addresses distinct choices for each field Does this recursively, meaning that once the user selects the postalcode from the distinct postalcode choices in Addresses the choices for parish, locality and street would be further limited as per Addresses key. When the user makes the second choice the options in the other two would be further reduced and so on. Does this to the point when the user selects both locality and street (unique_together in Addresses), and the choices for postalcode and parish would be completed (if not yet selected). The street field should remain … -
How to use existing pure Python 3.6 project to implement as Django site?
I have a Python 3.6 project and it mostly does processing stuff. My program/script takes only one input in the terminal and that's it for a user-end. After all processing, it simply outputs a text file, which is again what I want. I want to know a proper styling to arrange my Django project, how to use existing project files and also strategy for user-input from Django web app. Again, let me be clear, in my project user inputs something from the terminal and program outputs a text file. I hope I am pretty clear. -
Filtering Geodjango Results using Function Based Views
Currently, the webpage displays a list of found results sorted by distance (similarly to the ListView). What I would like to do is to create a filter to further narrow down these results. Views.py def teacher_list(request, **kwargs): if request.method == 'GET': form = LocationForm(request.GET) if form.is_valid(): SearchPoint = Point(form.cleaned_data['Lng'], form.cleaned_data['Lat']) Radius = form.cleaned_data['SearchRadius'] Type = form.cleaned_data['Type'] else: form = LocationForm() SearchPoint = Point(0, 0) Radius = form.cleaned_data['SearchRadius'] else: form = LocationForm() SearchPoint = Point(0, 0) Radius = form.cleaned_data['SearchRadius'] results = Teacher.objects.filter(location__distance_lte= (SearchPoint, D(km=Radius)))\ .annotate(distance=Distance('location', SearchPoint))\ .order_by('distance') return render(request, "users/teacher_list.html", context={"form": form,"teacher_list":results,}) Currently filtering works, but not for categorical variables. For example, if I change the location or search radius, the form is updated and I see new results. However, I have a categorical variable called TYPE which can be either FREE or PAID. If a person selects a FREE filter, only show results which are free and vice versa. These are boolean fields in my model. class Teacher(models.Model): free = models.BooleanField() paid = models.BooleanField() What I tried adding is some sort of filter parameter that will work similarly to if Type == 'Free': filter_variable = 'free=True' elif Type == 'Paid': filter_variable = 'paid=True' else: filter_variable ='' new_result_set = results.filter(filter_variable) Is … -
How to create csv file and save to file filed in django model?
I'm using django csv (https://docs.djangoproject.com/en/1.11/howto/outputting-csv/) and i want to save generated csv file to file field in below model class CsvDoc(models.Model): csv_file = models.FileField( upload_to="path") -
Django - How to connect citrix sharefile to django server?
I'd like to connect citrix sharefile to django server. I am looking for a document but I can't find it. When the django server get a request, it should find a file from citrix sharefile and get it. At the end of the processing, the django server send a modified file to citrix sharefile and save it. Is it possible? -
Django update_or_create in bulk
Does Django have any bulk function to update_or_create? Let's say I want to update the 'last_emailed' time of 10,000 users, but LastEmailed may also not exist for a specific user so it is update_or_create. Or must I resort to raw SQL? My database is postgresql. -
Two breakpoints, but one reacted
views.py class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form = StatisticsBaseForm() def home(request, template_name): import ipdb; ipdb.set_trace() redirect_url = request.GET.get('period') def get_context_data(self, **kwargs): import ipdb; ipdb.set_trace() context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ 'applications_by_state': ApplicationsByState(), 'applications_calendar': ApplicationsCalendar(), 'new_customers_calendar': NewCustomersCalendar(), 'statistics': Statistics(), 'form': StatisticsBaseForm(), }) return context urls.py urlpatterns=[ url(r'^$', login_required( StatisticsIndexView.as_view()), name='index'), ] I put a breakpoint in the home() and get_context_data() method, but it stopped only in the get_context_data(). Why don't I have any results in home() method?