Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
image file can not found or does'nt exists in django
my django version is 1.11 i can not display my image file to the page it say media/products/file-name does not exits but i check my MEDIA_URL and MEDIA_ROOT are correct settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,"static_my_proj") ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"workspace/static_cdn","static_root") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"workspace/static_cdn","media_root") urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url from django.contrib import admin from app import views from products.views import (ProductListView, ProductDetailView, ProductFeaturedListView, ProductFeaturedDetailView, ProductDetailSlugView, ) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home_page,name='home'), url(r'^contact/$', views.contact,name='contact'), url(r'^login/$', views.login_page,name='login'), url(r'^register/$', views.register_page,name='register'), url(r'^product/$',ProductListView.as_view(),name='product'), # url(r'^product/(?P<pk>\d+)/$',ProductDetailView.as_view(),name='detail'), url(r'^product/(?P<slug> [\w-]+)/$',ProductDetailSlugView.as_view(),name='detail'), url(r'^featured/$',ProductFeaturedListView.as_view(),name='featured'), url(r'^featured/(? P<pk>\d+)/$',ProductFeaturedDetailView.as_view(),name='fdetail'), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL,document_root = settings.STATIC_URL) urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root = settings.MEDIA_URL) models.py def get_filename_ext(filepath): base_name = os.path.basename(filepath) name,ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance,filename): new_filename = random.randint(1,2324324423) name, ext = get_filename_ext(filename) final_filename = '{new_filename} {ext}'.format(new_filename=new_filename,ext=ext) return'products/{new_filename}/{final_filename}'.format(new_filename=new_filename,final_filename=final_filename) class ProductManager(models.Manager): def featured(self): return self.get_queryset().filter(featured=True) class Product(models.Model): title = models.CharField(max_length = 120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2,max_digits=10,default = 39.99) image = models.ImageField(upload_to=upload_image_path,null=True,default=True) featured = models.BooleanField(default=False) objects = ProductManager() def __str__(self): return self.title > This is the error Page not found (404) Request Method: GET Request URL: https://ecommerce-hk967144.c9users.io/media/products/1299799540/1299799540.jpg Raised by: django.views.static.serve "/media/products/1299799540/1299799540.jpg" does not exist -
How to delete records in django of certain type?
I am basically building a quiz game. I have three types of records stored in database- Question, Answer, Hint. Now I want to add a deletion feature to the answer such that when the user deletes the answer, everything above it right upto the question will be deleted. So a user may ask a question, get few hints and finally get the answer.Then the user chooses to delete the answer and everthing above it upto the last question gets deleted. I know how to delete the last n records last_n = Message.objects.all().order_by('-id')[:10].delete() But this would mean in the last n records, there could be more than one question asked and so both questions could be deleted. My condition needs that keep deleting right from where it is triggered to the latest message of type Question. For now I can only get the message of particular type not upto a particular type Message.filter(type="Question").order_by('-id')[:10] How do I achieve that? -
How to set verbose name for django user defiend admin action
As in django documention here, I wrote my first Django action like this: def make_verified(modeladmin, request, queryset): query_set.update(title='new title') It works pretty right. But I need to change the shown name for this action. currently, the name is shown as below: It means The name of The function which handles the action of this choice. I couldn't find anything about this in the documentation. How can I set verbose for this? Any help will be appreciated. -
join two tables in django admin to get columns for display_list
I am having problem with list_display/joining two table for django admin interface. I want to have columns- program_name and is_active from SchPrograms model with parameter_name, parameter_description from VisVisitParameters model in django admin. I am able to have those columns which i am using with return in each of these models. I tried to take help from the question that already has been asked. But still i could not able to figured this out. class SchPrograms(models.Model): program_id = models.AutoField(primary_key=True) program_name = models.CharField(max_length=200, blank=True, null=True) creation_timestamp = models.DateTimeField(blank=True, null=True) is_active = models.IntegerField() class Meta: managed = True db_table = 'sch_programs' app_label = 'polls' def __str__(self): return self.program_name class VisVisitParameters(models.Model): vparameter_id = models.AutoField(primary_key=True) parameter_name = models.CharField(max_length=300, blank=True, null=True) parameter_description = models.TextField(blank=True, null=True) is_active = models.IntegerField(choices=STATUS_CHOICES) class Meta: managed = False db_table = 'vis_visit_parameters' def __str__(self): return str(self.vparameter_id) app_label = 'polls' class VisVisitParameterMappings(models.Model): vp_map_id = models.AutoField(primary_key=True) vparameter = models.ForeignKey(VisVisitParameters,on_delete=models.CASCADE) program = models.ForeignKey(SchPrograms,on_delete=models.CASCADE) display_order = models.IntegerField(blank=True, null=True) is_active = models.IntegerField() class Meta: managed = False db_table = 'vis_visit_parameter_mappings' app_label = 'polls' def __str__(self): return str(self.parameter_name) model.py class VisVisitParameterMappings_admin(admin.ModelAdmin): list_display = ('program_name','is_active','parameter_name','parameter_description ') -
Can I perform queries in django pre_save signals?
This is models.py class ledger1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys') Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2) Closing_balance = models.DecimalField(max_digits=10,decimal_places=2) class journal(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companyname') Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,) Credit = models.DecimalField(max_digits=10,decimal_places=2) I want to make a mathamatical equation using django queries and the result of my equation will be displayed in the ledger1.Closing_Balance field So I have tried this: @receiver(pre_save, sender=ledger1) def update_user_closing_balance(sender,instance,*args,**kwargs): Closing_balance = ledger1.objects.annotate(debitsum=Sum('Debitledgers__Debit')) + instance.Opening_Balance - ledger1.objects.annotate(creditsum=Sum('Creditledgers__Credit')) instance.Closing_balance = Closing_balance Is it possible in django??? Because if I run this I am getting unsupported operand error... Is there any alternative code for this??? If anyone knows it...Plz help Thank you in advance -
Unable to fetch nested model data with ListAPI View Django Rest Framework
I have a django rest framework app which creates projects structure based on the models. A Project can have multiple sections i.e. section 1, section 2 etc and each section can have only one section info and section question. To avoid creating same columns in different section tables, i created a separate sectionInfo and sectionQuestion model which is linked to projects via foreign key. SectionQuestion and section1,section2 are linked to sectionInfo with onetoonefield. The catch is i want to fetch the details in the format defined in project serializer where section1 and section2 will come with project details and i want the info and question details as part of section1, section2 as json data. My section1, section2 and sectionquestion are connected to project model via sectionInfo model and i want output in reverse as shown below:- { "p_name": "test2", "p_name_full": "test2-2018-09-20", "section1": { ....... "sectionInfo":{.........} "sectionQues":{.........} }, "section2": { ....... "sectionInfo":{.........} "sectionQues":{.........} } } views.py class ProjectListAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = ProjectSerializer def get_queryset(self): return Projects.objects.all() def list(self, request): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) if not serializer.data: return Response({'code': 'empty'}, status=HTTP_200_OK) return Response({'code': 'retrieve_success', 'message': serializer.data}, status=HTTP_200_OK) models.py class Projects(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) p_name = models.CharField(max_length=100) … -
Django; how to test redirect url and template that is set by window.location in js
I'm trying to test url that is set by window.location in js. def test_redirect_after_delete_entry(self): response = self.client.get(reverse_lazy('blog:delete_entry', kwargs={'pk': 1})) self.assertRedirects(response, '/?next=/blog/delete/1', status_code=302) Maybe because it's using ajax, self.assertsTemplateUsed doesn't work well. (The template is not as expected.) ajax part is like this $.ajax({ url:'/blog/delete/' + id, method: 'DELETE', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) }, success: function() { window.location = "http://.../blog/list" }, }) How can I test if it's redirected to correct url and template? Also currently, I'm refering to url like http://... But I'm wondering if I can use namespace in js like Django uses. Anyone could give me tips? -
Is it possible to import/seed data into default User model?
I am new to programming and learning Djano. I have details of many users in a csv file and I want to import all these users in one go to the default User model. This should be dynamic, in future if the admin wants to create bulk users then instead of creating all users manual, he should be able to just import the csv file to create the users. Is this possible in Django? -
Django queryset for foreign attributes
I have to select a result table according to this: Select Session --> Select Course --> Here all student's result will be shown The problem is I cannot query all the specific students attended the course of that session. My model for result: class Course(models.Model): cid = models.AutoField(primary_key=True) class Student(models.Model): sroll = models.IntegerField() class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Session(models.Model): sesid = models.IntegerField(primary_key=True,verbose_name= ('Session')) class Registration(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Assignation(models.Model): reg = models.ForeignKey(Registration, on_delete=models.CASCADE, null=True) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True) class Result(models.Model): asign = models.ForeignKey(Assignation, on_delete=models.CASCADE, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, null=True) ct1 = models.FloatField(null=True, blank=True) My views.py has: @method_decorator(login_required, name='dispatch') class SelectSession(ListView): template_name = 'Dashboard/selectsession.html' model = Session fields = ['sesid'] def get_queryset(self): return Session.objects.all() @method_decorator(login_required, name='dispatch') class SelectCourse(ListView): template_name = 'Dashboard/selectcourse.html' model = Course, Registration fields = ['all'] def get_queryset(self): course = Registration.objects.filter(session_id=self.kwargs['pk']) return course @method_decorator(login_required, name='dispatch') class BatchResult(ListView): template_name = 'Dashboard/batchResult.html' model = Result,Student,Registration,Assignation fields = ['all'] def get_queryset(self): result=Result.objects.filter(???=self.kwargs['pk']) return result -
An invalid form control with name='test' is not focusable
I wrote in forms.py # -*- coding: utf-8 -*- from django import forms from django.core.validators import MaxValueValidator, MinValueValidator class InputForm(forms.Form): test = forms.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(3)],widget=forms.TextInput(attrs={'placeholder': 'input test'})) test1= forms.DateTimeField(widget=forms.TextInput(attrs={'placeholder': 'input test1'})) in top.html {% with form as f %} <form action="{% url 'common:get_data' %}" method="POST"> {% csrf_token %} <section class="main__contents__section js--contentSection" id="section-1" dataNum="1"> <div class="main__contents__section__answer"> <h4 class="selected main__contents__section__answer__title">input</h4> {{ f.test }} <input class="js--goTo disabled" type="button" value="next" dataGoTo="1-1"> </div> </section> <section class="main__contents__section js--contentSection" id="section-1-2" dataNum="1-2"> <div class="main__contents__section__answer"> <h4 class="selected main__contents__section__answer__title">input</h4> {{ f.test1 }} <input class="js--goTo disabled" type="button" value="next" dataGoTo="2"> </div> </section> </form> {% endwith %} When I run the codes,I got an error,An invalid form control with name='test' is not focusable&An invalid form control with name='test1' is not focusable.A web page told me do not use valiation solove this error butI want to use validation.So how should I fix this? -
Anonymous User Error on sending some message in a django chat application
I'm trying to save form data to an anonymous user, however I get the below error when trying to save some data for eg:here its messages. I am not clear what the issue is? ValueError: Cannot assign "SimpleLazyObject: django.contrib.auth.models.AnonymousUser object at 0x03D88350>> models from django.db import models from django.contrib.auth.models import User class Chat(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.CharField(max_length=200) def __unicode__(self): return self.message View from django.shortcuts import render from django.contrib.auth import authenticate, logout, login from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from chat_2 import settings #import time from .models import Chat def test(request): return render(request,'alpha/test.html',{'next': next}) def Login(request): next = request.GET.get('next', '/home/') if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) #WelcomeUser(user) return HttpResponseRedirect(next) else: return HttpResponse("Account is not active at the moment.") else: return HttpResponseRedirect(settings.LOGIN_URL) return render(request, "alpha/login.html", {'next': next}) def Logout(request): #logout(request) #Chat.objects.all().delete() return HttpResponseRedirect('/login/') def Home(request): c = Chat.objects.all() return render(request, "alpha/home.html", {'home': 'active', 'chat': c}) def Post(request): if request.method == "POST": msg = request.POST.get('msgbox', None) c = Chat(user=request.user, message=msg) if msg != '': c.save() return JsonResponse({ 'msg': msg, 'user': c.user.username}) else: return HttpResponse('Request must be POST.') -
TypeError at /password_reset/ django
I try to override default password reset template and got this error: TypeError at /password_reset/ __init__() takes 1 positional argument but 2 were given This is my urls url(r'^password_reset/$', auth_views.PasswordResetView, {'template_name': 'accounts/password_reset_done.html'}, name='password_reset'), -
Apache Http sevrer + Django Application running independent
I have setup, where i have installed three django application and i have configured to Apache Http server with Wsgi.py file. whenever i want to make changes to one App in django then i want to restart whole Apache http server, result in it will affect the remaining two django application. is it possible to start or stop django app from apache http server independently. -
Update Average and Total in a table Django
I am creating a result management program. I need to find Average from the best 3 marks input out of 5 (CT1 to CT4, Assignment) or less. If less than 5 marks are input, it will ignore the null columns. also if less than three are input, it will dummy the 3rd one with the average of the given two inputs and then calculate the average. Single input will show that marks directly in average. Finally the average and attendance marks will be sum in total. My Model is: class Result(models.Model): asign = models.ForeignKey(Assignation, on_delete=models.CASCADE, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, null=True) ct1 = models.FloatField(null=True, blank=True) ct2 = models.FloatField(null=True, blank=True) ct3 = models.FloatField(null=True, blank=True) ct4 = models.FloatField(null=True, blank=True) asn = models.FloatField(null=True, blank=True) avg = models.FloatField(null=True, blank=True) atd = models.IntegerField(null=True, blank=True) total = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.asign.reg.session) + ' - ' + 'IT-' + str(self.asign.reg.course.cidn) + ' - ' + self.student.snam views.py: class FindStudentresult(ListView): template_name = 'Dashboard/findStudentresult.html' model = Result,Student,Registration,Assignation fields = ['all'] def get_queryset(self): result=Result.objects.filter(student=self.kwargs['pk']) return result def totals(self): avg = -
MySQL prepared statement produces error with Django, but works in command line
MySQL table has 3 columns - region, month and revenue with values like this Table structure I have written a query which groups revenues by month for each region SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT("SUM(CASE WHEN region = ", QUOTE(region)," THEN revenue ELSE 0 END) AS ", CONCAT('`', region, '`'))) INTO @sql FROM (SELECT * FROM TABLE1 WHERE region IS NOT NULL AND region <> '') RTD; SET @sql = CONCAT("SELECT DATE_FORMAT(month, '%M-%Y') as Months, ", @sql, " ,SUM(revenue) as `Grand Total` FROM TABLE1 GROUP BY month ORDER BY month ASC" ); PREPARE region_stmt FROM @sql; EXECUTE region_stmt; which produces results like this (this is the desired result) in command line and sequel pro Query result But when I use same query with Django 1.8 with python 2.7 cursor, it produces error ProgrammingError: (1064, u'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'SELECT GROUP_CONCAT(DISTINCT\r\n CONCAT("SUM(CASE WHEN region = \'", `regio\' at line 2') -
ModelForm django shows no file chosen when editing
I'm trying to create the edit of posts for a blog. When i create the form with the instance all the fields display but the image part appears like "No file chosen" Here is my model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() image = models.ImageField(blank=True, null=True) publication_date = models.DateField(default=datetime.date.today) expiring_date = models.DateField() Here is my form class PostForm(forms.models.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.instance.publication_date = datetime.date.today() class Meta: model = Post exclude = ['publication_date'] widgets = { 'title': forms.fields.TextInput(attrs={ 'class': 'form-control' }), 'content': forms.Textarea(attrs={ 'class': 'form-control' }), 'image': forms.fields.FileInput(attrs={ 'class': 'form-control' }), 'expiring_date': forms.fields.DateInput(attrs={ 'input_type': 'date', 'class': 'form-control' }), } This is my view def edit(request, post_id): post = get_object_or_404(Post, pk=post_id) form = PostForm(instance=post) return render(request, 'posts/edit.html', {'form': form}) And here is my template {% block content %} <div class="row"> <div class="col-md-12"> <div class="card animated materialU animation-delay-5"> <div class="card-block card-block-big"> <form action="{% url 'posts:update' %}" method="post" enctype='multipart/form-data'> {{ form }} <input type="submit" name="save changes" value="Save Changes" class="btn btn-success"> {% csrf_token %} </form> </div> </div> </div> </div> {% endblock %} What is missing? -
how to display model data to html page
I am following this tutorials and created a model and can see the data from admin page. https://djangoforbeginners.com/message-board/ However, i am unable to see the see the posts in the html page. My html pages is inside the template: Model: pages/models.py from django.db import models # Create your models here. class Post(models.Model): text = models.TextField() def __str__(self): return self.text[:50] View: pages/views.py class DiagramsPageView(TemplateView): posts = Post.objects.all() template_name = 'diagrams.html' contex= {'posts': posts} pages/urls.py from .views import DiagramsPageView, urlpatterns = [ path('diagrams/', DiagramsPageView.as_view(), name='diagrams'), ] The HTML template page is here <!-- templates/home.html --> {% extends 'base.html' %} {% block content %} <h1>Diagrams</h1> <h2>Styling Tables</h2> <ul> {{posts}} </ul> {% endblock content %} The HTML page only outputting Diagrams Styling Tables -
Django ImageField will not display on webpage
I am using an imageField in my Django model and the photo is not being recognized when I try to display it in the html. Here is my models.py from django.db import models class LatestRelease(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=300) cover = models.ImageField(upload_to='personal/static/img/') display = models.BooleanField(default=True) Here is view.py from django.shortcuts import render from personal.models import LatestRelease def index(request): releases = LatestRelease.objects.all() return render(request, "personal/home.html", {'releases': releases}) HTML code {% for release in releases %} <img src="{{ release.cover.url }}" class='' height='235' width='235'> {% endfor %} So basically, the image path {{ release.cover.url }} is /personal/static/img/[image name] and my photos only appear to show up when I use the url path /static/img/[image name] as the source. Is there anyway to take /personal out of the string that is created from {{ release.cover.url }} ? Or to make it so that my img source accepts files under /personal/static/img/[image name]? -
Django - Ajax POST error 403 (Forbidden) and 500 (Internal Server Error)
I'm using Ajax to post data. It threw the error 403 (Forbidden), then I added @csrf_exempt to my view. Afterwards, error 500 (Internal Server Error) occurred. I've tried different like following the docuement to add extra code and imported it to the template. I'm struggling to fix these two problem. One's gone then the other occurs. detail.html: <script> $(document).ready(function () { $("#add").click(function (event) { event.preventDefault(); $.ajax({ url: '{% url "cart:add_to_cart" %}', type: "POST", dataType: 'json', success: function (response_data) { <do something here> }, }); }); }); </script> <form method="post"> {% csrf_token %} <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> <input name="bookID" value=" {{ book.id }} " hidden> <button id="add" type="submit"> Add to Cart</button> </form> Once I added @csrf_exempt, error 500 came out. cart/views.py: @csrf_exempt def add_books(request): # some code here response_data = { 'quantity': BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity'] } return JsonResponse(response_data) -
ImageField not displaying on webpage in Django
I am using an imageField in my Django model and the photo is not being recognized when I try to display it in the html. Here is my models.py from django.db import models class LatestRelease(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=300) cover = models.ImageField(upload_to='personal/static/img/') display = models.BooleanField(default=True) Here is view.py from django.shortcuts import render from personal.models import LatestRelease def index(request): releases = LatestRelease.objects.all() return render(request, "personal/home.html", {'releases': releases}) HTML code {% for release in releases %} <img src="{{ release.cover.url }}" class='' height='235' width='235'> {% endfor %} So basically, the image path {{ release.cover.url }} is /personal/static/img/[image name] and my photos only appear to show up when I use the url path /static/img/[image name]. Is there anyway to take /personal out of the string that is created from {{ release.cover.url }} -
Python Django auto generating field not present in form
I'm new to django and I have a web application, in which I have an model called Template. this model has one field called body and one field called tokens. sample body would be : "I am {{ first_name }} {{ last_name }}" I want tokens field to be filled by comma separated values : "first_name, last_name" so in admin form for creation and change I don't want to be asked for this field value. how can I achieve this in django? here is what I tried, which doesn't work. class SmsTemplate(models.Model): """ Message SMS Template """ name = models.CharField(max_length=255) body = models.TextField() tokens = models.SlugField() created = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if self.pk is None: self.tokens = ",".join(re.findall(r'{{\s*(.*?)\s*}}', self.body)) super().save(*args, **kwargs) python 3.7.0 django 2.1.1 -
Django Views for simple food menu
I need help with building views for food menu I did the models just have an issue to make the views https://preview.themeforest.net/item/rosa-an-exquisite-restaurant-wordpress-theme/full_screen_preview/7920093 basically idk how to do it , all I I wanna show is category and its item like this I'm beginner -
Django - POST method error "POST /......./ HTTP/1.1" 405 0
I use the POST method since I need to change the database. But each time I used the POST method, this error occurred. Every time I click the button, the page will not be loading and saying "POST /book/go-action/ HTTP/1.1" 405 0. There is no difference when I use q = request.POST["quantity"] or q = request.POST.get('quantity', ''). If I use GET method, the issue will not occur but the GET method cannot meet the needs. Also I don't need action in the form, cos I don't need the page to redirect to somewhere and I'm using ajax to call the function view. How can I fix the issue? book/detail.html: <form method="post"> {% csrf_token %} <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> </select> <input name="bookID" value=" {{ book.id }} " hidden> <button id="add" type="submit"> Add to Cart</button> </form> cart/views.py: def add_books(request): c = Cart.objects.get(user=request.user) if request.method == 'POST': # q = request.POST["quantity"] # book_id = request.POST["bookID"] q = request.POST.get('quantity', '') book_id = request.POST.get('bookID', '') # the rest of the code here return JsonResponse(response) -
int() argument must be a string, a bytes-like object or a number, not 'QuerySet'
I'm working from this tutorial as a guide. Their SignupForm is very similar to mine, but I'm receiving an int() argument must be a string, a bytes-like object or a number, not 'QuerySet' error when I try to add the ManyToMany. (This is just the first step in what will eventually be several user types, so using is_xyz type Booleans on the MyUser class is not a long-term solution): models.py class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): # Does the user have a specific permission? # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): # "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): return self.is_admin class Meta: db_table = 'users_myuser' verbose_name = 'MyUser' class ApplicationUser(models.Model): user = models.OneToOneField(MyUser, on_delete=models.CASCADE) class AdminUser(models.Model): user = models.OneToOneField(MyUser, on_delete=models.CASCADE) destination = models.ManyToManyField(Destination, blank=True) forms.py class GatekeeperPlusSuperCreationForm(forms.ModelForm): password1 = CharField(label="Password", widget=PasswordInput) password2 = CharField(label="Password confirmation", widget=PasswordInput) class Meta: model = get_user_model() fields = ('email',) destination = forms.ModelMultipleChoiceField(queryset=Destination.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) def clean_password2(self): password1 = … -
Giving relations an order to sort by
Given the following Django models: class Room(models.Model): name = models.CharField(max_length=20) class Beacon(models.Model): room = models.ForeignKey(Room) uuid = models.UUIDField(default=uuid.uuid4) major = models.PostiveIntegerField(max_value=65536) minor = models.PositiveIntegerField(max_value=65536) The Beacon model is a bluetooth beacon relationship to the room. I want to select all Rooms that match a given uuid,major,minor combination. The catch is, that I want to order the rooms by the beacon that is nearest to me. Because of this, I need to be able to assign a value to each beacon dynamically, and then sort by it. Is this possible with the Django ORM? In Django 1.8?