Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding and removing friends with CustomUser model
now i have some troubles with launching add/remove views for my friends functional. Tha main error is 'WSGIRequest' object has no attribute 'CustomUser' I also have troubles with displaying a list of users on page. I am sure that problem is in using custom user model, but I couldn`t find the appropriate solution for it. These are always error strings: Friends.make_friend(request.CustomUser, new_friend) Friends.make_friend(request.CustomUser, new_friend) Here`s my code: views.py: def change_friends(request, operation, pk): new_friend = CustomUser.objects.get(pk=pk) if operation == 'add': Friends.make_friend(request.CustomUser, new_friend) elif operation == 'remove': Friends.lose_friend(request.User, new_friend) return redirect('posts:all') models.py: from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): class Gender(models.TextChoices): MALE = 'MR', _('Mister') FEMALE = 'MS', _('Misis') class AvatarType(models.TextChoices): WARRIOR = 'WR', _('Warrior') ELF = 'EL', _('Elf') GUARDIAN = 'GD', _('Guardian') HEALER = 'HL', _('Healer') SNIPER = 'SR', _('Sniper') first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) position = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) gender = models.CharField(max_length=2, choices=Gender.choices, default=Gender.MALE) avatar_type = models.CharField(max_length=2, choices=AvatarType.choices, default=AvatarType.ELF) email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class Friends(models.Model): users = models.ManyToManyField(CustomUser, related_name = 'friend_set') current_user = models.ForeignKey(CustomUser, related_name = 'owner', null = True, on_delete = models.CASCADE) … -
Mac OS Django-admin startproject mysite receives syntax error
I'm trying to follow the tutorial on https://docs.djangoproject.com/en/3.1/intro/tutorial01/ and have made it to the step where you are supposed to run django-admin startproject mysite in the command line. I have tried running the followings: django-admin startproject mysite django-admin.py startproject mysite django-admin startproject.py mysite $ django-admin startproject mysite and $ django-admin.py startproject mysite and all of them receive SyntaxError: invalid syntax either with a ^ under the "t" in "startproject" or under the $ when I've tried that. I've searched through about ten different posts trying to figure out how to proceed, and none of the answers provided have worked for me. They all continue to receive SyntaxError: invalid syntax I would really appreciate any insight into why this is happening and how to fix it. -
How to write regular expression url for list parameter in django urls
We have a django function with name and the following parameters @api_view("GET", "POST") def data(request, process, wo=[]): pass where process is interger and wo is list of integers and my django url path is something like this re_path(r"^wo_pai/(?P<process>[\d]+)/(?P<wo>[\d]+)", data), How can i modify the url in such a way that it will accept the list -
Pattern where python django view would respond back with 'Task still running' if the task take longer than a specified time
This is not about async or long-running job that can be run through Celery. Not often, but a few times, some of our web requests take longer, and if the Django view is still processing, our gateway will return a time-out to the front-end. I am looking for any established pattern in django where we can return the response saying 'Task still running' (HTTP code 100 or 102) if it goes beyond a certain time, but the task/thread continues execution. This way, we can handle the UI in front-end through some messaging, instead of giving an API time-out experience returned by our gateway. I am not looking for polling or the API sending another response, it just returns 102 response, but let the actual task execution continue. -
Django users under admin model
My project has operators and users. i want to map the users to operator.when someone logs in from operator account he/she can see users mapped to his account. E.g. Operator A and Operator B 5 users where user 1,3,5 are linked with Operator A and rest users are linked with operator B. Now when operator A cheks his admin panel, users 1,3,5 data can be reflected in his admin panel. Same thing goes with operator B and users 2,4. Please help how i can design the model or any other technique to achieve the goal. Thanks in advance. -
Create a permission in Django that can be optionally applied to superusers
I want to create a permission (or something that achieves the same thing) that can be applied to all users optionally, including super users. I can create a custom permission very easily: ct = ContentType.objects.get_for_model(MyModel) Permission.objects.create( name='optional permission', codename='optional_permission, content_type=ct) However, this will always return True for superusers user.has_perm('my_app_label.optional_permission') My use-case is: I'd like to create a queryset manager function that only returns Draft articles for users in Groups that have optional_permission applied. I'd like superusers to be exempt from seeing these draft articles if they want. -
NOT NULL constraint failed: home_profile.user_id
I have written an extension of the Django auth.user model which adds middle_name and phone fields to the model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) middle_name = models.CharField(max_length=20, blank=True) phone = models.CharField(max_length=10, blank=True) def __str__(self): return(f'{self.user.username} profile') I am using the following forms to accept input from the user. class RegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username', 'password1', 'password2'] class ProfileForm(forms.ModelForm): phone = forms.CharField(max_length=10, min_length=10) middle_name = forms.CharField(max_length=20, required=True) class Meta: model = Profile fields = ['middle_name', 'phone'] The view for the register route is as follows: def register(request): if request.method == 'POST': user_form = RegistrationForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data.get('username') user_form.save() profile_form.save() messages.success(request, f'Welcome { username }! Your account has been created. Sign in to continue.') return redirect('login') else: return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form }) else: user_form = RegistrationForm() profile_form = ProfileForm() return render(request, 'home/register.html', { 'user_form': user_form, 'profile_form': profile_form }) This is contents of the signals.py file from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() The issue … -
Django cannot connect to mysql
So i put my django app and mysql inside docker container. Here is what i do Docker file FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app and here is my docker-compose-yml version: '3' services: db: image: mysql:latest ports: - "3306:3306" environment: - MYSQL_DATABASE=django_example - MYSQL_USER=root - MYSQL_PASSWORD=123456 - MYSQL_ROOT_PASSWORD=123456 volumes: - "./db:/var/lib/mysql" web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/app - /tmp/app/mysqld:/run/mysqld Then i run it with docker-compose up I get this error MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Here is my database setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_example', 'USER': 'root', 'PASSWORD': '123456', 'HOST': 'localhost', 'PORT': '3306', } } My docker ps --all CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c61ac60bc037 mysql:latest "docker-entrypoint.s…" 2 minutes ago Up 34 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp py_rest_api_db_1 f00857755a46 py_rest_api_web "python manage.py ru…" 5 minutes ago Up 34 seconds 0.0.0.0:8000->8000/tcp py_rest_api_web_1 So how can i fix it ? did i miss something? -
Django Dependent/Chained Dropdown List - Select A Valid Choice Error
I have implemented a Dependent dropdown list within Django but when I try to submit the form I get the following error 'Select a valid choice. That choice is not one of the available choices.' I have spent a while looking on the web for the answer and have tried a few with little avail. From my understanding and reading, this is an error because I render the form with a queryset of none. Then I use ajax to fill in the options. Even though I have updated the dropdown list, the form validation is checking my submitted answer against a queryset of none - thus the error. So i'm hoping someone can help me to update the choices the form will accepted on form submission. views.py # stage6 is where I render my view and check validation def stage6(request): form_deal = DealForm(request.POST or None, prefix='inst') if form_deal.is_valid(): form_deal.save() messages.success(request, 'Deal added successfully.') form_deal = DealForm() context = { 'dform': form_deal, } return render(request, 'stages/stage6/stage6.html', context) # This is used for my ajax request def load_offers(request): property_process_id = request.GET.get('propertyprocess_link') offers = Offer.objects.filter(propertyprocess_link=property_process_id).order_by('id') return render(request, 'stages/stage6/offers_dropdown_list.html', {'offers': offers}) forms.py class DealForm(forms.ModelForm): deal_date = forms.CharField( label='', widget=forms.TextInput(attrs={'type': 'date'}) ) target_move_date = forms.CharField( … -
Django templates {% include %} fallback value
I'm trying to dynamically load a template like so: {% include 'some-folder/'|add:var|add:'.html' %} But these templates are not always present. So I would like to add a fallback value/default template to be loaded if one being requested is not found. Is this possible? If not (out-of-the-box), how can I write a custom templatetag that does so? -
How to get user information from database when the only thing in client browser is the AuthToken?
Building my first app with a real backend. In my app, when a user registers or logs in (with username and password), a token is saved to the cookies of their browser. After registration (or when logging in), I can easily return information pertaining to this particular user (name, id, etc.). # Django REST backend for loggin in and getting user token class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class( data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'user_type': user.user_type, }) Next time the user accesses the app in the same device, the token will be there and I can make the http requests for which a token is necessary. However, since I won't be logging the user in again (not asking for username and password every single session), I won't get that user's additional information. In my React app I would like to have the user set in state at all times, e.g. user = {first_name: 'john', user_type: 'p'} but I don't know how to get the user info when the only thing I have is their token. I am more than welcome to criticism to … -
How to redirect for last page visit DJANGO PYTHON
good evening! Hope everything is great! Well, I have a little problem with redirect in Django, I was trying to make a comment section for my web app but after "posting" the comment, I can only redirect the user to my homepage (through return redirect ('/') Models.py: class Task(models.Model): title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) responsable = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name="author", default=author) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','HR'),('L','Legal'),('F','Finances'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') is_public = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("task-detail", kwargs={"pk": self.pk}) class Comment(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=User) body = models.TextField(help_text='Add a comment') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('-created',) def __str__(self): return '%s - %s' % (self.task.title, self.author) Views.py: class CommentCreate(CreateView): model = Comment fields = ['body'] def form_valid(self, form): form.instance.task_id = self.kwargs['pk'] form.instance.author = self.request.user form.instance.created = timezone.now() form.save() return redirect('/') urls.py from django.urls import path, include from . import views from .views import (DashboardTaskAppView, TaskDetailView, TaskCreateView, TaskUpdateView, DashboardTaskAppViewPublic, TaskDeleteView, CommentCreate) urlpatterns = [ … -
NameError: name 'Profile' is not defined
here is my models.py code. im trying to run the python3.8 manage.py migrate command to create the tables for the database but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Image(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null='True', blank=True) image = models.ImageField(upload_to = 'pics/') name = models.CharField(max_length=50,blank=True) caption = models.CharField(max_length=250, blank=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, ) date_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): comment = models.TextField() image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True ) name = models.CharField(max_length=100, blank=True) user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True ) created = models.DateTimeField(auto_now_add=True, null=True) class Profile(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/', default='default.png') bio = models.TextField(max_length=500, default="My Bio", blank=True) followers = models.ManyToManyField(User, related_name="followers", blank=True) following = models.ManyToManyField(User, related_name="following", blank=True) -
How to set post_id to resolve error : 'django.db.utils.IntegrityError: NOT NULL constraint failed: posts_comment.post_id'?
Well I am using django and i am trying to add commenting with ajax. when i am clicking on the comment submit button that is performing no action but in the terminal it showing me 'django.db.utils.IntegrityError: NOT NULL constraint failed: posts_comment.post_id' error. I have double checked my models.py but still didn't get how to solve it. model.py class Comment(MPTTModel): author = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE, default=None, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') post = models.ForeignKey(Post ,related_name='comments', on_delete=models.CASCADE) body = models.TextField() create_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) view.py def single_post(request ,*args, **kwargs): slug=kwargs.get('slug') print(slug,'slug') pk=kwargs.get('pk') print(pk,'pk') post = get_object_or_404(Post,pk=pk,slug=slug) allcomments = post.comments.filter(status=True) comment_form = CommentForm() return render( request, 'posts/post_test.html', { 'post': post, 'comment_form': comment_form, 'allcomments': allcomments, } ) def addcomment(request): if request.method == 'POST': comment_form = CommentForm(request.POST) print(comment_form) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('body') user = request.user.username user_comment.author = request.user user_comment.save() return JsonResponse({'result2': result, 'user': user}) urls.py urlpatterns = [ path('test/<int:pk>/<str:slug>/',views.single_post,name ='post_detail'), path('commented/',views.addcomment,name='addcomment'), ] if more information is require than tell me in a comments session. I will update my question with that information. Thank you ! -
Form is always not valid/Cannot assign instance
I've been struggling with my issue for a while. It continues my previous question: How to handle data from two forms in one view? I figured out that the problem is in this form: class TranslatorChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(TranslatorChoice, self).__init__(*args, **kwargs) self.fields['owner'].queryset = Translator.objects.all().filter(owner = self.user_id) owner = forms.ModelChoiceField(queryset = None) class Meta: model = Translator fields = ('owner', ) Its' model: class Translator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='created_translators' ) def __str__(self): return str(self.user) And the view: def link_translator(request): if request.method == 'POST': form = TranslatorChoice(request.POST) if form.is_valid(): pass return redirect('dashboard') else: form = TranslatorChoice(user_id=request.user) With the code above the form gives me options to choose from but whenever I hit submit the form asks me to select a valid choice. However, if I change Translator.objects.all().filter(owner = self.user_id) to Translator.objects.all() form.is_valid() gives me true but another error appears: ValueError at /linkt/ Cannot assign "<Translator: rawkymonk>": "Translator.owner" must be a "User" instance. My guess that the main problem is ModelChoiceField so if there's an alternative to it please tell me. -
You have 29 unapplied migration(s). Your project may not work properly for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django
I wasn't sure how to set up Doccano on my computer to perform sequence labeling tasks so I followed the instructions from this website. While following the instructions and running the code on git bash, I encountered some errors. Could you please explain what these errors mean and how to rectify them? Thanks $ python manage.py createsuperuser (this is the error below after running this code on git bash) You have 29 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, api, auth, authtoken, contenttypes, sessions, social_django. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\okekec\AppData\Local\Continuum\anaconda3\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auth_user -
Django How to pass a checkbox value into a function
I have created a table in django, each rows has a id and a checkbox. I have assigned the value for each checkbox as the id of the row. When the user clicks on the checkbox I want it to call a function and pass in the id number as well as whether that checkbox is now checked. sets.html: <td class="text-center"> {% if set.status %} <input type="checkbox" checked name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'"> {% else %} <input type="checkbox" name="inputs" value="{{ set.id }}" onclick="location.href='{% url 'dashboard:setUpdate' %}'"> {% endif %} </td> views.py def set_update(request): print(request.GET.getlist('inputs')) return redirect('dashboard:sets') -
Authenticate two parameters in Django Rest Framework
I built a simple api endpoint using Django Rest Framework where, in order to see the endpoint's data, the user needs to input a public key and a secret key. Here is what i did: class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): # Get the username and password public = request.data.get('public', None) secret = request.data.get('secret', None) if not public or not secret: raise exceptions.AuthenticationFailed(_('No credentials provided.')) credentials = { get_user_model().USERNAME_FIELD: public, 'secret': secret } user = authenticate(**credentials) if user is None: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (user, None) # authentication successful class My_View(viewsets.ModelViewSet): authentication_classes = (CustomAuthentication,) ... Now, i'm trying to access the endpoint like that: localhost/api/endpoint/?public=TEST&secret=TEST but every time i get "No credentials provided.". What do i need to do in order to be authenticated here? Thanks in advance! -
Djagno Rest Framework Serialization only reading in first column
I am trying to read in data from a list into a serializer. When the method is executed below it only appends the name of the dashboard to my widgets_value table. A little bit about widget_endpoint_post method it first takes in a request object that looks like request object {'dashboard_name': 'check_out', 'widgets': [{'position': {'top': 1, 'left': 1, 'width': 1, 'height': 1}, 'name': 0, 'content': {}, 'public_private': '', 'owner': '', 'title': ''}], 'type': 'public', 'user': 'Person_1'} The method below uses two serializers one to create a table to reference a dashboard another to save each dashboard's layout views.py @api_view(['POST']) def widget_endpoint_post(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) serializer=AddDashboardSerializer(data=request.data) data={} if serializer.is_valid(): account=serializer.save() body['dashboard_name']=account.dashboard_name body['user']=account.user body['type']=account.type print('test') else: data = serializer.errors print(body['widgets']) # print(body['widgets']) for x in range(len(body['widgets'])): print(body['widgets'][x]['position']['top']) serializer2=AddWidgitSerializer(data=request.data) data={} if serializer2.is_valid(): account=serializer2.save() body['dashboard_name'] = account.dashboard_name body['type'] = account.widget_type body['user'] = account.owner body['widgets'][x]['name'] = account.widget_name body['widgets'][x]['position']['top'] = account.top body['widgets'][x]['position']['left'] = account.left body['widgets'][x]['position']['width']=account.width body['widgets'][x]['position']['height']=account.height else: data=serializer.errors return Response('Dashboard saved') serializers.py class AddDashboardSerializer(serializers.ModelSerializer): dashboard_name=serializers.CharField(), user=serializers.CharField(), type=serializers.CharField(), class Meta: model= DashboardView fields=['dashboard_name','user','type'] class AddWidgitSerializer(serializers.ModelSerializer): dashboard_name=serializers.CharField(), widget_name=serializers.CharField(), top=serializers.CharField(), left=serializers.CharField(), height=serializers.CharField(), width=serializers.CharField(), widget_type=serializers.CharField, owner=serializers.CharField, class Meta: model=WidgetView fields=['dashboard_name','widget_name','top','left','height','width','widget_type','owner'] Below is the WidgetView table it only validates the name of the dashboard and I don't know why. -
Add custom attributes to Django models through mixins
I'm trying to add custom fields to models to be displayed as columns when inlined in admin. These fields are derived from a separate abstract model. I would like to compute these values at display time. Details below, issues tl;dr: For multiple ingredients, all rows are updated with the last computed value. When there are two ingredients 1 and 2, nutritional info for 2 is displayed for both ingredients. The column name displayed in the inline table is "Get nutrient value", and not 'calories', 'fats', etc. class Nutrition(models.Model): class Meta: abstract = True calories = models.DecimalField(max_digits=10, decimal_places=2, default=0) proteins = models.DecimalField(max_digits=10, decimal_places=2, default=0) fats = models.DecimalField(max_digits=10, decimal_places=2, default=0) carbohydrates = models.DecimalField(max_digits=10, decimal_places=2, default=0) class RecipeIngredient(..., NutritionMixin) ... size = models.DecimalField(max_digits=10, decimal_places=2, default=1) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) ... Ingredient stores the nutrition information for each ingredient, and RecipeIngredient.size stores the quantity in the current recipe. I define a mixin class, with the goal of adding a method for each field in Nutrition. from functools import partial from functools import update_wrapper def get_nutrient_value(base, derived, nutrient_name): ratio = nutrition.get_measurement_ratio(base, derived) return round(ratio*getattr(base, nutrient_name), 2) class NutritionMixin(object): def __init__(self, *args, **kwargs): for f in Nutrition._meta.fields: if self.ingredient_id: base = Ingredient.objects.get(id=self.ingredient_id) derived = self method … -
how to get the value in flask from Django?
I am beginner in Django & flask,I created a form in django and i want the value in the form to be passed to flask webservice where it takes the value and invoke the method and return back the outputs back to Django Where i can display the outputs.Below are the codes: views.py import django from django.shortcuts import render from django.http import HttpResponse import requests import math import json # Create your views here. def hi(request): return render(request,'hello/index.html') def output(request): n=int(request.POST.get("no")) response=requests.post("http://127.0.0.1:5000/") return render(request,'hello/index.html',{'out':response['out'],'value':response['value']}) index.html <!DOCTYPE html> <html> <body> <form action="output" method="post"> {% csrf_token %} Enter a number: <br/> <input type="number" name="no" value="0"> <br/> <input type="submit" ><br/> </form> <div> {{out}}</div> </body> </html> flask code from flask import Flask,jsonify,request import math import django app = Flask(__name__) @app.route('/',methods=['POST']) def index(): n=request.form["no"] r=[] for i in range(int(n)+1): r.append(i) a=[] for i in range(int(n)+1): com=math.factorial(int(n))/(math.factorial(r[i])*math.factorial(int(n)-r[i])) a.append(com) return jsonify({'out' : a,'value': r}) if __name__ == '__main__': app.run(debug=True) -
How do I make custom filters work in Django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEAR CHOICE" the page refreshes but it doesn't work. I think my "year_filter_method" is not working also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! **Note it doesn't work with or without pagination. models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = Music.Year return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.html {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' %} … -
Django: Multiplication of n Decimal Fields returns result with n*2 decimal places
I'm using django, and I have this model: class CartLine(DeletableModel): product = models.ForeignKey('Product', related_name='cart_lines', on_delete=do_nothing) cart = models.ForeignKey('Cart', related_name='lines', on_delete=do_nothing) quantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=_('Quantity')) @property def total_sum(self): return self.product.price * self.quantity class Meta: verbose_name = _('Cart Line') verbose_name_plural = _('Cart Lines') when I used the property total_sum in the template like {{ line.product.price }}, it return the result 300.0000. even when I tried with the filter tag floatformat like {{ line.product.price|floatformat:2 }} it returned the same value, it didn't format it. so I went to the python shell and tried it, and it returned the same value: >>> cartline.total_sum Decimal('300.0000') and when I changed the property to: @property def total_sum(self): return self.product.price * self.quantity * self.quantity and tested it in the console: cartline.total_sum Decimal('900.000000') it's like concatinating the decimal places... how can I fix that or work around that to limit the display to 2 decimal places when I do the multiplication or any other operation? -
How to allow configurable choices on a model of a django library without permanent migration changes?
I have a model in a library with a ChoicesField. Ideally I would want to allow people to define these choices in the settings of the apps that will use the library. This is not really possible as this would create/require a new migration in the library for every change made in the settings for every app!!! The django docs state in https://docs.djangoproject.com/en/dev/topics/migrations/ that is not possible to skip that model. Django will make migrations for any change to your models or fields - even options that don’t affect the database - as the only way it can reconstruct a field correctly is to have all the changes in the history, and you might need those options in some data migrations later on (for example, if you’ve set custom validators). What are the best alternatives? I could subclass ChoicesField to not trigger migrations, but it's not really the most elegant solution. Is there any nice alternative to do something similar? (I would also try to avoid having another model) -
Comment body for blog returning none
I'm including a comment section for a blog and the body of the comments return none instead of the comment entered. Point me in the direction of what I'm doing wrong. The views.py for the comment section def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) #List if active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': cd = form.cleaned_data #A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): #Create comment object but don't save to db yet new_comment = comment_form.save(commit=False) #Assign the current post to the comment new_comment.post = post #Save the comment to db new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form}) the models.py of the comment section class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=50) #user's name email =models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'comment by {self.name} on {self.post}', self.body In forms.py I'm using the ModelForm method like so: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') detail.html {% with comments.count as total_comments %} <h2> {{ total_comments …