Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make a ForiegnKey to an unknown model in django
I'll illustrate by example I have class Stone(models.Model): # name, color, whatever class Member(models.Model): # whatever class Image(models.Model): stone = models.ForiegnKey(Stone, on_delete=...) # this should have the model that needs images image = models.ImageField() I'm using a foriegnKey to the Image model to make multiple images, But This forces me to create an Image model for each Model, In my example, Stone can has multiple images right? I want Member and all my models that need images to use the same class, I want to make only one images table. I've been searching for a while but I don't think I know what should be the search text, I read about ContentType but I don't think I understand what it does and I don't even know if it's the what I'm asking for. -
How to implement multi-tenancy with custom user model?
I'm trying to create a multi-tenant application where authentication happens through the django default user model. I've used my own custom user model. I want to use same database with multiple schemas. User Model class UsersManager(BaseUserManager): def create_user(self, username, password=None, **kwargs): if not username: raise ValueError('Users must have a valid username.') if not kwargs.get('email'): raise ValueError('Users must have a valid email.') if not kwargs.get('contact_number'): raise ValueError('Users must have a valid contact number.') account = self.model( username=username, email = kwargs.get('email'), contact_number=kwargs.get('contact_number'),first_name=kwargs.get('first_name'),last_name=kwargs.get('last_name') ) account.set_password(password) account.save() return account def create_staffuser(self, username, password, **kwargs): account = self.create_user(username, password, **kwargs) account.is_admin = False account.is_superuser = False account.is_staff = True account.is_agent = False account.save() return account def create_superuser(self, username, password, **kwargs): account = self.create_user(username, password, **kwargs) account.is_admin = True account.is_staff = True account.is_superuser = True account.is_agent = False account.save() return account def create tenant_user(self, username, password, **kwargs): """Custom command to create a tenant user""" ... ????????????????????? class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50, default=None, null=True) middle_name = models.CharField(max_length=50, default=None, null=True) last_name = models.CharField(max_length=50, default = None, null=True) username = models.CharField(unique=True, max_length=50) email = models.EmailField(unique=True) street_address = models.CharField(max_length=150) city = models.CharField(max_length=50) contact_number = models.CharField(max_length=40) alternative_contact_number = models.CharField(max_length=40,default=None, null=True) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) objects = UsersManager() USERNAME_FIELD … -
Modeling a 2D Table in PostgreSQL (Django)
So I'd like to model a 2D table in PostgreSQL, and by 2D I mean I'd like to add/update/delete both rows and columns. Before I really get into the details I wanted to convey that I did look into dynamic Django models such that I could extends models and add columns during runtime but to be honest it does seem like kind of a hack job, and none of those packages have good docs or is maintained as of now for the latest version of Django and Python. NoSQL is kinda a stretch to switch too this late in the game and eliminates many of the useful features of Django such as the ORM and model integration with DRF. For example in this table, I have some required fields such as firmware name to which I might add publish date or build number or something of the sort. But I also have column headers which may be added or removed as new software versions are released, for example 4.0.1. Is there such a way of modeling this to optimally create a CRUD API that avoids unnecessary redundancy? As of now, I basically have the following models, but of course storing … -
How to get current page number of pdf document which is rendered using <embed> tag in html?
I am rendering a simple html template in my Django project and I want to dynamically know which page the user is reading currently. Is there any way to get that information, and then use it at the backend. -
How to keep getting http data in flutter?
I am currently creating a location tracking application. It contains a backend where lat and long is stored. So how can my flutter application keep getting the data from the server in certain intervals using http in flutter? -
Nontype error while iterating json in djagon template
I need to iterate json in my django template. I receive nontype error while attempting to do this. the JSON object must be str, bytes or bytearray, not NoneType context["reserved"] = json.dumps(reserved, sort_keys=True) return render(request, 'users_templates/reservations.html', context) {% for date,time in reserved.items|loadjson %} <tr> <td>{{forloop.counter}}</td> <td>{{date}}</td> <td>Pitt</td> <td>35</td> <td>test</td> </tr> {% endfor %} -
How do I create comment which is automatically is related to model
I need to set comment which is automatically related to the Article model when created article list article comment article list comment model -
Django: can't retrieve variable from my view after AJAX call
After an AJAX Post request, I'm trying to retrieve from my view some list values contained in a variable. The idea is to use these values to populate a dropdown. But my variable seems empty. I thought that it was because I initially used a 'return render()', but even with a 'return HttpResponse()' it doesn't work. This is my views.py: def MyView3(request): if request.method == 'POST' and request.is_ajax: myVariable = ["1", "2", "3", "4", "5"] print(myVariable) return HttpResponse(myVariable) else: return render(request,'home3.html') This is my html code: <form class="wrapper" action="" method="post"> {% csrf_token %} <select name="myVal" class="toChange"> <option val="1">1</option> <option val="2">2</option> </select> <select id="dep" name="dep"> {% for item in myVariable %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <script type="text/javascript"> function dropdownChange () { var selectedValue = $(".toChange option:selected").val(); $.ajax({ type: 'POST', data: {'myVal': selectedValue}, }); var mylist = '{{myVariable}}'; alert(mylist); } $(".toChange").change(dropdownChange); </script> </form> The idea here is to triger the AJAX call when I select a new value in my 'myVal' dropdown. The call works since the view is correctly activated, as 'print(myVariable)' shows the expected result in the console. Moreover, my alert pop-up is displayed. Yet, it is empty. I would need it … -
I am developing a quiz app and trying to recuperate different responses of one question with django
i am developping a quiz app and trying to recuperate deffirent responses of one question with python-django; but it is not working need some help plz this is my views.py, when I try to add different responses of a question; the only one that is inserted is the last one def add_question_form_submission(request): print("hello form is submitted.") Commentaire= request.POST["Commentaire"] questions = request.POST["question"] matiere= request.POST["matiere"] dif = request.POST["dif"] reponses= request.POST["reponse"] comment = request.POST["comment"] flag = request.POST["flag"] ques=question(questionA=questions,explication=Commentaire, difficulte=dif,id_matiere=matiere) ques.save() rep =reponse(response=reponses,commentaire=comment,estVrai=flag,id_question=ques.id_question) rep.save() return render(request,"myblog/questionnaire.html") and this is my template with javascript, i used javascript to add more fields in order to add more responses of a question {% extends "myblog/base.html" %} {% block content %} <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x < max_fields){ //max input box allowed x++; //text box increment $(wrapper).append('<div><input placeholder="reponse" type="text" name="reponse"/> <input placeholder="Comment" align="center" type="text" name="comment"><select name="flag"> <option value=True>Vrai</option><option value=False>Faux</option></select> <a href="#" class="remove_field">Remove</a></div>'); //add input box } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); x--; }) }); … -
how to send the selected value to django?
I trying to implement a search button using ajax and django where I send the selected value the server, but I can't get the selected value from the select HTML tag , the variable value is always empty ({"obj":""}) ?? HTML : div class="col-2"> <label style="color : white;">Title</label> <select name="da" id="da" class="form-control da"> <option selected></option> {% for obj in ds %} <option value="{{obj}}">{{obj}}</option> {%endfor%} </select> <button type="submit" class="btn btn-warning btn-lg search">ajax</button> </div> ajax : var value = $('#da').val(); console.log(value) $(document).ready(function() { $('.search').click(function(){ var csrftoken = $('[name="csrfmiddlewaretoken"]').val(); $.ajax({ type: "GET", url: '/search/ajax/', data: JSON.stringify({'obj' : value}), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, success: function(response) { do somthing ...... }, error: function(rs, e) { alert(rs.responseText); } }); }) }); view.py def filter_ajax(request): if request.method == 'GET': value = request.GET.get('obj') print(value) -
get_object_or_404 not working properly in django
when I attempt to get an object with specific slug it gave me 404 page error, however I've hard coded the slug name and that worked and I've printed the slug field separately and it was the one that I've already tested before. this the view part: def show_category(request, hierarchy=None): category_slug = hierarchy.split('/') category_queryset = list(Category.objects.all()) all_slugs = [x.slug for x in category_queryset] print(all_slugs) print(get_object_or_404(Product, title='benz')) parent = None for slug in category_slug: if slug in all_slugs: parent = get_object_or_404(Category, slug=slug, parent=parent) else: # these 3 lines bellow: print(slug) print(get_object_or_404(Product, slug='benz')) instance = get_object_or_404(Product, slug=slug) breadcrumbs_link = instance.get_cat_list() breadcrumbs_name = instance.get_cat_names() category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_name] breadcrumbs = zip(breadcrumbs_link, category_name) return render(request, "products/product_detail.html", {'instance': instance, 'breadcrumbs': breadcrumbs}) return render(request, "products/products_list.html", {'product_set': parent.product_set.all(), 'sub_categories': parent.children.all()}) and these are Product and Category models: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(allow_unicode=True) parent = models.ForeignKey( 'self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" @property def get_products(self): return Product.objects.filter(category__name=self.name) class Product(models.Model): title = models.CharField(max_length=200) description = models.TextField(verbose_name='desription') slug = models.SlugField() image = models.ImageField(upload_to='product_pics', default='default.jpg') category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) def get_cat_list(self): k = self.category breadcrumb = ["dummy"] … -
Bootstrap : badge over an image instead of under it
I'm trying to put a little badge of colour over an image of a product with Bootstrap. Things were working well but I had to change the image to be of class embed-responsive in order to have the images of all products the same size. And now the badge cannot be seen anymore. I think this is because the badge is now under the image. Any idea how I can solve that ? Here is my code : <div class="list-card-image"> <div class="embed-responsive embed-responsive-16by9"> <div class="star position-absolute" ><span class="badge badge-success">Cuisiné par {{ plat.chef }}</span></div> <a href="{% url 'display' plat.id %}"> <img src="{{ plat.photo.url }}" class="img-fluid item-img embed-responsive-item" width="100%" height="100%"></a> </div> </div> Thanks in advance ! -
Convert postgres (.pgsql) data file to sqlite3 (db.sqlite3) on Ubuntu
I need to convert a postgres file into sqlite3 database file. I already have data in popstgres db. This is related to Django-webapp. Is it possible and if yes, how? -
InlineFormset Factory Dile Upload Form
I am trying to make an inlineforms through django. I have made a model to save the uploaded Image. Unfortunately the image is not getting uploaded through the form. I am not able to track why the image is not getting saved in the folder. models.py - This file contains all the models. class courses(models.Model): name = models.CharField(max_length = 50) class topics(models.Model): name = models.CharField(max_length = 50) sno = models.PositiveIntegerField(default = 0) course = models.ForeignKey(courses,on_delete = models.CASCADE,null = True) class sub_topics(models.Model): name = models.CharField(max_length = 50) content = models.TextField(null = True) sno = models.PositiveIntegerField(default = 0) image = models.ImageField(upload_to=('images/'),blank= True,null = True) topic = models.ForeignKey(topics,on_delete = models.CASCADE,null = True) forms.py - In this file through the inlineformset_factory I have made courses->topics->sub_topics data base structure. The sno is use to store the serial number of the child forms TopicFormset = inlineformset_factory(courses, topics, fields=('name','sno'),extra =1,widgets = {'sno': HiddenInput()}) Sub_TopicFormset = inlineformset_factory(topics, sub_topics, fields=('name','content','sno','image'),extra = 1,widgets = {'sno': HiddenInput()}) views.py - In this file I have used CreateView to display the forms created. While saving the results the Course and Topics are saved but while saving the subtopic only the character input is getting saved. The image is not getting saved Even after … -
Django REST Framework - Reference to the User who added the order
I am creating an application in Django REST Fremework, in which the user can add an order. I would like the serializer to set a reference to the user based on the token and complete the "Client" model field. It's actually works with HiddenField, as shown in the documentation. (Link: https://www.django-rest-framework.org/api-guide/fields/#hiddenfield) class OrderSerializer(serializers.ModelSerializer): client = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Order fields = '__all__' The problem is that when I fetch a single order or list of orders, Client field is of course hidden becouse of HiddenField type. curl -X GET http://127.0.0.1:8000/api/orders/12 { "id":12, "name":"sprzatanie ogrodka", "description":"dupa", "price":"12.20", "work_time_hours":2, "work_time_minutes":50, "workers_needed_num":3, "coords_latitude":"-1.300000", "coords_longitude":"1.100000", "created_at":"2020-03-08T13:20:16.455289Z", "finished_at":null, "category":1, "workers":[] } I would like the field to still capture reference to the logged in user, but at the same time to be visible when returning data from the API. What serializers field type I need to use? Thanks! -
Django models textchoice error while insert value
I'm trying to create a model with choice text as string for postgres varchar(10) models.py from django.utils.translation import gettext as _ from django.contrib.auth.models import User from django.db import models class File(models.Model): users = ( (str(user), str(user)) for user in User.objects.all() ) file_name = models.CharField(max_length=50) file_type = models.CharField(max_length=10) file_upload = models.FileField(upload_to ='uploads/') file_published_date = models.DateTimeField() file_uploaded_by = models.CharField(choices=users) I'm getting error at 'file_uploaded_by': Exception Type: TypeError at /admin/sftp/file/add/ Exception Value: '>' not supported between instances of 'int' and 'NoneType' -
Django static files dont find
i wrote this and my static files don't load my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my urls.py urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) error [08/Mar/2020 16:51:18] "GET /static/bootstrap/bootstrap.min.css HTTP/1.1" 404 1808 thank you in advance -
Images aren't being uploaded in django and showing up error 404
I am a newbie in django and making a trial blog for practice. I am getting an error regarding the images uploaded: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/default.jpg Raised by: django.views.static.serve "E:\Django\boot\media\default.jpg" does not exist the default.jpg is in the correct directory but am still getting this error. Also, if i upload an image, i can view it in django admin page but its not showing up in the actual webpage. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from PIL import Image class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) pic = models.ImageField(default="default.jpg",upload_to="images") title = models.CharField(max_length=200) sub_title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) content = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('detail',kwargs = {'pk':self.pk}) forms.py from .models import Post from django import forms class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','sub_title','content','pic') views.py from django.shortcuts import render from .models import Post from .forms import PostForm from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = … -
API endpoint returns TypeError: 'type' object is not iterable
I am writing a create user API by extending the class users with AbstractBaseUser class. The API was working fine for regular model fields like EmailField, CharField, BooleanField. But then I decided to store the profile_picture of users as well. So I create a new field profile_picture as ImageField to store the path of user's profile picture in the same extended users model. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='Images/', max_length=None, blank=True) is_active = models.BooleanField(default=True) # defing a custome user manager class for the custome user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' Then I updated UserAPIView class to add parser_classes = (FileUploadParser) view.py from django.shortcuts import render from . import views from rest_framework.views import APIView from django.db import IntegrityError from rest_framework import status from . import models, serializers from rest_framework.response import Response from django.core.mail import send_mail from rest_framework.parsers import … -
How to allow users edit thier profile?
I'm new to Django Framework and trying to learning it by making a website which users can post . I want to allow users to edit their profile after registration but the tutorials i found online was not straight forward and complicated . like these two : https://www.youtube.com/watch?v=D9Xd6jribFU https://www.youtube.com/watch?v=CQ90L5jfldw I would appreciate it if someone help me with this Thank you -
Django-sekizai not working despite following the documentation
I followed every step of the documentation to setup my project, but I can`t seem to get it working. Here`s the code: base.html {% load sekizai_tags %} <html> <body> <h1>I`m the base</h1> {% block content %}{% endblock %} {% block js %}{% endblock %} {% render_block "js" postprocessor "compressor.contrib.sekizai.compress" %} </body> </html> test.html {% extends "base.html" %} {% load sekizai_tags %} {% block content %} {% include "include.html" %} {% endblock %} {% block js %}{% addtoblock "js" %} {{ block.super }} <script> alert("Outer") </script> {% endaddtoblock %}{% endblock %} include.html {% load sekizai_tags %} I`m included {% block css %}{% addtoblock "css" %} <script> alert("Inner") </script> {% endaddtoblock %}{% endblock %} When I render that page, I can see Im the baseandIm included. The alert Outer gets fired but not the Inner. What should I do to also let the inner alert fire? -
Why doesn't migration work for foreign key in Django?
so I'm using Django to create a blog. To clarify who the author of an article is, I've added a foreign key in models.py class EachArticle(models.Model): # title, body, and so on userKey = models.ForeignKey(User, default=None, on_delete=models.CASCADE I've done the makemigrations and migrate command, but then I get this error that there is no column named 'userKey_id' in my 'eacharticle' relations. Why does this error occur? and why does it look for a column named 'userKey_id', when the field I added is 'userKey'? + I've checked the table in my Posgres, and realized there is no column named 'userKey', as well as 'userKey_id' apparently. I would very much appreciate your help :) -
Django TemplateSyntaxError: Could not parse the remainder: '"{%' from '"{%'
I am trying to do cycle inside the for loop but it raises error. What is the correct alternative. {% cycle "{% include 'col-1-of-3.html' %}" "{% include 'col-2-of-3.html' %}" "{% include 'col-3-of-3.html' %}" %} Error: TemplateSyntaxError: Could not parse the remainder: '"{%' from '"{%' -
How to update infromation on web page without refreshing the web page in django?
I have a Django model form connected to a MySQL database. Using model_name.objects.all(), I display all the names stored in the database on a different webpage (names = input from the user using Django forms). What I want to do is, when I change the names in the MySQL database it should update on the webpage without refreshing it. I know that I need to send a GET request to the database using AJAX, however, I do not know how to implement it in the code since I do not know JQuery or Javascript. I am also fairly new to Django and learning. Thank you for helping me out. My views.py is def up(request): allmodels = Newmodel.objects.all() context = {'allmodels':allmodels} return render(request, 'up.html', context) My up.html is <body> {% for models in allmodels %} <td> <li> {{models}} </li> </td> {%endfor%} </body> -
'HTTP status code must be an integer' error in Django view
i have small scraping view in my Django website, but i get an error 'HTTP status code must be an integer' in line: 'return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) ' def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' if request.method == 'POST': data = request.POST.get("textfield") if data == '': empty = 'Data is empty' return HttpResponse(request, 'scrapingscore.html', {'empty':empty}) else: data = data.replace(" ", "+") search = link + data + '&x=0&y=0' req = Request( search, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) req = urlopen(req).read() soup = BeautifulSoup( req, features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link return HttpResponse(request, 'scrapingscore.html', {'original_link':original_link}) return render(request, 'scraping.html') I don't know why i get an error 'HTTP status code must be an integer'. I have one argument in dict in this line with error and i don't know how to repair it, i thought it will work but it is not. When user input is blank, i also get this error in line 'return HttpResponse(request, 'scrapingscore.html', {'empty':empty})'.