Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with machine leaing gives this error Found array with 0 feature(s) (shape=(1, 0)) while a minimum of 1 is required
views.py from django.shortcuts import render from .models import questions from .serializers import approvalSerializers from django.http import JsonResponse from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import api_view import os from avasyu import settings import pickle import requests import numpy as np from django.core.cache import cache # Create your views here. data = [] def landing_views(request): return render(request, "avasyuapp/landing.html") def ques_views(request): cache.clear() return render(request, "avasyuapp/ques.html") def store_db(request): if request.method == "POST": ans1 = request.POST["answer1"] ans2 = request.POST["answer2"] ans3 = request.POST["answer3"] ans4 = request.POST["answer4"] ans5 = request.POST["answer5"] ans6 = request.POST["answer6"] ans7 = request.POST["answer7"] ans8 = request.POST["answer8"] ans9 = request.POST["answer9"] data.append(ans1) data.append(ans2) data.append(ans3) data.append(ans4) data.append(ans5) data.append(ans6) o1 = questions( ques='Have you motivated yourself to become a good communicator?', ans=ans1) o1.save() o2 = questions( ques='Can you speak in front of group without any nervousness?', ans=ans2) o2.save() o3 = questions( ques='Can you justify you as a good communicator?', ans=ans3) o3.save() o4 = questions( ques='Are you really happy to make communication as your future passion?', ans=ans4) o4.save() o5 = questions( ques='Is your english vocabulary and comprehension strong?', ans=ans5) o5.save() o6 = questions(ques='Are you good at grammar?', ans=ans6) o6.save() o7 = questions( ques='Have you achieved anything till date as a good … -
'ManyToManyDescriptor' object has no attribute 'add'
ranges = list(ranges) report.date_from = form.instance.date_from report.date_to = form.instance.date_to report.assigned_range.add(ranges) I am getting the error AttributeError at /create_stock_turnover_report 'ManyToManyDescriptor' object has no attribute 'add' But I can't understand why my database model is this assigned_range = models.ManyToManyField(to=assigned_range, blank=True, null=True) -
Is it possible to let users update their profile through a one time link in Django
I have tried all the techniques I could come up with, I couldn't find a way out. My question is, is it possible to let users update their profiles using a one time link in Django? If yes, can someone point me to a doc or maybe explainer which I can use as a guide? -
How to integrate a python script and execute it on Django
what I want to happen is: under some_list_of_contacts = [] will be the numbers from my django model. i will create a html template for this script that when I click the button it will execute this send_sms.py. under SMS_MESSAGEit will be the latest data coming from django model with timestamp. for example (As of {'timestamp'} the level is {'level'}). I'm a beginner on Django and Python, please how can I do these? Thanks! send_sms.py import boto3 AWS_ACCESS_KEY_ID = "<>" AWS_SECRET_ACCESS_KEY = "<>" AWS_REGION_NAME = "eu-west-1" SENDER_ID = "Test" SMS_MESSAGE = "Test" client = boto3.client( "sns", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME ) topic = client.create_topic(Name="notifications") topic_arn = topic['TopicArn'] some_list_of_contacts = [ '(must be numbers from django model)', ] for number in some_list_of_contacts: client.subscribe( TopicArn=topic_arn, Protocol='sms', Endpoint=number ) response = client.publish( Message=SMS_MESSAGE, TopicArn=topic_arn, MessageAttributes={ 'string': { 'DataType': 'String', 'StringValue': 'String', }, 'AWS.SNS.SMS.SenderID': { 'DataType': 'String', 'StringValue': SENDER_ID } } ) print(response) print("MessageId:" + response["MessageId"]) print("HTTPStatusCode:" + str(response["ResponseMetadata"]["HTTPStatusCode"])) -
How to set a default or add a Foreign Key in ModelForm?
Context: using Django 3.0.4. I have two models UserProfil a arbitrary UserModel automatically created by registering UserList more or less a simple list of lists Every registered User can create a new UserList entry in my model by giving a UserList.name in a form. If i put UserList.name and UserList.profile in the form my template generates the inputs and i can enter every value. it works so far. But it´s obvious Users should not allowed to choose the UserList.profile relation in the template, because if so, they could create a new list entry related to other users. so i need to set the value to the current user. My approach to save this relation was what u see in SingleListForm.save of my forms.py Unfortunately nothing is saving when i am entering a value for UserList.name in my Template Input. It only shows my form_invalidmessage: "Error something went wrong". additionally i also tried to removed the profilerfield from fields:in mySingleListForm and tried to save. but then i get the message The above exception (NOT NULL constraint failed: profil_userlist.profiler_id) was the direct cause of the following exception: Question How to set a default or add a Foreign Key in ModelForm? models.py class … -
Django edit default user group and add profile pictures
In django I want to edit the default user group so that I can the following attributes to all users, a description, a position, and a profile picture. I'm fairly new to django so if this question can be improved please let me know. -
image field with forms
i have a comment model in my django. i'm just using the content to submitting with the form but now i want to submit the iamge also.But its not working i"ve trying it many ways but its not working. views.py: def post_detail(request, pk): posts = get_object_or_404(post, pk=pk) comments = Comment.objects.filter(post=posts, reply=None,).order_by('-timestamp') #post=posts is the above post details posts its mean post for the exact corresponding posts is_liked = False if posts.likes.filter(id=request.user.id).exists(): is_liked = True if request.method == 'POST': comment_form = CommentForm(request.POST or None, request.FILES or None) if comment_form.is_valid(): content = request.POST.get('content') image = request.FILES['image'] reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create(post=posts, user=request.user, content=content, image=image, reply=comment_qs,) comment.save() notify.send(request.user, recipient=posts.author, actor=request.user, verb='comment in your post', target=posts, nf_type='comment_by_one_user') else: comment_form = CommentForm() context = {'posts':posts, 'comments':comments, 'comment_form':comment_form, 'is_liked': is_liked, 'total_likes': posts.total_likes(),} if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({'form': html}) return render(request, 'blog/post_detail.html', context) and my froms.py: class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here', 'rows': '4', 'cols': '10'})) class Meta: model = Comment fields = ('content', 'image',) the image is not submitting. -
UpdateView does not show existing data when using filter
I am quite new with Django and I need help. My problem is quite similar what Mike had in his case: UpdateView not populating form with existing data, but I have not found solution yet. My goal is to view owner dropdown selection list only those users who are members of the organization. models.py # organizations.models.py ... from accounts.models import User from core.models import TimeStampModel ... class Organization(TimeStampModel, models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField( verbose_name=_('Name'), max_length=255, unique=True ) code = models.CharField( verbose_name=_('Code'), max_length=255, null=True, blank=True ) owner = models.ForeignKey( User, on_delete=models.PROTECT, verbose_name=_('Owner'), related_name='owner', help_text=_('Organization Owner and Contact Person'), ) slug = models.SlugField(verbose_name=_('Organization key'), unique=True) ... class Meta: verbose_name = _('Organization') verbose_name_plural = _('Organization') ordering = ['name', 'code'] def __str__(self): return f'{self.name}, {self.code}' # Create automatically slug value from organization name field. # In case similar is exist then add extra count digit end of slug. def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Organization.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() self.next_update = timezone.now() + relativedelta( months=self.update_interval) super(Organization, self).save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'slug': self.slug } return reverse('organization_main_page', kwargs=kwargs) … -
Wagtail route still returns 404
I encountered a bit weird problem and not really sure why it happens. This is my model: class PostIndexPage(RoutablePage): max_count = 1 parent_page_types = [] intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] @route(r'^posts/$') def main(self, request): from django.shortcuts import render return render(request, self.get_template(request), self.get_context(request)) I defined route in that model but it seems to have no effect. http://127.0.0.1:8000/post-index-page/ - the old url is still working the old way http://127.0.0.1:8000/posts/ - but this one doesn't (404, not found). Do you have any idea what I'm doing wrong? -
Want to fetch value from HTML(Django) into javascript/ajax
{% for prod in product %} <div class="col-lg-3 col-md-6"> <div class="single-product"> <img class="img-fluid" src="{{prod.p_image}}" alt="" > <div class="product-details"> <h6>{{prod.p_name}}</h6> <div class="price"> <h6>${{prod.p_price}}</h6> <h6 class="l-through">${{prod.id}}</h6> </div> <input type="hidden" id="product_name" value="{{prod.p_name}}"> <div class="prd-bottom"> <a href="" class="social-info"> <span class="ti-bag" onclick="cart()"></span> <p class="hover-text">add to bag</p> </a> <a href="" class="social-info"> <span class="lnr lnr-heart"></span> <p class="hover-text">Wishlist</p> </a> <a href="" class="social-info"> <span class="lnr lnr-sync"></span> <p class="hover-text">compare</p> </a> <a href="" class="social-info"> <span class="lnr lnr-move"></span> <p class="hover-text">view more</p> </a> </div> </div> </div> </div> {% endfor %} i want to send these values to the javascript/ajax. How can i do it? product is Model name. i m displaying values of Model(Product) in this Div -
How to place a django form in a nav bar so that it appears on every page?
I have a form whose queryset depends on request.user, and whose initial value depends on a session key. The primary models are User (slight modification of default User model) and Account, with a many-to-many relationship between them. The form allows a User to change the Account that he/she is viewing, and that choice must persist as the User navigates the site. The form works fine when created in a single view and passed to a single template, but I want the form to appear in the top navigation bar so that the User can change Accounts from anywhere. Here is the form: class ChangeAccountContextForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.current_account_id = kwargs.pop('account_id') super(ChangeAccountContextForm, self).__init__(*args, **kwargs) self.fields['account_choices'].queryset = self.user.accounts.all() try: self.fields['account_choices'].initial = Account.objects.get(id=self.current_account_id) except(Account.DoesNotExist): self.fields['account_choices'].initial = None #queryset and initial are set to None, because they are assigned dynamically in the constructor (see above) account_choices = forms.ModelChoiceField(queryset=None, initial=None, label='Account:', widget=forms.Select(attrs={'onChange':'this.form.submit()', 'class': 'custom-select mr-sm-2 ml-2'}), required=True ) class Meta: model = User fields = ['account_choices'] And here is the existing view where the form is used: @login_required def welcome_view(request): user = request.user context = {} accounts = user.accounts.all().order_by('account_name') context['accounts'] = accounts context['num_accounts'] = len(accounts) try: account_id = request.session['current_account_id'] except (KeyError): … -
Show a DRF user token in a django template view
I have a very simple template view to allow user to view their drf token from django.views.generic.base import TemplateView from rest_framework.authtoken.models import Token class AuthTokenView(TemplateView): template_name = 'view_auth_token.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['username'] = self.request.user.username context['token'] = Token.objects.get(user=self.request.user) return self.render_to_response(context) I keep getting this even though I know Token is a model. Any ideas? context['token'] = Token.objects.get(user=self.request.user) AttributeError: type object 'Token' has no attribute 'objects' [12/Mar/2020 14:56:16] "GET /get_auth_token/ HTTP/1.1" 500 107751 -
Django 3 and SQL Anywhere
How do I connect a Django 3 (Python 3.6) new app to a SAP SQL Anywhere 16? I have tried to use sqlanydb, pyodbc and django_sqlany without success. -
Django: can't trigger AJAX call and send values back to my form
I need to run an AJAX call to perform a quick calculation in my django view and return the result in my html page, inside a tag. I'm very new to Javascript so I don't understand why my AJAX call hasn't been triggered. This is my html and JS code: <input type="text" name="SHm2" maxlength="10" type="number" value="50"> <input type="text" name="STm2" maxlength="10" type="number" value="50"> <button id="estimation" name= "estimation" onclick="calculate()">Estimation</button> <span>{{estimation}}</span> <script type="text/javascript"> function calculate () { $.ajax({ url: '/myApp/templates/homepage/', type: 'POST', data: { SHm2: $('#SHm2').val(), STm2: $('#STm2').val() }, success: function(estimation) { alert(estimation); document.getElementById("estimation").innerHTML = estimation; } }); } </script> And this is my views.py: def homepage(request): if request.method == 'POST' and request.is_ajax and 'estimation' in request.POST: SHm2 = request.POST.get('SHm2') STm2 = request.POST.get('STm2') estimation = float(SHm2) + float(STm2) estimation = json.dumps(estimation) return HttpResponse(estimation, content_type='application/json') The problem is that the AJAX code isn't triggered since I don't receive the alert. Nevertheless, the code in my django view is running anyway (which is strange, since I specified to run if 'request.is_ajax', which doesn't seem to be recognized on the other hand). It loads a new page where it correctly displays the result. But it's not what I want since I need the result to be … -
Is there any way to show a field on a listing page in Wagtail admin?
I know that I can register my model as a Django model and add an image there but I need to save a pages' tree and identify my pages by an image on a listing page. To make a long story short, I need to show images on a listing page in admin. -
Trouble with RFC 5545 Recurrence by day
I'm seeing erroneous behavior with a by-day (e.g. every Tuesday and Thursday) recurrence pattern. Suppose I have an event starting on Thursday 3/12 at 9p (2100h) Pacific time and recurring every Tuesday and Thursday. Pacific time is UTC-0700, so the event has a UTC start date of 0400h on 3/13--4am the following day. When my recurrences are generated they take the start time of the original event, but not the date. So my recurrences are generated on Tuesdays and Thursdays at 0400h, which translates to 9p PT on Mondays and Wednesdays. I've tried creating the events in local (Pacific) time and specifying a TZ-ID, but it doesn't seem to help. Is there a way to account for this? I don't want to try to infer whether there will be an issue and rewrite the recurrence pattern on the fly, as that A) seems very error prone, and B) will make the interface for editing the recurrence pattern very challenging as well. -
Django ORM raw query how manage quotes
In my Django project i have to implement a complex RAW query for extract data, for doing this i use the raw django function. The original query is: SELECT FT."Riferimento1", FT."Riferimento2", "CodProdotto", "QuantitaFatturata", "PrezzoUnit", "DataFattura", "NumeroFattura", "CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192'; if i run directly in pgadmin SQL all was done In django i implement in this fashion: >>> from idocuments.models import as_fatturetestata as asf >>> a = asf.objects.raw("SELECT FT."Riferimento1",FT."Riferimento2","CodProdotto","QuantitaFatturata","PrezzoUnit","DataFattura","NumeroFattura","CodCli" FROM public.idocuments_as_fatturetestata FT LEFT JOIN public.idocuments_as_fatturerighe FR ON FT."Riferimento1" = FR."Riferimento1" AND FT."Riferimento2" = FR."Riferimento2" WHERE FT."CodCli" = '12192'") but i get: SyntaxError: invalid syntax maybe the problem is how to manage quotes but i don't understand how transport the sql query into raw directive. Someone can help me please? so many thanks in advance -
Partially rending page, if click the button (image O)
enter image description here I want to make faster website. so I try rendering less in one time. If the button is clicked, the page is partially rendering like picture. I linked example of what i want to made. https://na.op.gg/summoner/userName=shernf click the arrow button, rendering new page -
Cannot login to deployed app. Nginix configuration issue on EC2
I've tried to get my api working on ec2 to working with my django/drf backend and my nuxt frontend app. When I deploy the app my frontend is rendered and my backend admin works but I cannot login or access render any data from backend. For Example, when I try to request url ec2-64-644-225-61.eu-west-1.compute.amazonaws.com/api Nothing happens. I'm trying to find documentation on this online but I'm not getting far. On the DRF official docs or nginx official docs I don't see any documentation that show's how to configure api on ec2. My app runs locally fine but on ec2 doesn't serve my frontend for backend data communications. Should these settings work or am I missing something? config for nginx upstream django { ip_hash; server 127.0.0.1:8000; } upstream nuxt { ip_hash; server 127.0.0.1:3000; } server { location ~ /(api|admin|static)/ { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } location / { proxy_pass http://nuxt; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $host; } listen 80; server_name localhost; } docker_compose version: '3.4' services: db: restart: always image: postgres volumes: - pgdata:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 redis: restart: always image: redis volumes: - redisdata:/data django: build: context: ./backend … -
DRF custom permission is not working for function view (get request)
I have Angular frontend sending request using firebase id_token. In the backend (backend.py) authenticates every request based on the id_token in the header. Using Firebase Admin SDK I added users to 'standard' or 'premium' group and also have local copy of users in the database. In permissions.py I check if the user belongs to either standard or premium. For QuestionCorrAPiView(APIView) it works as expected (if not logged in or if user is not in standard group, cant access). However, for the function view, I couldn't figure out why the permission class is not called. Even though _has_persmission returns False, it still allows access to exams view. I know I have made stupid mistake somewhere but don't know where. Any help is appreciated. ''' #All other imports from coc_api.permission import IsStandard @ /api_vie(['GET']) @/permission_classes([IsStandard]) def exams(request): exams = models.Exam.objects.all() serializer = coc_serializers.ExamSerializer(exams) return Response(serializer.data) class QuestionCorrAPIView(APIView): permission_classes = [IsAuthenticated,IsStandard] # IMPLEMENTATION HERE #permissions.py def _is_in_group(user, group_name): """ Takes a user and a group name, and returns `True` if the user is in that group. """ try: return Group.objects.get(name=group_name).user_set.filter(id=user.id).exists() except Group.DoesNotExist: return None def _has_group_permission(user, required_groups): return any([_is_in_group(user, group_name) for group_name in required_groups]) class IsStandard(permissions.BasePermission): # group_name for stadnard users required_groups = … -
Creating copy for blog post has no argument and return all pots and comments and updating date and return new id
class Blog_Post(models.Model): '''create copy in this class``` title = models.CharField(max_length=250) body = models.TextField() date_created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Author',on_delete=models.CASCADE) class Author(models.Model): name = models.CharField(max_length=50) class Comment(models.Model): blog_post = models.ForeignKey(Blog_Post,on_delete=models.CASCADE) text = models.CharField(max_length=500) -
Django: Error rendering views with CSRF token
There are lots of posts on the web regarding the error TypeError: 'module' object is not callable, when trying to use contexts, but I am stuck on this for almost 24h... I've read the documentation more than once and I still had no success. TL,DR: I don't know what I am doing and I need someone to explain me, how to use a {% csrf_token %} on a html page. Because my views.py are not rendering properly, if at all. If I don't use csrf_tokens/post methods, everything works fine! I'm new to Django. Using 3.0.4 Brief explanation of what I am trying to do and symptoms: My base.html as a sign-in button, which opens a modal, where the user can insert : and this triggers a post direct within the domain. Because of this reason, I need to use {% csrf_token %}. Which I do. Once I had the token, I get an error saying I need to setup the context on my views, which I did. I tried multiple ways and right now my views looks like this: from django.http import HttpResponse from django.template import Template, RequestContext def gallery_categories_view(request): template = Template('gallery-categories.html') context = RequestContext(request) html = template.render(context) return … -
django DB2 inspectdb failure :'NoneType' object is not subscriptable
my dev environment is in python 3.6 and virtualenv(virtualenv 15.1.0) and with dependencies below: django 2.2 ibm-db 3.0.1 ibm-db-django 1.2.0.0 as i used "(env_django2) λ python manage.py check", it return "System check identified no issues (0 silenced)." that is no problom. however, when i used "python manage.py inspectdb --database db2 DEMO.DEMOUSER", it return like these below: (env_django2) λ python manage.py inspectdb --database db2 DEMO.DEMOUSER # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models # Unable to inspect table 'DEMO.DEMOUSER' # The error was: 'NoneType' object is not subscriptable this is my db2 setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db2':{ 'ENGINE': 'ibm_db_django', 'NAME': 'test', 'USER': 'db2inst1', 'PASSWORD': 'XXXXXX', 'HOST': 'XX.XXX.XXX.XXX', 'PORT': 'XXXXX', 'PCONNECT':True, } } and … -
how do i create bridge table in djnago model
i have created two table's in djnago models. i have created foreign-key for both models like a 'cross-product' but while i applies python3 manage.py makemigrations cmd and then python3 manage.py migrate i get error django.db.utils.IntegrityError: The row in table 'subscription_registration' with primary key '1' has an invalid foreign key: subscription_registration.ProfileImages_id contains a value '1' that does not have a corresponding value in subscription_profileimages.id. models.py table-1 class Registration(models.Model): YourName = models.CharField(max_length=30) ProfileImages = models.ForeignKey('ProfileImages', on_delete=models.CASCADE, verbose_name="profile image key(as FK)", null=True, blank=True) Email = models.EmailField(max_length=254,null=True) password = models.CharField(max_length=254,null=True) table-2 class ProfileImages(models.Model): MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE, null=True, blank=True) profile_image = models.ImageField(upload_to='profile_image',default="some",null=True) note: the registration form have allready data as id 1 now i want to add profile image for that user. and i think i can create a bridge table between them so if please help me what i can do before creating bridget table i need to assign fk for both table am right? -
Extend wagtail page visibility and add subscription plans
I'm creating a website with wagtail where users can decide to buy a subscription plan. Each subscription should allow access to a page on the site. For example, "only users in the premium plan can read the news." The subscription must have an "expiry date". At the moment the visibility can be blocked to users in a specific group (which can be managed as a subscription) but I don't know how to manage the expiration date and it doesn't seem to be a particularly elegant solution for my problem. I haven't found anything to create a custom model user_group with an expiry_date field. I would like to know how a situation like this should usually be handled and if it is possible to add another entry in the visibility section, for example: "private, accessible to users in specific subscriptions".