Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
website.Product.category: (fields.E009) 'max_length' is too small to fit the longest value in 'choices' (3 characters)
I am new to Django and trying to run the cloned project from GitHub. Created a virtual environment by conda. Installed Django, Pillow by pip install django, python -m pip install Pillow in the activated virtual environment. but, when I run python manage.py runserver I am getting an error. Tried searching if there are any duplicate questions but seems like no one had the exact same issue. Here's the image of complete error with traceback -
how to get the data from text/html API response in Django
I send post request to (FortPay-Payment Gateway) API in Json format, and I get the Response in text/html format from the same URL ... what i need, is to get the data sent in this Response as it contains a Token that i need to reuse That is my request in the views.py: def DayTourCreditInput(request, buyer_id): buyer = get_object_or_404(DayBuyer, id=buyer_id) redirectUrl ='https://checkout.payfort.com/FortAPI/paymentPage' requestParams = { 'service_command ' : 'TOKENIZATION', '********' : '********************' #etc. } r = requests.post(redirectUrl, params=requestParams) content = r.text return HttpResponse(content, content_type='text/plain') ##I Tried r.json and r.json() and also return HttpResponse(contentJson, content_type='application/json') ... But all raises errors I looked for cgi python, but no enough docs available + i don't know if it is the suitable solution for this case or not Just wanna assure that the site respond by an html document with JavaScript involved in it -
Cookiecutter Django - Add field to signup form?
When I use django-allauth I can easily change the Signup form by just creating a new form and in settings.py add: ACCOUNT_SIGNUP_FORM_CLASS = "core.forms.SignupForm" I was unable to successfully do this with Cookiecutter Django. Shouldn't this work in Cookiecutter Django since it uses django-allauth? If not then how can I add or change fields for the signup form? -
django-celery-beat and DatabaseScheduler with a set first run time
I want to use django-celery-beat and DatabaseScheduler to create an "email alert" function for users. They should be able to say, when they want to receive these alerts (e.g. every day - 7 AM or every week monday 1 PM). I've almost figured out how to create the periodic tasks, i.e. >>> PeriodicTask.objects.create( ... interval=schedule, # we created this above. ... name='Importing contacts', # simply describes this periodic task. ... task='proj.tasks.import_contacts', # name of task. ... expires=datetime.utcnow() + timedelta(seconds=30) ... ) from https://github.com/celery/django-celery-beat, but how do I tell it when the first sendout should be? -
Get bank detail using ifsc in django
How can I get bank details when a user enters ifsc code in forms in django.Like when a user enters the the ifsc code other details like branch and all are shown -
Creating questionand quiz instance for a quiz app
So i am working on this simple quiz app, and i think i messed my model all up. The original objective is to have a quiz taker model, quiz categories, levels and a list of questions under each. However, am worn out on how to structure the model to enable each user have an instance of the quiz, levels and questions in order to keep track of the players progress. MODELS.PY from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # QUIZ CLASS MODEL class Quiz(models.Model): category = models.CharField(max_length=200, help_text="quiz name") class Meta: ordering = ['category',] def __str__(self): return f"{self.category}" # LEVEL CLASS MODEL class Level(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) DIFFICULTY = [ (("level1"),("level1")), (("level2"),("level2")), (("level3"),("level3")), (("level4"),("level4")), (("level5"),("level5")), (("level6"),("level6")), (("level7"),("level7")), (("level8"),("level8")), (("level9"),("level9")), (("level10"),("level10")), (("bonus"),("bonus")) ] levels = models.CharField(max_length=7, choices=DIFFICULTY) is_completed = models.BooleanField(default=False, help_text="check if category level has been completed") def __str__(self): return self.levels # QUESTION CLASS MODELS class Question(models.Model): question = models.CharField(max_length=1000) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) is_answered = models.BooleanField(default=False) def __str__(self): return self.question # ANSWER CLASS MODEL class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=1000) is_correct = models.BooleanField(default=False) def __str__(self): return self.choice # QUIZ TAKER MODEL class QuizTaker(models.Model): … -
automate and browse website from python django website
I used Python Selenium to browse and simulate tasks to automate some staffs, if the website didnt have API. How to do the same from my running python django website? Are there any issues or some better way to do that? -
Django ckeditor upload image
I'm trying to use ckeditor to upload an image. Looks like everything is set up by documentation, but still I'm getting an error while trying to upload an image. I think that there is a problem with static files. Looks like ckeditor doesn't know where to upload files, even though I've provided all needed parameters: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' I'm getting this message: [23/Feb/2020 20:17:47] "POST /ckeditor/upload/&responseType=json HTTP/1.1" 302 0 And here's what I get in browser. The red one is for "incorrect server response". -
Django - Update user image with ajax
Im working on a django project and I have a UserProfile model that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_image_path,null=True,blank=True, default="False") and I use this Mixin: class AjaxFormMixin(object): def form_invalid(self, form): response = super(AjaxFormMixin,self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors,status=400) else: messages.info(self.request, 'Not an image') return response def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): image = form.cleaned_data.get("image") data = { 'message':'Success!', 'image':image, } return JsonResponse(data) else: return response for this View: class ProfileView(AjaxFormMixin,FormView): form_class = ProfileUpdateForm template_name= 'userprofile.html' success_url = '/form-success/' queryset = User.objects.all() with this form: class ProfileUpdateForm(forms.ModelForm): class Meta: model = UserProfile fields = ['image'] def clean_image(self): image = self.cleaned_data.get('image') filename, file_extension = os.path.splitext(image) if not ".jpg" or '.png' in file_extension: raise forms.ValidationError(filename + 'is not an image') return image in the template I have this html form: <form class="profile_form" method='POST' enctype="multipart/form-data" data-url="{{ request.build.absolute.uri|safe }}"> {% csrf_token %} {{ form|crispy }} <input class='profile_img_btn' type="submit" value="Update Image"/> </form> and this ajax function: $(document).ready(function(){ var i_form = $('.profile_form'); i_form.submit(function(event){ event.preventDefault(); var i_data = $(this).serialize(); var i_link = i_form.attr('data-url'); console.log(i_data); $.ajax({ method:"POST", url: i_link, data: i_data, success: handleFormSuccess, error: handletFormError, }) function handleFormSuccess(data){ console.log(data); } function handletFormError(data){ console.log(data); } }) }) This is what I … -
Django ModelChoiceField embed url using mark_safe not working
I have the code: class TypeChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("<a href='https://www.google.com'> %s </a>" % obj.name) to display: Current Result which does not point to the specified url. What I want is to actually point to the specified link: like this so that I can click on it to go to that link. Thank you for your time. Have a good day. -
Get value in select tag
I need to get value from select tag. I send two value at the same time include value from input tag and select tag. But I can get just value from input tag. javascript part <script> $(document).ready(function () { first(); $('#btnAdd').click(first); // เมื่อ click จะสร้าง element ขึ้นมาใหม่(สร้างอินพุตใหม่) }); var choices = ["คอนแทคเลนส์", "น้ำยาทำความสะอาด", "อื่น ๆ"]; function first() { var id = $('#cover div').length + 1; // นับว่ามี tag div กี่อันแล้ว แล้ว +1 var wrapper = $("<div id=\"field" + id + "\" class='row info'><p></p>"); // สร้าง div var category = ""; category = "<div class='col-md-2'><select class='form-control' name=\"category" + id + "\">"; for (i = 0; i < choices.length; i = i + 1) { category += "<option value='" + choices[i] + "'>" + choices[i] + "</option>"; } category += "</select></div>"; var product = $("<div class='col-md-5'><input type='text' id='tags' name=\"product" + id + "\" class='form-control' size=40 placeholder='ชื่อสินค้า' required/></div>"); // สร้าง input wrapper.append(category, product); $('#cover').append(wrapper); $(wrapper).find("input[name^='product']").autocomplete({ source: "/autocomplete_product", minLength: 2, }); } views.py def autocomplete_product(request): data = request.GET product = data.get("term") category = data.get("category") I need to get category value from select tag. -
How do I get data under a specific user into template in Django
I have a very simple Django project. I have setup the login and sign up already to work but my one problem is that in models.py file under the UserProfile() class I have orders = models.ForeignKey(UserOrder) Now in admin I can make an order and then in the UserProfiles assign that order to an account but how can I make the user when he or she logs in see his orders after I assign them via my admin panel? Stuck on this for 3 hours! -
Javascript Neo4j JSON object from django to JS in
I'm building this webapp with django. I'm using the grid package by gijgo, to make a nice interactive table, with the ability to interact with my database. I'm using a neo4j database, and since it is not supported directly I'm changing the queries to make it work (changing the code for upload/edit/deletion and so on). here an example of the editable table: https://gijgo.com/grid/demos/javascript-sourced-data here you can see that with the parameter datasource, you can both specify a server interaction, or to use a json file created locally. https://gijgo.com/grid/configuration/dataSource I was using the local version, I was defining in view.py to pass an object to the page (maybe this is not the right word to use) preprocessed with: results=repr(dumps( )) then results returned. then in the HTML document, in a javascript I was using var data = jQuery.parseJSON({{results | safe }}); this allowed me to use it in the datasource option in the grid function (as a local object). However after I updated the edit/new interactions I noticed that of course the json file passed from view prevented the grid to be updated (I had to update the page with f5 every time to see the results). Therefore I decided to … -
Django: "constants" configuration middleware
I'm writting an application that has two languages availables (English and Spanish). The way that I decided to face this was by doing methods for each label that I will display in templates, for example: constants.py: def c_accept(language): if language == 0: return 'Aceptar' elif language == 1 or language is None: return 'Accept' In this way, I can use c_accept instead of String literals by passing the language that the user has chosen (saved in request.session['language']). So far so good, until I found I had too many "constants", and it brings a problem. If I pass all the constants in every view, it's a lot of garbage process for each request, and if I pass only the "constants" that I will use in that view, it takes a lot of time to be careful on which constant I'm using and which not. So I realized I could make a middleware which loads all my constants but only one time, as Django documentation explains in the class-based middleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. **(I want to load all my constants here)** def __call__(self, request): # Code to be executed for each request before # … -
Conditional annotation/aggregation of QuerySet
I have a annotation which cumsums values in a QS which applies to every item in the QS but I want it to only apply to specific users so that each users cumsum is separated. Example: queryset = queryset.annotate( user_views_cumsum=Window(Count('video'), order_by=F('date_time').asc()))\ .values('user', 'video', 'date_time', 'id', 'user_views_cumsum').order_by('date_time', 'user_views_cumsum') ...gives the QuerySet: <QuerySet [ {'user': 2, 'video': 13, 'date_time': datetime, 'id': 5, 'user_views_cumsum': 1}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 6, 'user_views_cumsum': 2}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 7, 'user_views_cumsum': 3}, {'user': 2, 'video': 16, 'date_time': datetime, 'id': 8, 'user_views_cumsum': 4}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 9, 'user_views_cumsum': 5}, {'user': 2, 'video': 16, 'date_time': datetime, 'id': 10, 'user_views_cumsum': 6}, {'user': 2, 'video': 16, 'date_time': datetime, 'id': 11, 'user_views_cumsum': 7}, {'user': 4, 'video': 16, 'date_time': datetime, 'id': 12, 'user_views_cumsum': 8}, {'user': 4, 'video': 16, 'date_time': datetime, 'id': 13, 'user_views_cumsum': 9} ]> ..but I want 'user':4 to have their first user_views_cumsum as 'user_views_cumsum': 1 not 'user_views_cumsum': 8. I see in the django docs about conditional aggregation but I don't know the users id beforehand. I also don't want to filter the QS because I want the QS to remain in tact. How can I achieve this? Edit: It is … -
File manager (dropbox clone)
I am working on a django + react wep app. I would like to make a file management browser like you see on google drive and dropbox. The functionalities it would have would be that it lists files (filename, filesize, date) and users would be able to upload, delete and download files. Users can only see their own files. However, I am facing some trouble figuring out the best way to do this. I was wondering if I need to make a database table, that contains info about all files (their owner, location, filename, filesize, date). Then I would in my react app make a table displaying this info with buttons on each row for deleting and downloading the file. When for instance clicking delete on a file, it would then delete that file on the database using the api. In my django app I would make a mechanism (not sure if it should be a signal) that deletes the actual file when a file object is deleted on the database. I would also have a location tracker, that keeps track of the current folder. So that if you click on a folder (I make a function that checks the … -
Django update_or_create in views.py
do 'update_or_create' and 'get_or_create' works in views.py? I follow the instruction here Create Django model or update if exists I think 'update_or_create' and 'get_or_create' works only in models.py, cause when I apply it in my views it doesn't work, did I miss something? to those people who will answer this question, thanks in advance :) please help me guys.. this is my views.py def grades(request): global gradekos, dates, averages id = request.POST.get('teacher') teacher = EmployeeUser(id=id) category_id = request.POST.get('category') category = gradingCategories(id=category_id) subject_id = request.POST.get('subject') subject = Subject(id=subject_id) #ave=request.POST.get('average') student = request.POST.get('students') #students = StudentsEnrolledSubject(id=student) periods = request.POST.get('period') period = gradingPeriod(id=periods) gradekos = [] dates = [] averages = [] for average in request.POST.getlist('average'): averages.append(average) for gradeko in request.POST.getlist('gradeko'): gradekos.append(gradeko) for date in request.POST.getlist('date'): dates.append(date) i = 0 h = 0 for single_date in dates: for student in request.POST.getlist('students'): update_data, create = studentsEnrolledSubjectsGrade.objects.update_or_create( Teacher = teacher, GradeLevel = grade, Grade = gradekos[i], Date=single_date, Grading_Categories = category, grading_Period = period, Subjects = subject, defaults = {"Students_Enrollment_Records": student} ) i += 1 update_data.save() for single_date in dates: for student in request.POST.getlist('students'): students = StudentsEnrolledSubject(id=student) insert_data, create = studentsEnrolledSubjectsGrade.objects.get_or_create( Teacher=teacher, Students_Enrollment_Records=students, Date=single_date, Grade=gradekos[i], Grading_Categories=category, Subjects=subject, ) i += 1 insert_data.save() return render(request, 'Homepage/pending.html') -
Generate controlled string in django
I've wondered how I'd generate a string in django, that will act after following rules: Each country (so each unique entry in a specific model field) will have their own beginning number. The number should start with the country identifying beginning number, but then it should count up. There should be 11 digits generated pr. order number. So as an example we would have these two for country 1 and country two's first order: country one order one: 10000000001 country one order two: 10000000002 country two order one: 20000000001 country two order two: 20000000002 To make it clear, then I do wish it to increase naturally within the country, so if the first order is from country one, and the second order is from country two, then we will have the following order numbers registered: 10000000001 20000000001 and not like this: 10000000001 20000000002 The first client in each country should end with 1, the second with 2 and so on. How can i best do this? -
Django Cannot Connect to SQL Server 2019
I have a django Project and want to connect to SQL Server 2019. But I have a problem when doing migration. Here is the error message: django.db.utils.NotSupportedError: SQL Server v15 is not supported. I'm using Django 2.1.15 and SQL Server Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 Does it mean this django version cannot using SQL Server 2019? I'm still new in django project. Thanks before -
"SyntaxError: invalid syntax" in views.py
In my applicaton when user fills inputs I should send him/her email and create instance of that user. But I can't run my application because of following error: Exception in thread django-main-thread: Traceback (most recent call last): ... File "/Users/progbash/Desktop/pragmatech/pragmatechproject/pragmatechproject/urls.py", line 21, in <module> path('', include('pragmatechapp.urls')), File "/Users/progbash/Desktop/pragmatech/denvx/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/Users/progbash/Desktop/pragmatech/denvx/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/progbash/Desktop/pragmatech/pragmatechproject/pragmatechapp/urls.py", line 2, in <module> from . import views File "/Users/progbash/Desktop/pragmatech/pragmatechproject/pragmatechapp/views.py", line 26 return render(request, 'pragmatechapp/index.html', context) ^ SyntaxError: invalid syntax This is my views.py: def index(request): context = { 'applicants': Applicant.objects.all() } if request.method == "POST": applicant_name = request.POST.get('name') applicant_email = request.POST.get('email') applicant_phone = request.POST.get('phone') subject = 'Thank you.' message = 'Hi, ' + str(applicant_name) from_email = settings.SERVER_EMAIL recipient_list = [applicant_email] send_mail(subject, message, from_email, recipient_list) if request.POST.get('email'): Applicant.objects.create( name = request.POST.get('name'), email = request.POST.get('email'), phone = request.POST.get('phone') return render(request, 'app/index.html', context) And my urls.py file: from django.urls import path from . … -
Spyne WSDL doesnot contains https in WSDL
I am using spyne with django. The issue is that WSDL generated by Spyne doesnot contains https in WSDL however my application is being served on https and I am requesting the WSDL on https but issue is same Thanks -
How to set values passed from python list to a html progress bar
I have an application where people can read news items and comment.Then those comments are analysed using NLP techniques and comments are classified in to two categories as positive, negative. What I want to do is display how much percentage of comments are positive and how much percentage of comments are negative under each news item.So what I did was I added the [id, headline, newsText, date , positiveCommentPercentage, negativeCommentPercentage] data of each news item in to a Python list and appended it in to a another List and passed it to the web page. list = [id, headline, newsText, date ,positiveCommentPercentage ,negativeCommentPercentage ] newsData.append(list) template = 'AppOne/news.html' return render(request, template, {'nd': newsData}) I could successfully display the news headline,news and date on the web page as follows, <div> {% for x in nd %} <h2>{{x.1}}</h2> <h5>{{x.2}}</h5> <h6>{{x.3}}</h6> {% endfor %} </div> But I want to show the number of "positive comments percentage" and "number of negative comments percentage" under each news item as 2 progress bars as shown in the image So I tried to use the html progress bars shown in 'w3schools' site. <div class="w3-light-grey w3-round"> <div class="w3-container w3-blue w3-round" style="width:60%">60%</div> The question I have is how to … -
Page not found (404) on a Class-based views
I have a problem with my class bases views and i can't resolve it! i try to render a web page that show a detailed post. But my class based view refuse to work correctly. So i tried many things but no one fix my prob. It return me a 404 page not found. my urls.py from django.urls import path from .views import PostListView, PostDetailView from .models import Post from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('about/', views.about, name='blog-about'), ] my view.py # pylint:disable=no-member from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post def home(request): context = Post.objects.all() return render(request, {'posts': context}) class PostListView(ListView): model = Post context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post def about(request): return render(request, 'blog/about.html', {'title': 'About'}) my post_detail.py {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <img class="img-profile" src="{{ object.author.profile.image.url }}" /> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted | date:"d F, Y " }}</small> <hr /> </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> </article> {% endblock content %} thanks:) -
Annotation of cumulative sums of fields in queryset
This one is a doozy. I have a model which records data from when a user has watched a video: class VideoViewed(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) date_time = models.DateTimeField(default=timezone.now) From the queryset I would like to have each object in the queryset store a value which is a cumulative sum of total videos viewed by that specific user up until this point in time. Currently I have this annotation: queryset = queryset.annotate( user_views_cumsum=Window(Sum('video'), order_by=F('date_time').asc()))\ .values('user', 'video', 'date_time', 'id', 'user_views_cumsum').order_by('date_time', 'user_views_cumsum') Which I want to give the Queryset: <QuerySet [ {'user': 2, 'video': 13, 'date_time': datetime, 'id': 5, 'user_views_cumsum': 1}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 6, 'user_views_cumsum': 2}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 7, 'user_views_cumsum': 1}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 8, 'user_views_cumsum': 3}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 9, 'user_views_cumsum': 4}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 10, 'user_views_cumsum': 2} ]> But Sum('video') is giving me the cumsum of the videos id so it looks like this: <QuerySet [ {'user': 2, 'video': 13, 'date_time': datetime, 'id': 5, 'user_views_cumsum': 13}, {'user': 2, 'video': 13, 'date_time': datetime, 'id': 6, 'user_views_cumsum': 26}, {'user': 4, 'video': 13, 'date_time': datetime, 'id': 7, … -
connecting the views to the my models in Django
I have this data: [ { "x": -1.31242086143345, "y": 0.40178573392332, "z": -1.02033965707123, "ts": 1580485700059, }] I posted this data and I received this data with this code in my views: def save_acc(request): accelerometer_data = json.loads(request.read()) return JsonResponse(accelerometer_data,safe=False) I created my model according to each element of the first data: from django.db import models class accelerometer_data(models.Model): x = models.DecimalField(max_digits=30, decimal_places=10) y = models.DecimalField(max_digits=30, decimal_places=10) z = models.DecimalField(max_digits=30, decimal_places=10) ts = models.DecimalField(max_digits=30, decimal_places=10) So, in mysql database the name of table is accelerometer_data and there are 5 columns:id, x , y ,z ,ts I just need whenever, I post data to my app, I need directly save data to my database. I think I have to connect my views to my models, for this problem but I do not know how I can do this, thanks for yor help