Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django ModelSerializer unable to mark a field required as false
I am trying to make a field investor required as False in Django Restframework's ModelSerializer. class WatchListSerializer(serializers.ModelSerializer): class Meta: model = WatchList fields = ['id', 'investor', 'property'] extra_kwargs = { 'investor' : { 'required' : False } } However, both the fields are defined as ForeignKeys in the model. As you can see in above implementation I am trying to override the default implementation of field investor using extra_kwargs. Unfortunately, it still asking to provide the value for investor. Here is the model Watchlist - class WatchList(BaseModel): investor = models.ForeignKey(User, on_delete=models.PROTECT, blank=False, null=True) property = models.ForeignKey(Properties, on_delete=models.PROTECT, blank=False, null=True) class Meta: unique_together = (('investor', 'property',)) def __str__(self): return f'Watch List Object {self.id}:' -
how can i convert str to float (the value of foreignkey)
please how can i convert Foreignkey value string to float ? in models.py i create a following code, the target is to get the value of foreingkey as float then use it to calculate the value of redevance. class production(models.Model): nom= models.CharField(max_length=70, blank=False, null=True) choix_type = ( ('','selectionner le type de projet '), ('exploration/production','exploration/production'), ('developpement/production','developpement/production'), ('Exploitation','Exploitation'), ) forme_projet = models.CharField(max_length=50, default='', blank=False, null=True, choices=choix_type) quantite = models.FloatField(blank=False, null=True) prix = models.FloatField(blank=False, null=True) def __str__(self): return str(self.nom) if self.nom else '' def calcule_production(self): return self.prix * self.quantite class redevance(models.Model): production_projet = models.ForeignKey(production, on_delete=models.CASCADE, null=True, blank=False) cout_transport = models.FloatField(blank=False, null=True) cout_liquifaction = models.FloatField(blank=False, null=True) cout_separation = models.FloatField(blank=False, null=True) def calcule_cout(self): return (self.cout_transport + self.cout_liquifaction + self.cout_separation) - self.production_projet type error the error seems like this: thanks -
How to Create an api to extract xml file in django
I need to create an API in Django that will use to take an XML file and extract the data from it. I have created models and serialization and now I can not understand the view part(api) please help. -
Django Test ValidationError when input is not a digit
How to test ValidationError when User inserts Text for my zip code example? This is my validation in my models.py file: def validate_zip_code(value): zip = str(value) if not zip.isdigit(): raise ValidationError('Please enter a valid zip code.') And my test file in test_models.py class TestZIP(TestCase): def test_zip_code_digit(self): self.assertRaises(ValidationError, validate_zip_code, 'Random Text') Running python.manage.py test I get no Errors, but when I run coverage html and check the test percentage, I get told that this function has not been tested correctly. What am I doing wrong? -
Otree Page not found Server Error 404. How to add sub-url to the domain name?
I am using the kubernetes cluster where, I already have a domain name "https://example.com". I need to deploy the otree server by creating the sub-urls above the domain which is already purchased for hosting. Is their is something i can change in settings.py to make this change happen. enter image description here -
How to get data in the form of table in django using cloud firestore?
I'm trying to get data in the form of a table, but the data is not being fetched, I don't know how to get the record, I'm using cloud firestore to get the data -
froala editor show textarea in django admin site
I'm trying to use froala editor, but its show textarea in admin site here is my model.py code from django.db import models from froala_editor.fields import FroalaField # Froala Editor class Page(models.Model): contant = FroalaField(options={ 'toolbarInline': True, }) def __str__(self): return self.contant -
Django html variables are splitting when binding
I have a simple html template which shows permissions in a table for each group. Every cell of the table, contains a button. I want to show the name of the permission in a popover of every button! The problem is that Django variable is not working fine! <button type="submit" class="btn" title={{ permission.name }}> ... </button> As you can see in above, the title is initialized with {{ permission.name }} and I expect to see full name of permission when hovering button, but it just contains the first word! Which is not odd because this is what I saw in the inspect elements: <button type="submit" class="btn" title="نمایش" لیست="" کاربران=""> ... </button> As you can see, title is ruined! What's the problem here? Why it's not working as I expected? -
Django + Celery run task only once (at a specific time)
Let me explain what I want to do through the example. class SampleModel (models.Model): start = models.DateTimeField (** options) end = models.DateTimeField (** options) status = models.BooleanField (** options) For example, when a user is banned, the ban date (start) and the ban expiration date (end) and the (status) field that I add to check if they are banned. (This is actually just an example of different scenarios, the date a post was opened to visitors, etc.) I know that I can create tasks using "Django + Celery + Celery-beat", but what i want to do is to set the run time of the task and run it only once -
How to serializer my children model objects properly?
Here I am trying to return the children objects serialized data like this but this is not working. I got this error. raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Type is not JSON serializable How to solve this issue ? model class Type(models.Model): name = models.CharField(max_length=200, unique=True) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, null=True, blank=True) serializer class ListTypeSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Type fields = ['name', 'children'] # for some reason I can not do `return obj.type_set.values('name')` # since I have so many customized variable names. # I am displaying only name here in question. def get_children(self, obj): return ListTypeSerializer(obj.type_set.all(), many=True, context={'request': self.context['request']}).data -
display list item in HTML template
I have 2 list that I imported from my python code to the html template which is called eligable and overTimeHours. I tried displaying them like this: <ul> {% for item in eligable %} <div class="pad3"> <li>{{item}} - {{item.overTimeHours}}</li> </div> {% endfor %} </ul> but only {{item}} is displayed but {{item.overTimeHours}} did not display. here is my python code: def specificDate(response): empName = employeeName.objects.all eligable = [] overTimeHours = [] check = False if 'checkEmployee' in response.POST: n = response.POST.get("nameEmployee") specDate = response.POST.get("date") correctDate = None try: newDate = datetime.strptime(specDate, '%Y-%m-%d') correctDate = True except ValueError: correctDate = False print("This One: ",correctDate) if correctDate == True: if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists(): check = True emp = employeeName.objects.get(employee=n) t = Name.objects.get(name=emp, date=specDate) overT = Name.objects.filter(name=emp, overtime=True) for item in overT: eligable.append(item.date) totalTime = (datetime.combine(item.date, item.timeOut)- datetime.combine(item.date, item.timeIn)).seconds/3600 hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) overTimeHours.append(time) checkIn = t.timeIn.strftime("%H:%M:%S") checkOut = t.timeOut.strftime("%H:%M:%S") messages.info(response, checkIn + ' - ' + checkOut) return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable, "check":check, "overTimeHours":overTimeHours}) else: messages.info(response, 'Result does not exist') else: messages.info(response, 'Please enter correct input') else: pass return render(response, "main/specificDate.html", {"empName":empName}) -
i want to make a dropdown menu . I searched for the different techniques but my design is changing
I want to make that lead(below Dashboard) to be dropdown menu. without changing my design. The lead is under ul tag. <div class="wrapper "> <div class="sidebar" data-color="purple" data-background-color="white" data-image="../assets/img/sidebar-1.jpg"> <div class="logo"><a href="http://www.creative-tim.com" class="simple-text logo-normal"> Creative Tim </a></div> <div class="sidebar-wrapper"> <ul class="nav"> <li class="nav-item "> <a class="nav-link" href="{% url 'UserProfile' %}"> <i class="material-icons">person</i> <p>Lead</p> </a> </li> -
Multiple Choice in Models Inquiry
We are doing a React frontend and Django backend project. We will have a series of moral dilemmas that each will have separate multiple-choice options. Each separate dilemma may have anywhere between 2 and 4 multiple-choice possible answers. We are struggling to find an answer as to what the best way to do this is.. This is the super rough model that we have so far: class Dilemmas(models.Model): title = models.CharField(max_length=64) image = models.ImageField(upload_to='ethics_app/image_assets') dilemma = models.TextField() # insert multiple-choice options here that will be between 2 and 4 possible answers. def __str__(self): return self.title -
How to use functors instead of functions in django?
I have a model called Story: from django.db import models from api import settings from core.functions import UploadImage from .settings import STORY_UPLOAD_PATH get_story_upload_path = UploadImage(STORY_UPLOAD_PATH) class Story(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField(upload_to=get_story_upload_path) caption = models.TextField() expiration_date = models.DateTimeField() import datetime import uuid import os The behavior for uploading photos is the same for multiple models, thus I decided to make a functor that holds the path to upload to and pass it to the models with common behaviour. The functor: import datetime import uuid import os class UploadImage: def __init__(self, upload_path): self.upload_path = upload_path def __call__(self, instance, filename): filename = f'{datetime.datetime.now()}_{uuid.uuid4()}_{filename}' return os.path.join(self.upload_path, instance.username, filename) The serializer class: from rest_framework import serializers from models import Story, ViewedStory class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ('id', 'user', 'image', 'caption') read_only_fields = ('id', ) When I try to make migrations, I get this error: Migrations for 'stories': stories/migrations/0001_initial.py - Create model Story - Create model ViewedStory Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File … -
Debugging not working in VS Studio Code Django
I have been working through the official Django Tutorial in Visual Studio Code but I have run into an issue. Currently when I ever I set a break point at the line now = datetime.now the debugger seems to fail reach it. Attached it my urls.py code and my view.py code. from django.urls import path from hello import views urlpatterns = [ path("", views.home, name="home"), path("hello/<name>", views.hello_there, name="hello_there"), ] Above is the urls.py code. Below is the views.py code. import re from django.utils.timezone import datetime from django.http import HttpResponse def home(request): return HttpResponse("Hello, Django!") def hello_there(request, name): now = datetime.now() formatted_now = now.strftime("%A, %d %B, %Y at %X") # Filter the name argument to letters only using regular expressions. URL arguments # can contain arbitrary text, so we restrict to safe characters only. match_object = re.match("[a-zA-Z]+", name) if match_object: clean_name = match_object.group(0) else: clean_name = "Friend" content = "Hello there, " + clean_name + "! It's " + formatted_now return HttpResponse(content) I apologize if the formatting is off, I am a beginner and new to stack overflow. -
Django - Follow Button Functionality Does Not Work
I'm attempting to create a project similar to a social networking site, where users can follow each other. The follow button on someone's profile will allow your own profile to follow that user. Currently when I click the follow button on a profile, nothing happens. There's no error either. I'm pretty stuck with where to go on this. Any help is super appreciated. Relevant parts of urls.py: path("fol/<str:username>", views.fol, name="fol"), path("following_list/<str:username>", views.following_list, name='following_list'), path("profile/<str:username>", views.profile, name="profile"), views.py - function for following: def fol(request, username): if request.method == 'GET': currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts.count(), 'profileuser': profileuser, 'follower': follower, 'totalfollower': totalfollower, 'following': following, 'totalfollowing': totalfollowing, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) else: currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if not following_each_other: f = Follow.objects.create(target=profileuser, follower=currentuser) f.save() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=request.user, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) context = { 'posts': posts.count(), … -
Vscode not reading in my default value and telling me theres no value typed in
Below is my code where I try to make 0 as a default if no information is added into my admin. I am confused because my error "ValueError: Field 'asking_price' expected a number but got ' '." is telling me I have put in no information when I try to make my migrations.1 -
How to rectify post request error on django
I'm learning to build a custom registration section on django and it hasn't been easy for me to understand. I'm using a tutorial, but I'm stuck for a couple of hours now. The issue is that when I click on the submit button I get 404 error stating that the url I requested does not match with any in my django project. It worked for the instructor but mine throws back status404 which states The current path, account/, didn’t match any of these. . Where am I getting it wrong? url.py (django app) urlpatterns = [ path('', include('account.urls', namespace='account')) ] url.py (account) urlpatterns = [ path('account/register', views.account_register, name='register'), path('activate/<slug:uidb64>/<slug:token>)/', views.account_activate, name='activate') ] ================ views.py if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Account' message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = … -
After user click on like button page should not refresh(redirect) and update count of likes
When user click to like a post the web page should not refresh(redirect) and count of the likes should be updated. How can I achieve this please help me. Here is my block of code <a style="{% if request.session.email %}pointer-events: auto;{% else %}pointer-events: none;{% endif %}" href="/post_comment_like/{{j.id}}"> <i class="fa fa-thumbs-o-up" aria-hidden="true" style="color: gray;"></i></a> views.py def post_comment_like(request, id): if (request.session.get('email') is None) or (request.session.get('email') == ""): return HttpResponseRedirect("/home") email = request.session.get('email') qury = Comment.objects.get(id=id) obj_id = qury.object_id qury_like = Comment_like.objects.filter(email=email) qury_like = Comment_like.objects.filter(email=email, object_id=qury.id, dislike_comment="1").first() if qury_like: qury_like.delete() save_form = Comment_like(email=email, user_name=request.session.get('name'), content_type=qury.content_type, object_id=qury.id, content=qury.content, flag_reply=qury.flag_reply, flag_comment_id=qury.flag_comment_id, flag_level=qury.flag_level, like_comment='1') save_form.save() qury.like_comment = '1' qury.dislike_comment = '0' qury.save() # return redirect(request.META.get('HTTP_REFERER')) return HttpResponseRedirect(reverse('detail', args=[str(obj_id)])) -
Django, JavaScript PUT request 403 forbidden?
I am trying to make a fetch "PUT" method in my JavaScript code to send the textarea value to my django backend and in my views.py I want to update my post description and save the post. Why I am getting PUT 403 forbidden error tho? index.js function build_post(post){ // create new div for each thing that needs to be shown current_logged_in_user = document.querySelector('#user_detail').value; const element = document.createElement('div'); const post_username = document.createElement('div'); const post_description = document.createElement('div'); const post_date_added = document.createElement('div'); const post_likes = document.createElement('div'); // add the text for each div post_username.innerHTML = 'Username: ' + post.poster; post_description.innerHTML = 'Content: ' + post.description; post_date_added.innerHTML = 'Date: ' + post.date_added; post_likes.innerHTML = 'Likes: ' + post.likes; // append all divs to display-post element.appendChild(post_username); element.appendChild(post_description); element.appendChild(post_date_added); element.appendChild(post_likes); element.classList.add('element'); post_username.addEventListener('click', function() { load_user_info(post.poster); load_user_posts(post.poster); }); if (current_logged_in_user == post.poster){ const edit_button = document.createElement('button'); const save_button = document.createElement('button'); edit_button.innerHTML += 'Edit' save_button.innerHTML += 'Save' element.appendChild(edit_button); element.appendChild(save_button); var editableText = document.createElement('TEXTAREA'); editableText.value = post.description edit_button.addEventListener('click', function() { post_description.replaceWith(editableText) }); save_button.addEventListener('click', function() { console.log(editableText.value); **fetch(`/posts/${post.id}`, { method: 'PUT', body: JSON.stringify({ description: editableText.value }) })** }); } document.querySelector('#show-posts').appendChild(element) } views.py def post(request, post_id): # Query for requested post try: post = NewPost.objects.get(pk=post_id) except NewPost.DoesNotExist: return JsonResponse({"error": "Post … -
How to save base64 string as an image to local server in django python
I have base64 string and I try to encode it and then save it in a folder. So far I have been doing this data = {"status":"Trial"} if request.method == 'POST': decoded = request.body.decode("UTF-8") userdata = json.loads(decoded) image = base64.b64decode(str(userdata)) save_path = "Dummy/test" if not os.path.exists(save_path): pathlib.Path(save_path).mkdir(parents=True, exist_ok=True) img_save_path = "%s/%s%s" % (save_path, str(uuid.uuid4()), ".jpeg") with open(img_save_path, "wb+") as f: for chunk in image.chunks(): f.write(chunk) return JsonResponse(data) when I try the above code, the image is saved inside Dummy/test directory but when I open the image.. it says that the image can not be opened. Is there a right way to save base64 string as an Image in django python? -
How to configure firebase admin at Django server?
I am trying to add custom token for user authentication (phone number and password) and as per reference documents I would like to configure server to generate custom token. I have installed, $ sudo pip install firebase-admin and also setup an environment : export GOOGLE_APPLICATION_CREDENTIALS="[to json file at my server]" I am using Django project at my server where i have created all my APIs. I am stucked at this point where it says to initialize app: default_app = firebase_admin.initialize_app() Where should i write the above statement within Django files? and how should i generate endpoint to get custom token? Regards, PD -
Passing list dict to template not working django
I am trying to pass a list called eligable so that I can display on my website but when I run my website it does not display the list. I do not understand what is wrong. code: def specificDate(response): empName = employeeName.objects.all() eligable = [] if 'checkEmployee' in response.POST: n = response.POST.get("nameEmployee") specDate = response.POST.get("date") if employeeName.objects.filter(employee=n).exists() and Name.objects.filter(date=specDate).exists(): emp = employeeName.objects.get(employee=n) t = Name.objects.get(name=emp, date=specDate) overT = Name.objects.filter(name=emp, overtime=True) for item in overT: eligable.append(item.date) checkIn = t.timeIn.strftime("%H:%M:%S") checkOut = t.timeOut.strftime("%H:%M:%S") datee = datetime.strptime(specDate,'%Y-%m-%d') print("Here:: ",t.date) print("Month:: ",datee.month) messages.info(response, checkIn + ' - ' + checkOut) return redirect('/specificDate') else: messages.info(response, 'Name does not exist') else: pass return render(response, "main/specificDate.html", context={"empName":empName, "eligable":eligable}) This is the html to print my list: {% for item in eligable %} <div class="pad3"> {{item}} </div> -
Running Django management command from cron causes ImportError
I have a Django project running on an AWS Lightsail Bitnami Apache server that needs to regularly scrape data from a schedule model (I created a script for this, let's call it script_1). script_1 scrapes the data and, for uncovered items, it runs another script (script_2) at a predetermined time via a Linux at command. I have set up both scripts as Django management commands because they both access my models. Running script_1 directly from the command line (python /opt/bitnami/path/to/manage.py script_1) works perfectly. In order to automate this, I scheduled script_1 to run as a daily cron job. However, it's not working from cron. The problem is almost identical to this question, but the answer didn't work for me. I checked the mail it sends when the cron job runs and the output is as follows: X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/home/bitnami> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=bitnami> Message-Id: <20210505014501.7D91A80872@ip-dev-machine-address.ec2.internal> Date: Wed, 5 May 2021 01:45:01 +0000 (UTC) File "/opt/bitnami/path/to/manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax This line comes from raising an ImportError when importing execute_from_command_line. I haven't changed manage.py at all, see below for the file: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): … -
Django customer review forms
I am having trouble thinking of how to approach this. I want to create a form in django, that will be rendered on the index page, and it's only function is to be a customer review of the company. I feel like having a login and authentication would be too cumbersome for somebody to just jump on really quick and leave a review for the small business, so I just want them to be able to fill out the form. I had a different, more elaborate model built out, but I have decided to try and go simple. Just a name, a comment on the company, and a integer rating. Below is the model that I have now. Just not sure how I would go about doing this, building the views and forms and then just having the review rendered in html. Should I have a login or no? I just needed some advice because I have been having issues. I've even contemplated using the Rest Framework. This is what I have so far but not exactly sure if it will work. Not sure if this is the best place for my question, but I couldn't think of anywhere else.. …