Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link fixed choices to new created questions in django
I'm very new as a django developer and I'm attempting to build a ranking web app. What I wanted to do is once a new question is created by the user through a crispy form, automatically changed the m2m model and link that new question with the choices. The choices are a fixed rank from 1 to 5 and they cannot be manipulated by users and not showing on the question create form. From what I read, I guess that this operation could be done by m2m_changed signal (or post_save, not sure), but I'm not really familiar with its functionality. I tried several times on differents ways but I'm not addresing good results. When I go to the admin page and set the choices to the new question manually this works perfect; same thing when I create the question and run the for loop by command line through the shell, but what I want is automate this process when the question is created by users. Sorry for the extensive, hope to be clearly enough! Thanks for the help!! I breakdown my codes below. models.py class Choice(models.Model): choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Question(models.Model): choice = … -
Displaying the value of ManyToMany relationship in django admin
I am trying to display a brand of a bike in my django admin panel. I have managed to display the title, but I am struggling with the brand. Here's my models.py: class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand, null=True) def __str__(self): return self.item.title class Brand(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name I have tried that: def __str__(self): return self.brand.name But nothing is displaying then. Any ideas how to display the self.item.title and brand name at the same time? -
Django how to multiply (.count) of one field in to another field in models and show the result in template
I have a project that may give points to persons who post. I have two models (Post and Points). I want to count each user post in (Post) and multiply the result to create_post_points field in (Points) and show the result in template. What i tried to do (signals, aggregation, queryset, intermediate class in models) but i failed. Can any one help me? Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) post_date = models.DateTimeField(default=timezone.now) post_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) favourite = models.ManyToManyField(User, related_name='favourite', blank=True) class Points (models.Model): create_post_points = models.IntegerField() create_comment_points = models.IntegerField() Views.py def PostListView(request): posts = Post.objects.all() context = { 'title': 'Home Page', 'posts': posts, } return render(request, 'blog/index.html', context) Templates {% for post in posts %} <div class="border p-3 mb-3"> <div class="media"> <img class="img-fluid rounded-circle border m-2" style="width: 70px; height:70px;" src="{{post.author.profile.image.url}}" alt="User Photo"> <div class="media-body"> <h5><a class="text-primary" href="{% url 'detail' post.id %}">{{post.title}}</a></h5> <h6 class="text-dark">Auther Score : {{******}}</h6> <p>{{post.content |truncatechars:150 }} <a class="text-primary" href="{% url 'detail' post.id %}">read more</a></p> </div> </div> </div> {% endfor %} -
Communication between two docker containers based on multi-tenant architecture
I have two django projects (mircroservices), running in separate docker containers. Both projects are using django-tenant-schemas. How can I send a request from serice-bar to service-foo on url http://boohoo.site.com:18150/api/me/, 18150 is the PORT of project-a? I need to use the tenant url so that project-a can verify the tenant and process the request. I can send a request by using the container name, but that doesn't work because if I use http://site.foo:18150/api/me, it sends the request successfully, but there's no tenant with definition site.foo. Here's the docker-compose.yml: version: '3.3' services: db: container_name: site.postgres image: postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres foo: container_name: site.foo build: context: ../poll command: python /app/foo/src/manage.py runserver 0.0.0.0:18150 depends_on: - db environment: - DB_HOST=site.postgres - DJANGO_SETTINGS_MODULE=main.settings.dev stdin_open: true tty: true ports: - "18150:18150" bar: container_name: site.bar build: context: ../toll command: python /app/bar/src/manage.py runserver 0.0.0.0:18381 depends_on: - db environment: - DB_HOST=site.postgres - DJANGO_SETTINGS_MODULE=main.settings.dev stdin_open: true tty: true ports: - "18381:18381" -
django annotate queryset with field comparison result
I have a queryset like this: predicts = Prediction.objects.select_related('match').filter(match_id=pk) I need to annotate this with a new field is_correct. I need to compare two string fields and the result should be annotated in this new field. the fields that I want to compare are: predict from Prediction table result from Match table (that has been joined through select_related) I need to know what expression should I put inside my annotate function; below I have my current code which throughs a TypeError exception: predicts = predicts.annotate(is_correct=(F('predict') == F('result'))) all help will be greatly appreciated. -
No Reverse Match /'learning_log_app_1' is not a registered namespace
why every time its popping up with this text however the names of templates are identical. -
I'm getting an data integrity also and index error while updating the primary key team id , how to resolve the data integrity error
elif request.method == 'POST': alphabet = string.ascii_letters + string.digits #leader_name = request.POST.get('team_cordinator_name').split(' ') leader_name = request.POST.get('team_cordinator_name') leader_fname, leader_lname = name_checker(leader_name) #leader_fname = leader_name[0] # if len(leader_name) > 1: # leader_lname = leader_name[1] ppUser = PolicyPortalUser2020.objects.create( fname = leader_fname, lname = leader_lname, email = request.POST.get('team_cordinator_email'), password = ''.join(secrets.choice(alphabet) for i in range(20)), is_PP_user = True, ) teacherObj = Teacher2020.objects.create( name = request.POST.get('teacher_name').split(' ', 1), school = request.POST.get('teacher_name'), mobile_no = request.POST.get('teacher_mobile'), email = request.POST.get('teacher_email'), ) try: if request.POST.get('org_type') == 'school': max_team_id = Team2020.objects.filter(team_id__contains='2020IRSCPOLICYS').aggregate(Max('team_id')) else: max_team_id = Team2020.objects.exclude(team_id__contains='2020IRSCPOLICYS').aggregate(Max('team_id')) except: if request.POST.get('org_type') == 'school': max_team_id = '2020IRSCPOLICYS001' else: max_team_id = '2020IRSCPOLICY001' max_team_id = int(max_team_id[-3:]) + 1 if request.POST.get('org_type') == 'school': max_team_id = '2020IRSCPOLICYS' + str(max_team_id) else: max_team_id = '2020IRSCPOLICY' + str(max_team_id) tObj = Team2020.objects.create( team_id = max_team_id, tname=request.POST.get('team_name'), institute = request.POST.get('institute'), pUser = ppUser, teacher = teacherObj, city = request.POST.get('city'), state = request.POST.get('state'), #is_school = request.POST.get('school'), shall we use these fields to identify #is_college = request.POST.get('college'), ) class Team2020(models.Model): pUser = models.OneToOneField(PolicyPortalUser2020,on_delete=models.CASCADE,blank=True,null=True) phase = models.ForeignKey(Phase2020,on_delete=models.DO_NOTHING,blank=True,null=True) teacher = models.ForeignKey(Teacher2020,on_delete=models.DO_NOTHING,blank=True,null=True) notifications = models.ManyToManyField(Notifications2020,blank=True,) is_offer_generated = models.BooleanField(default=False) id = models.IntegerField(null=True,blank=True) team_id = models.CharField(primary_key=True,max_length=30,) tname = models.TextField() city = models.CharField(max_length = 40, null = True, blank = True) state = models.TextField() is_member_registered = models.BooleanField(default=False) max_members = models.IntegerField(default=4) total_score … -
can't edit decimal value after setting it (Django)
As the title says, i can update the number value but not the decimal if i set it to 11.11 i cant change it to 11.12 but can change to 12.11 models price = models.DecimalField(max_digits=6, decimal_places=2) view def consumable_update(request, pk): current_consumable = get_object_or_404(models.Consumables, pk=pk) edit_consumable_form = forms.EditConsumableForm(request.POST, name=current_consumable.name, price=current_consumable.price) if request.method == 'POST': if edit_consumable_form.is_valid(): name = edit_consumable_form.cleaned_data['name'] price = edit_consumable_form.cleaned_data['price'] if models.Consumables.objects.filter(Q(name=name) & ~Q(id=current_consumable.id)).exists(): messages.add_message(request, messages.INFO, _('إسم الخامة مضاف من قبل بالفعل')) else: current_consumable.name = name current_consumable.price = price current_consumable.save() messages.add_message(request, messages.INFO, _('تم تعديل الخامة بنجاح')) return redirect('consumable_details', pk=current_consumable.id) else: edit_consumable_form = forms.EditConsumableForm(name=current_consumable.name, price=current_consumable.price) context = { 'current_consumable': current_consumable, 'edit_consumable_form': edit_consumable_form, } return render(request, 'consumable_update.html', context) forms.py class EditConsumableForm(forms.Form): def __init__(self, *args, **kwargs): self.name = kwargs.pop("name") self.price = kwargs.pop("price") super(EditConsumableForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs = {'value': self.name} self.fields['price'].widget.attrs = {'value': self.price} name = forms.CharField(widget=forms.TextInput) price = forms.DecimalField(widget=forms.NumberInput) -
storing a list of data in a list django
I am creating an upvoting system where the user upvotes, however to prevent a user from voting more than once I need to store a list of all users who have upvoted the post, I am using sqlite3 database, I would like to know how to go about storing these users in a list in my post model, I have tried several diffrent options but they havent worked. Database: sqlite3 Python Version: 3.8 Django Version: 3.0.3 -
Django migrate fails on Postgresql backend due to ERROR: syntax error at or near "="
Some background: I'm trying to install the arches project on Windows. After some problems, I've seen it is recommended to run it on Linux, so now I'm running on Ubuntu terminal for Windows. When I run python manage.py setup_db, I receive the following query and output: SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IN ('jerarch', 'template_postgis'); DROP DATABASE IF EXISTS jerarch; CREATE DATABASE jerarch WITH OWNER = ENCODING = 'UTF8' CONNECTION LIMIT=-1 TEMPLATE = template_postgis; ERROR: syntax error at or near "=" LINE 4: ENCODING = 'UTF8' ^ I was thinking it might be an ENGINE problem is settings.py, but I'm using the default django.contrib.gis.db.backends.postgis that came with the project. Chaning this configuration to the known django.db.backends.postgresql gives the same output. It looks like a legit syntax error, so I'm not sure why is the backend generarating this query (with the = sign). -
Django — Can't get static CSS files to load
What im trying to link in index.html <link rel="stylesheet" href="{% static 'assets/css/main.css' %}"/> and I have also done {%load static%} my file structure is like this: signup/static/assets/css/main.css settings.py STATIC_URL = 'signup/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] the error: [29/Feb/2020 17:19:31] "POST /postsign/ HTTP/1.1" 200 3445 Not Found: /postsign/signup/static/assets/css/main.css I cant understand where that /postsign/ is coming from my urls.py is like this: urlpatterns = [ path('admin/', admin.site.urls), path('', views.signIn), path('postsign/', views.postsign), path('logout/', views.logout, name="log"), path('signup/', views.signUp, name="signup"), path('postsignup/', views.postsignup, name="postsignup"), path('profile/', views.profile, name="prof"), ] and the postsign method is: def postsign(request): email = request.POST.get('Email') passw = request.POST.get("Password") try: user = authe.sign_in_with_email_and_password(email, passw) except: message = "Invalid Username or Password" return render(request, "signin.html", {"messg": message}) print(user['idToken']) session_id = user['idToken'] request.session['uid'] = str(session_id) return render(request, "index.html") -
How to get other field data when using values and annotate for the group in Django
i want to fetch 1 product for each product_type_id for specific brands. so, I wrote this query it returns proper output but in my product model, there are other several fields like product_name, product_info, etc that are not accessible why? it only returns product_type_id & price. plans_data = Product.objects.filter(brand__brand_id = brand_data_1.brand_id).values('product_type_id').annotate(min_brand_price=Min('product_price')) -
Django / Nginx does not server debug toolbar static files
Unbale to understand what kind of issue, Nginx does not serve some JS / CSS from folder I was trying to integrate debug_toolbar to my existing django project and all files that are realted to debug_toolbar(JS / Img / CSS) not being served. Successful response for "app.js" request from project http://10.0.0.15/static/js/app.js - Resp code is 200 [29/Feb/2020:12:09:34 +0000] "GET /static/js/app.js HTTP/1.1" 200 8474 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36" 0.000 - . 10.0.0.1 200 - 767 8831 Failure response for "toolbar.css" http://10.222.222.15/static/debug_toolbar/css/toolbar.css - Resp code is 400 2020/02/29 12:11:33 [error] 13#13: *2 open() "/home/user/app/static/debug_toolbar/css/toolbar.css" failed (2: No such file or directory), client: 10.0.0.1, server: , request: "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1", host: "10.0.0.15", referrer: "http://10.0.0.15/static/debug_toolbar/css/" [29/Feb/2020:12:11:33 +0000] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 404 197 "http://10.0.0.15/static/debug_toolbar/css/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36" 0.000 - . 10.0.0.1 404 - 827 406 **Even though when i configured alias for static to assets in nginx config, nginx is looking for stating folder not assets ** Mentioned below is djnago configuration. **I just run static RUN python manage.py collectstatic --noinput in dockerfile by enabling "TOOLBAR_ENABLE" in environment, when i inspect all required resources are found in … -
Django rest framework register login api
I am a beginner in Django Git Repo I was creating the register and login API, and I have also created the register API, and there is nothing wrong with that, but I did not know anything about the login API so I got an error, in my opinion, serializers.py and There is a slight error in the views.py, please tell me the error so I know where my error is. File "/Users/sierra/Courses/LoginAPI/form/serializers.py",line 14 if Account.objects.filter(email=email,password=password).exists() : TabError: inconsistent use of tabs and spaces in indentationBlockquote serializers.py from rest_framework import serializers from form.models import Account # from django.contrib.auth.models import User class LoginSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['email', 'password',] extra_kwargs = {'password': {'write_only': True}} if Account.objects.filter(email=email,password=password).exists() : return True return False # def validate(self, data): # password = data.get('password') # email = data.get('email') # def username_present(email,password): class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = Account fields = ['email', 'username', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account views.py from django.shortcuts import render from rest_framework import status from … -
How to change get_object to detail = False in Django APIView?
I have a view looking like below class UserFpProfileView(generics.GenericAPIView, mixins.CreateModelMixin, mixins.RetrieveModelMixin): serializer_class = UserFpProfileSerializer permission_classes = (permissions.IsAuthenticated,) authentication_classes = (authentication.TokenAuthentication,) def post(self, request, *args, **kwargs): if self.request.user.type != 'fp': raise exceptions.PermissionDenied(detail='FP 계정만 접근할 수 있습니다.') serializer = self.get_serializer( data=request.data ) serializer.is_valid(raise_exception=True) serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_200_OK) @action(detail=False) def get_object(self): # Raise error if user type is not fp if self.request.user.type != 'fp': raise exceptions.PermissionDenied(detail='FP 계정만 접근할 수 있습니다.') profile = UserFpProfile.objects.filter(user=self.request.user) return profile The post request works fine; however, get_object is pointing to /:id detail route. So I added an action decorator to specify that detail=False; however, this doesn't seem to change the fact that I need to enter id at the end. I don't want to use ListRetrieve because that makes the return value an array. How do I either change the return value from array to single object in get_queryset action or loos the detail part in the URL in get_object? -
Django Rest Framework: URL with nested resources and two ID's
I'm working with DRF and I'm struggling to create a URL like this: /myApp/languages/<language_id>/countries/<country_id>/ Thanks to a previous question, I know that I can easily use the @action method decorator within DRF router's extra actions, to handle URLs with this format: /myApp/languages/<language_id>/countries/ However, I haven't found a way to register the new URL that I need, where I include an ID for the second resource: /myApp/languages/<language_id>/countries/<country_id>/ How can I do it with DRF? -
How to limit prefetch_related data in django
I've two tables brand and a product. each brand has multiple products. So. I used prefetch_related to get related products for a particular brand with only a minimum product price. but the problem is when I have 2 products with the same price it selects both records so how to limit this? alternatives_data = Brand.objects.filter(category__category_slug = category_slug).prefetch_related( Prefetch('products', queryset=Product.objects.annotate( min_brand_price=Min('brand__products__product_price') ).filter( product_price=F('min_brand_price') ).order_by('product_id'))) i tried everything but nothing work! -
Bulid error on Travis CI to Django 3.0.3 on GitHub repo
After adding .travis.yml file to project directory, travis ci is giving me errors that I can't solve. .travis.yml looks like this: language: python python: - "3.7" # command to install dependencies install: - pip install -r requirements.txt # command to run tests script: pytest The error I get is: Worker information 0.14s0.01s0.00s0.01s system_info Build system information 0.01s0.00s0.35s0.21s0.05s0.00s0.04s0.00s0.01s0.01s0.01s0.01s0.01s0.00s0.00s0.02s0.00s0.01s0.30s0.00s0.00s0.00s0.01s0.00s0.12s0.01s0.81s0.00s0.00s6.03s0.00s2.73s0.00s2.28s docker_mtu resolvconf git.checkout 1.05s$ git clone --depth=50 --branch=master https://github.com/ChrisAchinga/The-Diary.git ChrisAchinga/The-Diary 0.01s0.01s$ source ~/virtualenv/python3.7/bin/activate $ python --version Python 3.7.1 $ pip --version pip 19.0.3 from /home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/pip (python 3.7) install 10.77s$ pip install -r requirements.txt 0.40s$ pytest ============================= test session starts ============================== platform linux -- Python 3.7.1, pytest-4.3.1, py-1.7.0, pluggy-0.8.0 rootdir: /home/travis/build/ChrisAchinga/The-Diary, inifile: collected 0 items ========================= no tests ran in 0.05 seconds ========================= The command "pytest" exited with 5. Done. Your build exited with 1. The error from travis The link to github: https://github.com/ChrisAchinga/The-Diary -
Django Query with Left and Inner Joins
I have 3 django models which are connected like this: class AppUser(models.Model): pass class UserDevice(models.Model): user = ForeignKey(AppUser, related_name='user_devices') class Token(models.Model): user_device = OneToOneField(UserDevice, related_name='auth_token') I have a situation in which I need to perform a query which Left Joins AppUser with UserDevice and Inner Joins UserDevice with Token (because I only need UserDevices which have a Token in system). But whatever I've written until now using django's prefetch_related and Prefetch objects, hasn't been useful. The problem is that the ORM uses either Left Outer join for both joins or Inner join for both of them. Is it possible to achieve what I want using ORM or should I necessarily write raw SQL for this? -
Creating a static non submittable form in Django Admin
I want to create a static form in Django admin. Basically we have an Admission model and form but at this stage this is non accessible for our client to edit. But we need to show them a static form of what it will look like once they get the edit access. Any way to achieve this? -
Django generic view, check if request is in the same group as creator
Im searching for a way to check user groups when request User is in the same group as the Creator then access and when not then access declined. The reason behind this is that not every Staff Member may edit all contributions. Only if the staff member is in the same group as the author, then the staff member may edit the article. My View: class EditArticleView(LoginRequiredMixin, UpdateView): model = Article message = _("Your Article has been updated.") form_class = ArticleForm template_name = 'articles/article_update.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('articles:list') ''' def get_queryset(self): queryset = super(EditArticleView, self).get_queryset() queryset = queryset.filter(user=self.request.user) print(self.request.user) return queryset ''' -
Disqus impementation on a modal django
I am trying to add comments to my django app, but each page needs to be unique; With the modal i cannot get a workaround to add disqus comments. I will be grateful if you get for me a workaround for the same. -
Models not displaying: unable to display models in site
anyone can help me with python django models, here is my code models.py class honeymoon(models.Model): locationh = models.CharField(max_length=100) imgh = models.ImageField(upload_to='locations') detailh = models.TextField() def __str__(self): return self.locationh views.py def top10_honeymoon(request): context = { 'posth': honeymoon.objects.all() } return render(request,'shop/honeymoon.html',context) html <div class="blog_list"> <h1 class="blog_heading"> Top 10 Destination For Honeymoon</h1><br><br> <h2 class="blog_location">{{ posth.locationh }}</h2><br> <img class="blog_img" src="{{ posth.imgh.url }}"><br> <p class="blog_details">{{ posth.detailh }}</p><br><br> </div> admin.py admin.site.register(honeymoon) i'm trying to make model and trying to add some items from admin blog but its not displaying anything in my site, and not even showing the error. data is uploading from admin panel but its not displaying -
How to edit a database var with a button press in html and django
I currently have a post model that has the atrribute: Up_vote, id like it so when a button is pressed it will +1 to the up_vote var in the db. I am using python 3.8 and the latest version of django Current views.py code: class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 home.html code: <button class="btn btn-outline-info" >Up Vote</button> <small class="text-muted">Up votes: {{ post.up_votes }}</small> I would like the up vote to increase when a user presses the button, I have checked other solutions but they havent worked for me. -
How to extend the settings file in Django?
I'm using Constance - Dynamic Django settings to configure some values in my project. according to Constance, I should add all the configurations in the settings.py file. but I need to separate this configuration in another file. I tried to extend the settings file by doing the code below, but it didn't work it is not reading the value from that new file. from .settings import * CONSTANCE_ADDITIONAL_FIELDS = { 'corres_format_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': (("xx - xx", "xx - xx"), ("xx/xx", "xx/xx"), ("xx : xx", "xx : xx"))}], 'date_format_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': (("dd/mm/yyyy", "dd/mm/yyyy"), ("mm/dd/yyyy", "mm/dd/yyyy"), ("dd-mm-yyyy", "dd-mm-yyyy"))}], } CONSTANCE_CONFIG = { 'Correspondence_format': ("xx - xx", 'Choose the correspondce format', 'corres_format_select'), 'Date_format': ("dd/mm/yyyy", 'Choose the date format', 'date_format_select'), }