Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store multiple Values in one session variable in django
I want to store college IDs in a session variable that each ID should get stored in same session. i want it when user click on ADD button. so whenever the ADD button would be clicked that ID Should get stored in choice session variable. here is what i have tried. views.py def my_choices(request, cid): # when user is making the choices clg = college.objects.all() title = "Choice Filling" page = "Choice Filling" stud = student.objects.get(id=request.session['id']) clgid = college.objects.get(id=cid) choice_list = [] if stud.isactive != 1: messages.error(request, "Your registration process is incomplete.") else: choice_list.insert(len(choice_list), clgid.name) print(choice_list) request.session['choices'] = choice_list return render(request, 'college_list.html', {'cid': cid, 'clg': clg, 'title': title, 'choice':choice_list}) models.py class college(models.Model): name = models.CharField(max_length=50) password = models.CharField(max_length=10) institute_code = models.IntegerField(unique=True) class student(models.Model): fullname = models.CharField(max_length=50) password = models.CharField(max_length=10) email = models.EmailField(unique=True) I want to store cid for every click in choice_list but it's not storing multiple values, instead it overrides the previous value and store new every time. i tried choice_list.insert(..) also but nothing happens. -
Django how to allow user to set paginate_by value in profile
I allow my users to update their profile and set the paginate_by value for various ListView pages. How do I access this value within my view? Currently, the default is 20 as shown: class CandidateListView(LoginRequiredMixin, ListView): template_name = 'recruiter/candidate_list.html' context_object_name = 'candidates' paginate_by = 20 Instead of 20, I want to access that field in their profile. Do I need to pass it to view as parameter? Thank you. -
how to pass a JavaScript variable to Django views
I'm new to Django and HTML. i have a code like below: ... <script> var cars = ["Saab", "Volvo", "BMW"]; </script> ... I need to pass the var (["Saab", "Volvo", "BMW"]) to my Django view. -
How to assign users to groups in Django?
I have created a custom Users model by inheriting AbstractBaseUser and PermissionMixin. I am able to add users to this model but I also want to assign a custom group to each user at the time of creation. I have created two custom groups in Group model of auth application (database table name - auth_group). As I have used AbstractBaseUser and PermissionMixin to use the default authentication of Django, it has created a new database table to define relations between Users and Group with the name users_and_auth_users_groups (the table name has the extension of my app name i.e users_and_auth). This table has 3 fields id as Primarykey, user_id as (MUL), and group_id as (MUL). How would I be able to add the records to this database table from the APIView. Saving an instance to the model can be achieved like this - model.objects.create() In above case I am aware of the model class and I am also aware of the manager class object i.e objects and it's method i.e create. But in case of database table users_and_auth_users_groups I am not even aware of model and its manager class object and methods. I have tried to look for the solution almost … -
Django React Build fails with Uncaught SyntaxError: Unexpected token '<' Error
I am new to the React/Django community. I am trying to build my first application. Everything works fine in my local instance. But when I make the build and push the code to Heroku, I get the below error. Uncaught SyntaxError: Unexpected token '<' in couple of JS files. Manifest: Line: 1, column: 1, Syntax error. in mainfest.json I have the code in this git repo https://github.com/gowda-nirmal/DjangoReactApp and here is the heroku application path for reference https://the-djagno-react-app.herokuapp.com/ Request your assistance in this matter. Thanks in advance. -
KeyError while search for items from database Django 3
While trying to search for books on a Django app, I get KeyError. There are no book records in the database. def search(request): """Book search based on authors, and/or publisher, and/or title, and/or subject""" if request.method == 'GET': # create a form instance and populate it with data from the request: form = SearchForm(request.GET) # print (request.GET['search_value']) isbn_list_of_dicts = [] # check whether it's valid: if form.is_valid(): temp_dict = {} # Gets the search values, which is determined by what the user has typed into search bar search_values = form.cleaned_data['search_value'].split(" ") search_values = list(filter(None, search_values)) #print ("Search form") #print (search_values) # calls the query function to get list of dictionaries of book data isbn_list_of_dicts = query(search_values, 'all') # No such results could be found if len(isbn_list_of_dicts) == 0: return render(request, 'bookstore/search_results.html', {'books': request.session['isbn_list_of_dicts'], 'status': 'No results could be found :('}) request.session['isbn_list_of_dicts'] = isbn_list_of_dicts request.session.modified = True return render(request, 'bookstore/search_results.html', {'books': request.session['isbn_list_of_dicts'] , 'status': 'Search results for "%s"'%(' '.join(search_values))}) # Filters the search results by author def search_filter_author(request): return render(request, 'bookstore/search_filter_author.html', {'books': request.session['isbn_list_of_dicts']}) # Filters the search results by year def search_filter_year(request): return render(request, 'bookstore/search_filter_year.html', {'books': request.session['isbn_list_of_dicts']}) Stack trace: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/bookstore/search/?search_value=Dan+Brown Django Version: 3.0.2 Python Version: … -
Django models - Circular-Import-Issue
My Django-Project uses Three Apps, chat, user, sowi. Every App having models structured in the following way. I'm getting an error when starting the Server, i think it is because i have circular Imports. How do i fix this issue? chat/models.py from user.models import User class Chat(models.Model): name = models.CharField(max_length=100, default="private") class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.ForeignKey(Chat, on_delete=models.CASCADE) user/models.py from chat.models import Chat from sowi.models import Sowi class User(AbstractUser): chats = models.ManyToManyField(Chat, blank=True) subscriptions = models.ManyToManyField(Sowi, related_name="subscriptions", blank=True) memberships = models.ManyToManyField(Sowi, related_name="memberships", blank=True) blocked = models.ManyToManyField("self", related_name="blocked", blank=True) sowi/models.py from chat.models import Chat, Message from user.models import User class Sowi(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) chat = models.OneToOneField(Chat, blank=True, null=True, on_delete=models.CASCADE) Error Message: File "*/sowi/models.py", line 9, in <module> from chat.models import Chat, Message File "*/chat/models.py", line 4, in <module> from user.models import User File "*/user/models.py", line 5, in <module> from chat.models import Chat ImportError: cannot import name 'Chat' from 'chat.models' Thanks in Advance! -
Probem Making Migrations Django
everyone. I am having a problem when trying to makemigrations. My code is: start_date = models.DateTimeField(auto_now_add=True) The error is: You are trying to add a non-nullable field 'category' to item without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt Thank you for your help. -
AWS EB Error IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found
Hi I am trying to deploy a DJango site and publishing it through AWS Elastic Beanstalk The main problem is that apparently I have no MSSQL driver installed. I am pretty new to Aws EB so my head is exploding. All my project deploys well, except the MSSQL part. NOTES My MSSQL DB is external, not in RDS I've been trying with pyodbc but when i look at the logs I only see ['PostgreSQL', 'MySQL'] when i do pyodbc.drivers(). In my local machine Windows it works, and in my local MAC it also works ** MY CONTEXT ** -Python 3.6 running on 64bit Amazon Linux/2.9.6 -Django, I've tried 2.1, 2.2, 3.0 Can anyone help me, -
Django - adding multiple files
I am trying to add multiple files to a post object using Djang and jQuery, however, it seems that my files are not added successfully. I am not getting my errors however, t=it seems that my jQuery and views are not handling the files properly. My intention is to link every image uploaded to the post being created but this does not happen. Below are my views for uploading images and creating a post. @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): for image in request.FILES.getlist('files'): instance = Images(post=Post.objects.get(),image=image) instance.save() post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) class PostImageUpload(LoginRequiredMixin, View): def get(self, request): images = Images.objects.all() return render(self.request, 'home/posts/post_create.html', {'images':images} ) def post(self, request): data = dict() form = ImageForm(self.request.POST, self.request.FILES) if form.is_valid(): image = form.save(False) image.save() data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url} else: data['is_valid'] = False return JsonResponse(data) below is my javascript code for uploading files: $(document).ready(function(){ $(".js-upload-images").click(function () { $("#fileupload").click(); }); $("#fileupload").fileupload({ change : function (e, … -
how can i made curves (temperature, pressure, humidity ...) through data in a database using python
I want to make curves (temperature, pressure, humidity ...) through data in a database using python. I already used python-matplotlib to draw curves but I have stored values in a database, so how can I get them into a curve. import matplotlib.pyplot as plt plt.title("vitesse") plt.plot([0,5,7,15,20,25,30,45,50,55], [15,20,90,300,700,500,80,40,12,5]) plt.xlabel('label 2') plt.ylabel('Label 1') plt.show() -
unable to display image inside folder django
i am unable to display image in my webpage when i add notes tried several ways by looking similar questions but i couldn't help me so note.html <div class="container"> <div class="row"> {% for sticky in Notes %} <div class="col-md-3"> <div class="box"> <article class="media"> <div class="media-left"> <i class="glyphicon glyphicon-bookmark"></i> </div> <div class="media-content"> <div class="content"> {% if Notes.img %} <img src="{{sticky.img.url}}" class="img-responsive" /><br/> //tried Notes.img.url and also Notes.img.url {% endif %} <b>{{sticky.Title}}</b><br /> {{sticky.text}} </div> </div> <div class="media-right"> <a href="{% url 'del_note' sticky.id %} " <button class="glyphicon glyphicon-trash"></button> </a> </div> </article> </div> </div> {% endfor %} </div> </div> settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) below is my folder structure models.py class Note(models.Model): Title = models.CharField(max_length=100) text = models.TextField(max_length = 250) img = models.ImageField(upload_to='pics',height_field=None, width_field=None, max_length=100,blank=True, null=True) created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name = ("Note") def __str__(self): return self.text in the image source(src) field tried Notes.img.url and also Notes.sticky.img.url but in vain Thanks in advance -
Vertical alignment of text in Django form widget
I have a multi-line input field in my form. The text is aligned in the middle, but I want it aligned to the top. My form: class FeedbackForm(forms.ModelForm): submitter = forms.CharField(max_length=100, help_text="Name") sub_email = forms.EmailField(help_text="E-Mail Adresse (wird nicht veröffentlicht.)") sub_date = forms.DateField(disabled=True, help_text="Datum", initial=date.today()) content = forms.CharField(max_length=500, help_text="Text", widget=forms.TextInput(attrs={'vertical-align': 'top'})) My template: <form id="category_form" method="POST"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <table> <tr> <td><strong>Datum</strong></td> <td>{{ form.sub_date }}{{ form.sub_date.errors }}</td> </tr> <tr> <td><strong>Name</strong></td> <td>{{ form.submitter }}{{ form.submitter.errors }}</td> </tr> <tr> <td><strong>E-Mail</strong></td> <td>{{ form.sub_email }}{{ form.sub_email.errors }}</td> </tr> <tr> <td><strong>Text</strong></td> <td>{{ form.content }}{{ form.content.errors }}</td> </tr> </table> <p><input type="submit" name="submit" value="Save" /></p> </form> I'm trying to pass the CSS style in the attrs attribute of the widget, as described in the Django docs. But my text is still aligned in the middle. What am I doing wrong? -
How to start developing web apps with django
I have fallen in love with django and I want to learn how to develop web apps with django,how can ibgo about it -
calculate salary and tax deductions on js involving django
So I'm trying to calculate kenyan salary on a django framework, involving some js. I have prepared my code and tested it on the js file...it works! But when I link it to my html file and run django server, it doesn't seem to work. Please help me figure out the problem. I've included only the html and js code. function net_pay(basic_pay, benefits, insurance){ var basic_pay = document.getElementById("gross_salary").value; //"Please enter basic/gross pay: " var benefits = document.getElementById("benefits").value; //"Please enter housing allowance: " var insurance = document.getElementById("insurance".value); //"Amount of insurance premiums paid by the company: " var gross_pay = basic_pay + benefits; // Calculate Payee function payee(basic_pay){ // defined fixed tax for each level var tax_for_level_1 = 12298 * 0.10 var tax_for_level_2 = 11587 * 0.15 var tax_for_level_3 = 11587 * 0.20 var tax_for_level_4 = 11587 * 0.25 // define amount to deduct after each level var deduct_for_level_1 = 12298 var deduct_for_level_2 = 12298 + 11587 var deduct_for_level_3 = 12298 + 11587 + 11587 var deduct_for_level_4 = 12298 + 11587 + 11587 + 11587 // calculate tax for level 1 Up to 12,298 if (basic_pay <= 12298){ return tax1=basic_pay* 0.1 }// Calculate tax for level evel 2 (12,299 - 23,885) else … -
trying to pass one page data to next page but unfortunately data is not displayed
i am working in Django quiz project i am trying to display the answer the next page but using question.html user can select answer and click submit then next page is displayed but marks is not displayed i am use java-script to displayed marks... how can we solve the problem ?? question.html <!DOCTYPE html> <html> <head> <title></title> {% load static %} <script src="{% static 'JS/quiz1.js' %}"></script> </head> <body> <div id = "txt"></div> <form name="quizform" action="{% url 'answer' %}" method="POST" onsubmit="return submitanswer(answers=[{% for poll in questions %}'{{ poll.right_ans }}', {% endfor %}])"> {% csrf_token %} {% for poll in questions %} <h1>{{poll.question_id}}{{poll.question}}</h1> <h3><input type="radio" name="poll{{poll.question_id}}" id="poll1a" value="{{poll.option_1}}" >a.{{poll.option_1}}</h3> <h3><input type="radio" name="poll{{poll.question_id}}" id="poll1b" value="{{poll.option_2}}">b.{{poll.option_2}}</h3> <h3><input type="radio" name="poll{{poll.question_id}}" id="poll1c" value="{{poll.option_3}}">c.{{poll.option_3}}</h3> <h3><input type="radio" name="poll{{poll.question_id}}" id="poll1d" value="{{poll.option_4}}" >d.{{poll.option_4}}</h3> {% endfor %} <input type="Submit" value="Submit Answer" onclick="passvalues();" > </form> </body> </html> answers.html <!DOCTYPE html> <html> <head> <title>Result</title> <script type="text/javascript"> document.getElementById('maitrik').innerHTML=localStorage.getItem('textvalue'); </script> </head> <body> congretulations!.. <span id="maitrik">Hello</span> </body> </html> quiz1.js function submitanswer(answers) { var total = answers.length; var score = 0; var choice=[] for(var i=1;i<=total;i++) { choice[i]=document.forms["quizform"]["poll"+i].value; } for(i=1;i<=total;i++) { if(choice[i]== null || choice[i] == ''){ alert('you missed questions:'+i); return false; } } //var right_answer=["a","a","a","a","a","a","a","a","a","a"] for(i=1;i<=total;i++) { if(choice[i] ==answers[i-1]){ score=score+1; } console.log(answers[i]); } var results=document.getElementById('results'); results.innerHTML="<h3>Your scored … -
Why Django DoesNotExist Erase other objects?
I'm facing an issue with Django and specially the use of DoesNotExist. In my script, I'm trying to check if 'Scrapper' object exist or not, if it doesn't the object is created. For checking if it exist or not i'm using a 'try catch Model.DoesNotExists', .get() with two parameters the first one is an IDs and the last the User object. The issue is rising when two Scrapper object has a same ids but different user's, the first one 'Scrapper' is created and the second erase the first one. try: a = Scrapper.objects.get(id_lbc=ids, user=user) except Scrapper.DoesNotExist: a = Scrapper( id_lbc=ids, lbc_name=title, lbc_url=url, lbc_image=image, lbc_price=price, lbc_date=date, lbc_city=city, lbc_price_meter=price_meter, user=user, token_url=token, customer=customer, has_phone=phone, ) a.save() What I want is create two Scrapper object with same 'ids' but different User's for example Scrapper N°1 ids = 1234567 user = Nico(object) Scrapper N°2 ids = 1234567 user = Paul(object) I thought with the User object given, the Django query can see the difference between two Scrapper object but I misunderstood something... Thanks for the help -
Django query for multiple Group By
Table_A id name city 1 A USA 2 BB UK 3 CC USA Table_B id house_color 1 RED 2 Blue 3 Green i want to group by both the tables in Django So the result can be. [ { "city": "USA", "RED": 1, "Green": 1 }, { "city": "UK", "Blue": 1 } ] so far i have done this Table_B.annotate(city=F('Table_A__id')).values("city","house_color").annotate(Count('house_color'))) can anyone please help me to get the desired result Thanks. here id is foreign key. -
Save all i18 strings in single .po file
Is there a way to create single django.po for one language from all apps inside the project in BASE_DIR/locale or at least put .po file in BASE_DIR/app_name/locale? -
Logged in user has a different id than that of the same user in django database
I am trying to create a todo note application using django,sqlite database, when a user try to register into my app,he is assigned by an id by django by default,but when i try to retrieve/get information of that user using request.user.id it returns a different id than that of actual id.Example, a user is registered in my site by a name 'honey', the django sqlite shows his id as '12' but when i try to get it by request.user.id then its raising an matching query does not exist error. views.py def newNotePage(request): form = NewNote user = request.user print(user) #prints 'honey' print(user.id) #prints '13' cus = NotesModel.objects.get(id=user.id) print(cus) # raises - NotesModel matching query does not exist. if request.method == 'POST': form = NewNote(request.POST) if form.is_valid(): # cus = NotesModel.objects.get(id=user.id) # cus.notes_set.create(notesOf=user) form.save() return redirect('welcome') context={'form':form} return render(request,'todoapp/new_note.html',context) models.py class NotesModel(models.Model): userFromModel = models.OneToOneField(User,null=True,on_delete=models.CASCADE) name = models.CharField(max_length=100,null=True) def __str__(self): return self.name class Notes(models.Model): notesOf = models.ForeignKey(NotesModel,null=True,on_delete=models.SET_NULL) title = models.CharField(max_length=100,null=True) description = models.TextField(null=True,blank=True) created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.title) console output or server log django database -
django urls doesn't work on a distant server
my_project.urls from django.contrib import admin from django.urls import path from django.conf.urls import include, re_path from django.conf import settings from django.http import HttpResponse from machina import urls as machina_urls from allauth.account import views def empty_view(request): return HttpResponse("Empty View") urlpatterns = [ # path('', empty_view, name='empty_view'), path('admin', admin.site.urls), re_path(r'^account/', include('allauth.urls')), # path('', include('allauth.urls')), # re_path('^', include('allauth.urls')), I tested all the above possibilities. On my computer, localhost:8000/account/login/ is just fine. On a distant server (PlanetHoster), my_domain/my_app/ says : Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order: admin ^account/ /my_domain/my_app/account/ says : Using the URLconf defined in my_app.urls, Django tried these URL patterns, in this order: signup/ [name='account_signup'] login/ [name='account_login'] logout/ [name='account_logout'] The empty path didn't match any of these /my_domain/my_app/account/login return to the homepage of my_domain. And in settings.py LOGIN_URL = 'account/login' LOGIN_REDIRECT_URL = '/projects/project/' ACCOUNT_LOGOUT_REDIRECT_URL = "/account/login" ACCOUNT_EMAIL_REQUIRED = True # ACCOUNT_EMAIL_VERIFICATION = "optionnal" I test with the empty_view in the urls, with Application URL : my_domain/my_app/account/login on the server, it works. -
Submitting a Django form and returning a JsonResponse?
Im working on some API views, created with pure Django, which I have never done before. I am testing with Postman, and running into some issues. I need to be able to post form data, and convert it to JSON. My view def buyer_offer_api(request): if request.method == 'POST': form = BuyerForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() data = form.cleaned_data return JsonResponse(data, safe=False) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False) else: form = BuyerForm().fields return JsonResponse({'form': list(form)}) Now, testing a POST request on postman, using raw json data, I am getting a 404. Basically saying nothing has been filled out? -
bootstrap : cards in a for-loop
I try to use Cards from Bootstrap to show some information from different stocks in a database. I'm using DJANGO's template engine and already have the code below. On a desktop, after three cards a new row is showed but there is no space between the first and second row. When showed on mobile, all the cards are underneath eachother, but again with no space between. How can I add some extra space between the cards? <div class="container"> <div class="row"> {% for security in securities %} <div class="col-sm-4"> <div class="card" style="width: 18rem;"> <img src="{% static "public/engie.jpg" %}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ security.name }}</h5> <p class="card-text">Text here</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">{{ security.quote }}</li> <li class="list-group-item">{{ security.lastchange_pct }}</li> <li class="list-group-item">{{ security.remarks }}</li> </ul> <div class="card-body"> <a href="#" class="card-link">Card link</a> <a href="#" class="card-link">Another link</a> </div> </div> </div> {% endfor %} -
TypeError: '<' not supported between instances of 'method' and 'method' [closed]
I have a model form wherein I want the values in the drop-down to be sorted in alphabetical order based on name, however, because of method(get_full_name) I am unable to sort it. Snippet of my Model form: class AwardForm(forms.Form): def __init__(self, user=None, award_id=None, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(AwardForm, self).__init__(*args, **kwargs) if user and award_id: receivers = get_user_model().objects.select_related('employee'.filter(employeeemployee__user=user).exclude(id=user.id).distinct('id') self.fields['receiver'].choices = [('','--Please Select--')]+ sorted([(receiver.employee.id, receiver.get_full_name) for receiver in receivers], key=lambda name: name[1]) self.fields['sender'].widget.attrs['value'] = user.get_full_name() And my model is: class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.get_full_name() -
Django upload form for logo into BinaryField
I have a MySQL table with languages, and want to have a flag field next to every single language. This is an existing situation that I'm trying to convert from a different language into Django. This is the model I have for my languages: class Language(models.Model): language = models.CharField(primary_key=True,unique=True, max_length=8) description = models.CharField(max_length=35) flag = models.BinaryField(editable=True, blank=True, null=True) class Meta: db_table = 'language' verbose_name_plural = "language" def __str__(self): return self.description I already managed to display the flags in my list view. But I also want to have an upload function in my form, but I'm not able to figure this out. forms.py class LanguageForm(forms.ModelForm): class Meta(): model = Language fields = '__all__' widgets = { 'flag': forms.FileInput() } views.py class CreateLanguageView(LoginRequiredMixin,CreateView): login_url= '/login/' redirect_field_name = 'app/language_list.html' form_class = LanguageForm model = Language def form_valid(self, form): if form.is_valid(): data = form.cleaned_data self.object.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('language_list')