Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Render An Object In Django Views?
I have a form that accepts URLs. This URL is then being parsed with BS4 and product created with the following class: class Product(models.Model): product_id = models.CharField(max_length=50) pub_date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=255) url = models.TextField() price = models.FloatField() I want to save only unique products to the database. Therefore I added the following code into the add function in the views.py file to check the product by its ID: def add(request): ... product.product_id = soup.find('h1', class_='product-id').text if Product.objects.filter(product_id=product.product_id): return render(request, 'product/add.html', {'error': 'Product already exists'}) else: product.title = soup.find('h1', class_='product-name').text ... product.save() return redirect('/product/' + str(product.id)) Currently, user receives the 'Product already exists' error message. But I want to actually render the already existing product instead. Here is the function for detailed product: def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) return render(request, 'product/detail.html', {'product': product}) The URL to detailed product looks like this: http://example.com/product/22 There is probably a better way to retrieve, compare and then render an object. Please let me know. Thanks in advance! -
Comparing multiple forloop.counter values in templates
I have a homework assignment that wants us to create a gradebook table that will keep the same values entered in prior to hitting submit and I am having trouble actually getting those values set to stay, but I do have the scores for the "assignments" in a table, so I know it can be done but I am just a rookie with django templates and what not. I have tried to do the render method multiple times and loop through this score list but obviously rendering the table multiple times comes with its own issues, and now I am currently trying to loop through the lists of students, assignments, and grades (in probably a very inefficient way) in the Django template, but to get the expected results I would have to have 3 nested loops and only create a table's cell if the index of the outter two loops match certain constraints of the inner loop (see code below). VIEWS.PY: scores = list(models.Grade.objects.all().values_list('score', flat=True)) students = list(models.Student.objects.all().values_list('id', flat=True)) items = list(models.Item.objects.all().values_list('item_name', flat=True)) return render(request, 'main/index.html', {"row": students, "col": items, = "scores": scores}) INDEX.HTML: {% for i in row %} <tr><th>{{i}}</th> {% for j in col %} {% for k … -
Writing a view to allow user to add related data for a customer, like comments for example; on a single page
I have working models, forms, views and urls for a django CRUD app managing customer functions for a business. I just cant seem to figure out how to write a view to allow a user to add comments, or other data related to the customer and stored in other models using a single view and template. So for example; for customer a, all the comments for customer a with the option to add, amend etc.. and the same for the other related models. I understand how to do it for one i will be able to make quick progress. (old school programmer here) Here is what i am working with - keeping it simple. MODELS class Emergency(models.Model): # Fields name = CharField(null = False, blank = False, max_length=60) address = TextField(blank=True, null=True, help_text='Street and town', verbose_name='Address') telephone = CharField(blank=False, null=False, unique= True, max_length=20) relationship = CharField(choices=(('P', 'Parent'),('S', 'Son'),('D', 'Daughter'),('R', 'Relative'),('L', 'Partner')),max_length = 1,default='R') class Meta: ordering = ('-pk',) def __unicode__(self): return u'%s' % self.pk def get_absolute_url(self): return reverse('conform_emergency_detail', args=(self.pk,)) def get_update_url(self): return reverse('conform_emergency_update', args=(self.pk,)) class Client(models.Model): # Fields surname = CharField(null = False, blank = False, max_length=30) name = CharField(null = False, blank = False, max_length=60) # Relationship Fields emergencycontact … -
How do I send data from a JavaScript file to Django?
I'm trying to make a ML webapp that recognizes drawn digits. I've managed to use HTML and javascript to draw on canvas but I need to return this image data back to the main files of Django for the prediction algorithm. I'm able to "console.log" the image pixel data from the javascript file itself but how do I send this back to Django? Here's the code that is used for drawing: window.addEventListener("load", () => { const canvas = document.querySelector('#canvas'); const ctx = canvas.getContext('2d'); console.log("hi!") canvas.height = window.innerHeight; canvas.width = window.innerWidth; let painting = false; function startPosition(e){ painting = true; draw(e); } function endPosition(){ painting = false; ctx.beginPath(); var imgData = ctx.getImageData(0, 0, window.innerHeight, window.innerWidth); console.log(imgData); } function draw(e) { if (!painting) return; ctx.lineWidth = 10; ctx.lineCap = 'round'; ctx.lineTo(e.clientX, e.clientY); ctx.stroke(); ctx.beginPath(); ctx.moveTo(e.clientX, e.clientY); } canvas.addEventListener("mousedown",startPosition); canvas.addEventListener("mouseup",endPosition); canvas.addEventListener("mousemove",draw); }); -
Generate dynamic forms and update database with comma separated values
I am working on a web application for voting and I am trying to generate dynamic forms based on database information. Here's my models.py class ballot(models.Model): title=models.CharField(max_length=100) options=models.CharField(max_length=100) date_posted=models.DateTimeField(default=timezone.now) results=models.CharField(max_length=100) active=models.BooleanField(default=True) I was wondering if it is possible for values in the options field to be stored as a comma separated list such as 'option1,option2,option3' and this would be parsed to generate 3 radio buttons. Similarly, results would be also be a comma separated list that would match up with options, such as '0,0,0' in this case. So if the second radio button was selected and submitted, the results in the database would update to '0,1,0' -
How to fix 'Social Network Login Failure' error of django-allauth deployed on Elastic Beanstalk
I'm using django-allauth plugin to provide Facebook login in my application. The login works perfectly on my machine (localhost:8000) but it gives me this error when I try to login in the online version, deployed on Elastic Beanstalk (AWS): Social Network Login Failure An error occurred while attempting to login via your social network account. I've tried to debug it to get more information following this instructions: Debugging django-allauth Social Network Login Failure, but it gives no useful infromation: {'provider': 'facebook', 'code': 'unknown', 'exception': None} For the plugin configuration I've followed the guidelines provided by the documentation. And I think that everything is correctly configured in the FB app settings (app domain, site url, etc.) A strange thing is that even though the app is configured to work with the online version (set app domain to my real domain and not localhost) it gives me this error when I try the log in from the online version, but it works correctly when I try it from localhost, without changing the FB app settings. -
new models that I add aren't detected in the migrations
I deployed a website on python anywhere. Then I planed on adding an extra model for more functionality. I added that model offline and it works fine but when I made changes to the deployed website the bash console didn't detect any migrations. I thought there was something wrong with the model so I added some sample models to check but even those weren't getting detected when I used python manage.py makemigrations the same happened when I used python manage.py migrate I read up the docs but there isn't a problem with the code -
docker-compose volume won't persist data
I am setting a nginx-gunicorn-django-postgres project with docker-compose. I have a container with postgres and I want to make my data persistent. So for example when I do docker-compose ... start/stop/up/down I want the database to still be there. I have read that I should use volumes for this purpose as in my production.yaml: version: '3.7' services: web: build: context: . dockerfile: docker-compose/django/Dockerfile command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles expose: - 8000 environment: - SECRET_KEY=please_change_me - SQL_ENGINE=django.db.backends.postgresql - SQL_DATABASE=postgres - SQL_USER=postgres - SQL_PASSWORD=postgres - SQL_HOST=db - SQL_PORT=5432 depends_on: - db db: image: postgres:10.5 restart: always volumes: - /home/username/postgres_data:/var/lib/postgresql/data nginx: build: ./docker-compose/nginx volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - 80:80 depends_on: - web volumes: static_volume: media_volume: The problem is that whenever I do docker-compose -f production.yaml stop and then start again, the database is empty except for the migrations :(. I don't know how to tackle this problem. I guess that the container maybe doesn't have permissions to write to the volume? On the other hand when I start containers for the first time everything is working well, everything is in the database and so on. It is only after docker-compose ... stop/down when the database is … -
ProgrammingError while Running migrate Command in Django
I have made some changes to my model, changed a CharField to ArrayField. I am using Django 2 and PostgreSQL 11. Now I am getting an error while running migrate command: django.db.utils.ProgrammingError: cannot cast type jsonb to character varying[] LINE 1: ...MN "msg_list" TYPE varchar(500)[] USING "msg_list"::varchar(... I have googled the topic but I didn't find any solution to the issue. Here is the code for my model: class Sentence(models.Model): sent = models.CharField(max_length=150) msg_list = ArrayField(models.CharField(max_length=500), blank=True, null=True) sent_correct = models.CharField(max_length=300, blank=True) pub_date = models.DateTimeField(default=timezone.now) -
Django: How to update a single object
So I have this calendar website which the user can add events to. They can create a new event to add to the calendar or they can edit current events they have already added to the calendar. However, when they edit an event that has already been added and hit the submit button to post it, it creates a whole new event instead of editing the current one. I'm trying to get it to where when they edit an event that has been added, instead of creating a new event on submit, it edits the current one which they clicked on in the first place . views.py def event(request, event_id=None): if event_id: instance = get_object_or_404(Event, pk=event_id) print(instance) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): event = Event.objects.create(**form.cleaned_data, user=request.user) return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) -
Django executes second request before returning the first one
I am sending two PATCH queries from my front end to Django immediately one after the other. Both queries reach the same django REST framework endpoint (see below). My problem is the order in which things happen. The following code gives me this print: FIRST PATCH: clearing SECOND PATCH HAPPENING FIRST PATCH: after adding references So as you can see, the second patch is being execute in the middle of the first one. Which causes it to return an instance where the references field is empty as it has not been repopulated yet. def partial_update(self, request, pk=None, *args, **kwargs): if 'height' in data or 'pos_x' in data: # do something print("SECOND PATCH HAPPENING") return super(NodeViewSet, self).partial_update(request, *args, **kwargs) reference_ids = request.data.get('references', None) if reference_ids is not None: references = Node.objects.filter(pk__in=reference_ids) instance = self.get_object() print("FIRST PATCH: clearing") instance.references.clear() instance.references.add(*references) print("FIRST PATCH: after adding references") return super(NodeViewSet, self).partial_update(request, *args, **kwargs) Why is this happening? How can I ensure that the Second PATCH doesn't happen in the middle of the first one? -
How to show prices below a certain number?
I made filtration on my website. There are two options. Either to show prices, which are above "min_price" field or to show prices which are below "max_price" (you can choose both). The problem is that "max_price" shows "min_price" and I don't know why. my forms.py code class ProductSort(forms.Form): min_price = forms.IntegerField(label='от', required = False) max_price = forms.IntegerField(label='до', required = False) my views.py code (shows choosing options) form = ProductSort(request.GET) if form.is_valid(): if form.cleaned_data["min_price"]: products = products.filter(price__gte=form.cleaned_data["min_price"]) if form.cleaned_data["max_price"]: products = products.filter(price__gte=form.cleaned_data["max_price"]) -
Django , how to get related objects to post
The problem is simple. I have a func lazy_load_posts(), that through AJAX request append all my model comments to all article the same, but i only need to append related comments to one article . I have tried filter method and prefetch_related , but it did'nt work My view.py Class PhotoDetailView(DetailView): queryset = Photo.objects.select_related('user').prefetch_related('comments', 'comments__user', 'likes') context_object_name = 'photo' template_name = 'photo_detail.html' def get_success_url(self): return reverse('photo_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super(PhotoDetailView, self).get_context_data(**kwargs) comments = self.object.comments.all()[:5] context['comments'] = comments context['form'] = AddCommentForm(initial={'post': self.object.pk}) context['is_liked_by_user'] = self.request.user in self.object.likes.all() return context def lazy_load_posts(request): page = request.POST.get('page') comments = Comment.objects.all() results_per_page = 5 paginator = Paginator(comments, results_per_page) try: comments = paginator.page(page) except PageNotAnInteger: comments = paginator.page(2) except EmptyPage: comments = paginator.page(paginator.num_pages) posts_html = loader.render_to_string( 'comments.html', {'comments': comments} ) output_data = { 'posts_html': posts_html, 'has_next': comments.has_next(), } return JsonResponse(output_data) and my script.js $('#lazyLoadLink').on('click', function() { var link = $(this); var page = link.data('page'); $.ajax({ type: 'post', url: '/lazy_load_posts/', data: { 'page': page, 'csrfmiddlewaretoken': window.CSRF_TOKEN }, success: function(data) { console.log(data) if (data.has_next) { link.data('page', page+1); } else { link.hide(); } $('#posts').append(data.posts_html); }, error: function(xhr, status, error) { } }); }); -
Change request parameters in using custom django middleware
I want to add another field in my POST(JSON) request. The key-value pair has to be "request id". I have concluded that the best way would be to add a generate a random request id and inject it into the request object using middleware. I have written a custom middleware for this. I am getting an error when I try to hit the endpoint. I have tried searching through the internet but haven't found a solution to my error. class SimpleMiddleware: def init(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. req = json.loads(request.body) req_id = random.randint(0,1000000) req["req_id"]=req_id response = self.get_response(req) # Code to be executed for each request/response after # the view is called. return response The error I am getting is 'dict' object has no attribute 'is_ajax'. Can you please help me fix this and if there is an easier and better way to implement this, please let me know. -
How to Use the ArrayField in Django to Store a Python List of Strings
I have read the documentation but I didn't get it. I didn't understand the example code either. I want to store a Python list of strings with ArrayField. Can anyone give me a minimal example of how to store a list with ArrayField? I have googled the topic but I didn't find any tutorial or other material that addressed my use case. class Sentence(models.Model): sent = models.CharField(max_length=150) msg_list = ArrayField(models.CharField(max_length=500), blank=True, null=True) # This field has errors. sent_correct = models.CharField(max_length=300, blank=True) pub_date = models.DateTimeField(default=timezone.now) -
How to transfer Checkbox parameters in Django Materialized view?
The setup contains Django with Materialize view library. Two questions: 1) How to transfer parameters from html to .py -file when using Materialize checkbox? 2) If this works, then how to keep them in a session so that when next time visiting on page, the checkboxes are not empty? I have googled a lot and made many trials with no success. Library: href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" homepage.html: <form action="#"> {% for sites in wsites %} <label > <input type="checkbox" name="option{{sites.id}}" id="option{{sites.id}}" value={{sites.id}}/> <span>{{sites.name}} </span> </label> <br> {% endfor %} </form> views.py def homepage(request): if request.method == 'POST': print(request.POST) return render(request = request, template_name='main/home.html', context = {"wsites":Sites.objects.all }) Session parameters is an empty list, ie. print(request.POST) = []. I would appreciate to get some help how to resolve this. -
Maintain order in one to many relationship in Django
I am trying to maintain the order of a model with oneToMany relationship. How can I achieve a functionality like storing ArrayField of the model? Ordering with timestamp won't work as I would like to reorder. Maintaining another table with foreign key for each model and give another field like 1, 2, 3 will work but it might be too expensive if I am thinking on reordering case. Opinions? -
Object of type 'AuthToken' is not JSON serializable
I'm getting the above error when creating token, here's the code: from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) what am I doing wrong here -
Problem with if form.is_valid(): in Django
I asked about this problem in a previous post, but I made some mistakes in the code while making that post. Here we go again. I'm facing a problem with syntax in Django. The problem is in if form.is_valid(): and I don't know how to solve it. if form.is_valid(): if form.cleaned_data["min_price"]: products = products.filter(price__gte=form.cleaned_data["min_price"]) if form.cleaned_data["max_price"]: products = products.filter(price__gte=form.cleaned_data["max_price"]) -
django application uses elasticsearch to get data
I am having an algorithm that outputs time-series data but not in periodic time (eg. might be now, or in three seconds or four hours). The procedure is clearly asynchronous. From the other hand, I am having a Django application that needs these data to plot them in charts (also updates them in changes). My thought is to follow these steps: Use the algorithm and every time it produces outputs, push them into an elasticsearch index. Create a python script that uses django-elasticsearch-dsl and Searches elasticsearch every 2 seconds and updates my charts. Probably ajax will call Django view and the view will fetch elasticsearch. The thing here is that the time the algorithm produces output is not predefined (eg. it doesn't produce results every one second), so I think that querying elasticsearch every 2 seconds might be stupid. Is there a way to get the data from elasticsearch, every time a new entry appears? Something more asynchronous, rather periodical? Any suggestion? -
custom signup Django allauth form and add is_active field
1- customise django-allauth SignUpForm : i took a look at django allauth documentation and i find this and i will want to know if i need to create a new application and put the form or create the form in my main project, where there is the setting file class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Voornaam') last_name = forms.CharField(max_length=30, label='Achternaam') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() 2- my second question is : I want to when the user creates his account I would like to be turned off "deactivate it" and he can not log in until an administrator allows it. (is it possible to do that with Django allauth ) thanks "I am a Django-newbie ". Help! -
Django - how to create auth system with custom models
django default auth system uses own auth models, but I have created my own model and i want, the auth process happens there My model is : class User(models.Model): Nome = models.CharField(max_length=12) Sobrenome = models.CharField(max_length=12) Nickname = models.CharField(max_length=21,unique=True) Email = models.CharField(max_length=40) Password = models.CharField(max_length=20) Created_Account_Date = models.DateTimeField(auto_now=False,auto_now_add=True) Avatar = models.FileField(blank=True) Number_Following = models.IntegerField(default=0,null=False) Number_Followers = models.IntegerField(default=0,null=False) def __str__(self): return "%s%s" %("@",self.Nickname) I want use it to make auth process , and not django's default -
How do I convert a jupyter notebook file into a html content with all the CSS and javascript of the notebook, NOT with the terminal
I know I can save the jupyter notebook file as a HTML but creates a whole html file which corrupts my page in my web app. I want to be able to pass in a file url from my model into a function using nbconvert and get a html content to pass in my template with all the css and javascript. So I have already tried something which just passes down html without any css or javascript. from django.core.files.storage import default_storage import nbconvert from urllib.request import urlopen import nbformat from traitlets.config import Config from nbconvert import HTMLExporter #this comes from the model which has a filefield called jupyter if content.jupyter.url: html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_file("Adults Income.ipynb") and the body gets passed down to my template which gets rendered fine as a html stand alone, but I need the css and js components of my jupyter notebook. any suggestion would be appreciated. -
angular save() method not working hero tutorial
Following the Angular (using 7.3.4) Hero Tutorial. Using angular with a django backend. I cannot seem to get a hero name to update: I have a hero-detail.component.ts that has a save() method which should update the hero via the HeroService.updateHero() method. When i click the save button nothing happens at all... I am suspicious that the heroService.updateHero method is pointing to the wrong url, but I am not sure where to point it or what to pass it to. Also using Pycharm and put in return this.http.put(this.heroesUrl, hero, httpOptions is red as an unresolved function, but i think this is just a Typescript Pycharm setting that should not matter. Any pointers appreciated. hero-detail.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Hero } from '../hero' import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.scss'] }) export class HeroDetailComponent implements OnInit { constructor( private route: ActivatedRoute, private heroService: HeroService, private location: Location ) {} @Input() hero: Hero; ngOnInit(): void { this.getHero(); } getHero(): void { const number = +this.route.snapshot.paramMap.get('number'); this.heroService.getHero(number) .subscribe(hero => this.hero = hero); } save(): void { this.heroService.updateHero(this.hero) .subscribe(() => this.goBack()); … -
How to submit a HTML5 canvas as an image to django server
I have created a Canvas which can be drawn upon by the user. Now after drawing is done and as i hit the submit button i want it to reach the server in django. I can not figure out the javascript behind this and how to access it in django's views. What is the way of doing it.