Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible post the point dataset through form on django?
I want to post the point dataset into my postgres database using form. Is this possible? If yes, How can be possible? my views.py file from django.shortcuts import render from issue.models import Issue # Create your views here. def index(request): return render(request, 'pages/index.html') def about(request): return render(request, 'pages/about.html') def webmap(request): if request.method == 'POST': first_name = request.POST['firstname'] last_name = request.POST['lastname'] issue_header = request.POST['issue_header'] issue_body = request.POST['issue_body'] issue = Issue(first_name=first_name, last_name=last_name, issue_header=issue_header, issue_body=issue_body) issue.save() return render(request, 'pages/webmap.html') return render(request, 'pages/webmap.html') In this form I want to submit point data. I am using leaflet. And my marker location is var useMarker = true $('.fa-cubes').click(function () { if (useMarker) { map.on('click', function (e) { var popup = `<!-- Default form register --> <form class="text-center border border-light p-5" action="{% url 'webmap' %}" method="POST"> {% csrf_token %} <p class="h4 mb-4">Issue Form</p> <div class="form-row mb-4"> <div class="col"> <!-- First name --> <input type="text" name="firstname" id="defaultRegisterFormFirstName" class="form-control" placeholder="Your First Name"> </div> <div class="col"> <!-- Last name --> <input type="text" name="lastname" id="defaultRegisterFormLastName" class="form-control" placeholder="Your Last Name"> </div> </div> <!-- Issue header --> <input type="text" name="issue_header" id="defaultRegisterPhonePassword" class="form-control mb-2" placeholder="Input your issue header" aria-describedby="defaultRegisterFormPhoneHelpBlock"> <br> <!-- Password --> <input type="text" name="issue_body" id="defaultRegisterFormPassword" class="form-control" placeholder="Your issue in detail" aria-describedby="defaultRegisterFormPasswordHelpBlock"> <!-- … -
How to display name instead of email address while sending email in django rest framework?
This is django rest framework and here i am trying to send email and it is working fine also but the one problem is i want to display some name instead of email address in the users inbox for that i tried adding from_email argument in the urls but it didn't worked.It says TypeError: TemplateView() received an invalid keyword 'from_email'. How can i solve this settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "myemail" EMAIL_HOST_PASSWORD = 'mypass' EMAIL_PORT = '587' urls.py path( 'password-reset/confirm/<uidb64>/<token>/', TemplateView.as_view(template_name="registration/password_reset_confirm.html", from_email='MyName<myemail>'), name='password_reset_confirm'), -
Can i deploy both Flask and Django application in common aws Elastic Beanstalk server?
I have two applications built with Flask and Django framework. I would like to host both the applcation in aws Elastic Beanstalk. Is it possible to host both application using the common server? Thanks for the Answers. -
How can I escape colons in Django's field lookups?
I've brought some JSON metadata into a JSONfield() and some of the key names include a colon. Am I able to escape the field lookups so I can do something like the example below? filtered_qs = queryset.filter(data__properties__object:key="some_value") where object:key is the name of my JSON key Currently i'm getting the keyword cannot be an expression syntax error. I'm using Postgres 11.2 and Django 2.2.2. -
Graphene-Django Relay Cursor Based Pagination Does Not Work for Dynamic Data
I am fetching dynamic data using Graphene-Django Relay specification. import graphene from graphene_django.types import DjangoObjectType from graphene_django.fields import DjangoConnectionField from . import models class PostType(DjangoObjectType): class Meta: model = models.Post interfaces = (graphene.Node, ) class Query(graphene.ObjectType): post = graphene.Field(PostType) posts = DjangoConnectionField(PostType) def resolve_posts(self, info, **kwargs): return models.Post.objects.order_by('-created_date', '-id') When I add a new post after fetching cursors and data, cursors change. In other words, the cursor that was pointing to the exact offset of data does not point that data any longer. It points a new, different data. Thereby, I cannot implement a cursor-based pagination by using: query fetchPosts ($cursor) { posts(first: 20, after: $cursor)... } Because cursor changes as data changes, it is no different than traditional offset-based-pagination. Is there something I am missing? What I want for the cursor is not to change. Like this article: https://www.sitepoint.com/paginating-real-time-data-cursor-based-pagination/ How should I make the cursor point the same data that changes dynamically? -
List all the permissions and Select/ Deselect/ Update for a specific user
I am working on a custom Admin app in Django project. I repeat, I DO NOT want to use the Django's inbuilt Admin interface/app provided. I am stuck at a point where I want to change the Permissions given to a specific User. I used the generic UpdateView for updation of some specific User's details like Name, Email, User Name etc. but when it came to updating the User Permissions, there was neither a button,link nor a checkbox. How can I ADD/Remove/Update the permissions of a User? Any help would be highly appreciated. class UserUpdate(UserPassesTestMixin, UpdateView): models = User fields = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'is_superuser', 'user_permissions') def get_object(self, queryset=None): obj = User.objects.get(pk=self.kwargs['pk']) self.success_url = reverse_lazy('admin:user_detail', kwargs={'pk': obj.pk}) return obj def test_func(self): return self.request.user.is_superuser This is my view for updating the User Data by selecting a User. -
How many times does the Django ORM hit the database when calling a foreign key's primary key and using the in list filter?
Lets say I have the following models: class Foo(models.Model): ... class Bar(models.Model): name = models.CharField(max_length=255) foo = models.ForeignKey(Foo) Now, I am doing the following queries: foo_pks = set([]) for bar in Bar.objects.filter(name='some_name'): foo_pks.add(bar.foo.pk) for foo in Foo.objects.filter(pk__in=foo_pks): # Do something So basically, I am adding the primary keys to the set, and then using that set to make another query. How many times am I hitting the database? Moreover, is this horribly inefficient, and if so, is there a better way to do this? -
What to test in a simple DRF API?
So, I'm not a test expert and sometimes, when using packages like DRF, I think what should I test on the code... If I write custom functions for some endpoints, I understand I should test this because I've written this code and there are no tests for this... But the DRF codebase is pretty tested. But if I'm writing a simple API that only extends ModelSerializer and ModelViewSet what should I be testing? The keys in the JSON serialized? The relations? What should I be testing? -
Django - access individual fields in a class-based view generated form
I'm using a custom template I created for a class-based view. Previously I used a "pre-defined" template, one created by form.as_p, but for the custom template I need to access certain fields individually, specifically I have a CharField constrained by choices and I want to populate the options in a <select> field, yet using something like form.myInput doesn't work: Model: class MyObject(models.Model): ... states = ( ('A', 'Activated'), ('D', 'Deactivated') ) state = models.CharField(max_length=1, choices=states, blank=False, default='A') View: class CreateMyObject(CreateView): model = MyObject fields = '__all__' Custom template: ... <select id="state" class="form-control"> {% for s in form.state %} <option value="{{s.0}}">{{s.1}}</option> {% endfor %} </select> ... (this doesn't work!!!) I've seen some solutions where people define a Form but I don't have one. My form is 100% the Model itself. Do I still need to define one? It seems to me I should be able to access easily the fields in form, given that, for instance, form.as_p access all of them and easily creates a basic template... Thanks. -
Django snapshot upload and face recognize with opencv
I'm trying take snapshot with getUserMedia() and recognize face using opencv-python. I only get encoded image from user media and can't open it with opencv. I'm using django 2.2 as backend server -
Pre_delete signal does not work in Django
I am working with signals in Django, specifically with the pre_delete signal, code: signals.py file: def delete_unnecessary_image(sender, instance, using): print('holaaaa') instance.image.delete(save = False) apps.py file (here I register the receivers in the ready() method): def ready(self): from .signals import delete_unnecessary_image from .models import Course pre_delete.connect(delete_unnecessary_image, sender = Course) The problem is that it doesn't work, it doesn't eliminate the image of the Course model, and I don't know why. Any solution? -
Crispy forms throws VariableDoesNotExist error failed lookup for key [html5_required] on forms
I use allauth to sign in with emails and did a very basic custom login form and a template override for allauth and display the login form. Hitting the URL throws me straight into the exception: Failed lookup for key [html5_required] in [{'True': True, 'False': False, 'None': None}, {'True': True, 'False': False, 'None': None, 'form': , 'form_show_errors': True, 'form_show_labels': True, 'label_class': '', 'field_class': ''}, {'forloop': {'parentloop': {}, 'counter0': 1, 'counter': 2, 'revcounter': 2, 'revcounter0': 1, 'first': False, 'last': False}, 'field': }, {}] where I then have to continue the debugger twice to end up on the form. I tried looking for this specific [html5_required] tag/key but haven't found anybody with the same missing key. I removed the custom login form in settings.py to see if there is an issue but that didn't help. I even tested it with a simple ```ModelForm`` just displaying two fields and got the same issue. settings.py: INSTALLED_APPS = [ ... 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ... ] CRISPY_TEMPLATE_PACK = 'bootstrap4' ACCOUNT_FORMS = { "login": "users.forms.CustomLoginForm" } forms.py from django.utils.translation import ugettext as _ from django.urls import reverse_lazy from allauth.account.forms import LoginForm, SignupForm from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML from django.forms import ModelForm class … -
How to customize RetrieveAPIView to take a subview like `blogs/:blog_id/minimal` in Django REST Framework?
I am on Django 1.11, and I am trying to generate a minimal view for a view that is extending RetrieveApiView. The router looks like this: url(r'^(/blogs/(?P<pk>.*)', BlogView.as_view() The BlogView is implemented as such: class BlogView(RetrieveAPIView): search_fields = () queryset = Blog.objects.all() serializer_class = BlogSerializer @detail_route(methods=["get"]) def minimal(self, request, pk=None, **kwargs): return Response( data={ "message": 1 } ) So basically I want to get /blogs/:blog_id to display the current default full view from BlogSerializer, and /blogs/:blog_id/minimal to trigger the minimal function here somehow and display another view. Currently, this solution doesn't really work as I got 404 when visiting /blogs/:blog_id/minimal. Is it possible without having to manually declare another url in route? The reason I choose to not use a query parameter here because I would prefer to have different permission for those 2 view. a minimal view can be viewed by less restricted role -
Validate end_date is bigger than start_date in Django Admin
I have a start_date and end_date fields in save_related action of my Django Admin, I want to assign an error to end_date when it is bigger than start_date, I have been looking docs, but don't find an example about that. -
Django: Survey models and how to display them on template
I'm building a Survey creator that can multiple questions and they can be of four different types: text question, date question, date range question and multiple choice. Below are the models that I've used but I'm having a super hard time understading how to display the correct widget for the correspoding type of question. models.py class Survey(models.Model): title = models.CharField(max_length=255, unique=True) class Question(models.Model): TYPE_QUESTION = ( ("Text", "Text"), ("Date", "Date"), ("Date Range", "Date Range"), ("Multiple Choice", "Multiple Choice"), ) survey = models.ForeignKey(Survey, null=True) title = models.CharField(max_length=255) type_question = models.CharField(max_length=255, choices=TYPE_QUESTION, default=TEXT) class Answer(models.Model): question = models.ForeignKey(Question, null=True) user = models.ForeignKey(User, null=True) answer = models.CharField(max_length=255) I want to achieve something like this but without having to define the form manually: preview.html {% for question in questions|dictsort:"date_added" %} <div class="question-container"> <h4>{{question.title}}</h4> <div class="question-body"> {% if question.type_question == 'Text' %} <input type="text"> {% elif question.type_question == 'Date' %} <input type="date"> {% elif question.type_question == 'Date Range' %} <input type="date"> <input type="date"> {% elif question.type_question == 'Multiple Choice' %} <input type="radio" name="gender" value="male" checked> Yes<br> <input type="radio" name="gender" value="female"> No {% endif %} </div> </div> {% endfor %} Should I redefine my Answer model and define one model for each type of questions? or … -
How to update profile picture for existing model instance?
I'm trying to update a user's profile photo after they've already created their account. I'm using an abstract user model connected to a model called Person. For additional context, I have my application connected to AWS to deploy to Heroku. I have a form, model, url and view set up but I'm sure I'm missing some piece to the puzzle. <form action="{% url 'update-photo' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <table class="table-form"> {{ form|crispy }} </table> <input type="submit" class="btn btn-lg custom-bg"> <br><br> </form> class User(AbstractUser): is_active = models.BooleanField(default=False) class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) upload = models.FileField(default='core/static/images/default_avatar.png') class UpdatePhotoForm(forms.ModelForm): class Meta: model = Person fields = ('upload',) @login_required def update_photo(request): person = Person.objects.get(user=request.user) from core.forms import UpdatePhotoForm if request.method == "POST": form = UpdatePhotoForm(data=request.POST, instance=request.user.person) if form.is_valid(): person = form.save(commit=False) person.save() return redirect('profile') else: form = UpdatePhotoForm() return render(request, 'core/edit_profile.html', {'form': form}) ``` urls.py path('update_photo/', core_views.update_photo, name='update-photo'), The form submits without any error but does not actually update the photo. I can change the photo in the admin site but not via the form. Any help would be greatly appreciated! -
Adding different images based on if post is liked
I'm creating a social media website, where users can like each others post. I have successfully done most of this. I have allowed a user to like and dislike posts, and displayed a list of the users who have liked the post in my template. One issue I have is changing an image based on whether the user has liked the post or not. My current implementation is incorrect, and I am unsure how to solve it. Currently, I have a variable on the Post model(is_liked), and an image changes depending if this is true or not. My problem with this is if one user likes a post, it shows up as liked for every user. I want it so everyone can't see the graphic that is displayed when a post is liked, and only if they like it themselves. models.py: class Post(models.Model): file = models.FileField(upload_to='files/') summary = models.TextField(max_length=600) pub_date = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') is_liked = models.BooleanField(default=False) views.py: def likepost(request, post_id): if request.method == 'POST': tuser = request.user post = get_object_or_404(Post, pk=post_id) if post.likes.filter(id=tuser.id).exists(): post.likes.remove(tuser) post.is_liked = False post.save() else: post.likes.add(tuser) post.is_liked = True post.save() return redirect('home') home.html(template) {% if post.is_liked == True %} … -
Django multidatabases : data for model field from another db
Is there a way to make a field model get its data from another database? I want to query a magento db and select the customer_id to use in my model field. I Know we can set different databases in the setting file and select the database with using() -
Shopping cart fail to display Django 2.1
I am reading django book on how to build a shopping and for some reason the product (list and detail) pages are fine but the app crash when i try to access the page that supposed to display the cart. I am not sure what the problem is but here the error from the terminal Internal Server Error: /cart/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/myshop/myshop/cart/views.py", line 41, in cart_detail cart = Cart(request) TypeError: __init__() takes 1 positional argument but 2 were given [11/Aug/2019 20:48:25] "GET /cart/ HTTP/1.1" 500 63026 Internal Server Error: /cart/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macadmin/Documents/Django_fun4/myshop/myshop/cart/views.py", line 41, in cart_detail cart = Cart(request) TypeError: __init__() takes 1 positional argument but 2 were given [11/Aug/2019 20:48:28] "GET /cart/ HTTP/1.1" 500 63026 Internal Server Error: /cart/add/1/ Traceback (most recent call last): File "/Users/macadmin/Documents/Django_fun4/myshop/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner … -
celery periodic_task not finding tasks
I am trying to run a task every minute but with my current implementation, beat is not picking it up. If I modify my celery to add period task, it does pick it up and send it to worker but worker can't find it so it throws KeyError. Is @period_task enough for beat to find the library or it must be defined in celery.py file? Regardless, I would appreciate help. app ==>project name app conf base.py development.py production.py staging.py celery.py urls.py members models.py views.py app2 models.py views.py background tasks.py where base.py is settings.py with shared settings. My celery.py file is simply: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.task.schedules import crontab from decouple import Config, RepositoryEnv DOTENV_FILE = '.env' env_config = Config(RepositoryEnv(DOTENV_FILE)) # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', "app.conf.development") app = Celery('app') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() in background/tasks.py I have: @periodic_task( run_every=(crontab(minute='*/1')), name="add", ignore_result=True ) def add(): … -
the pagination doesn't work with me, how I solve this problem?
The pagination doesn't work, The numbers move but the content does not change, how I solve this problem? models.py class Board(models.Model): name = models.CharField(max_length=50, unique=True) description= models.CharField(max_length=50, unique=False) class Topic(models.Model): title = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name='topics',on_delete=models.CASCADE,default=True) board = models.ForeignKey(Board, related_name='topics',on_delete=models.CASCADE) created_dt = models.DateTimeField(default=timezone.now) views.py def boards_topic(request, id): board = get_object_or_404(Board, pk=id) paginator = Paginator(board, 3) page = request.GET.get('page') # board = paginator.get_page(page) try: page_list = paginator.page(page) except PageNotAnInteger: page_list = paginator.page(1) except EmptyPage: page_list = paginator.page(Paginator.num_pages) context = {'board':board, } return render(request, 'topics.html',context) url.py path('boards/<int:id>/', views.boards_topic, name='boards_topic'), TypeError at /boards/1/ object of type 'Board' has no len() Request Method: GET Request URL: http://127.0.0.1:8000/boards/1/?page=1 Django Version: 2.2.3 Exception Type: TypeError Exception Value: object of type 'Board' has no len() -
Unable to save stripe payments to table
I followed this stripe payments tutorial: https://testdriven.io/blog/django-stripe-tutorial/. I'm using the pop-up box. I'm not sure how I can save the information to the Payments table. This is my view code. The view works, but nothing saves to the model. I'm struggling to save data from user input to my databases. Is there a good tutorial on this? I'm new to Django. class PaymentsView(TemplateView): template_name = 'page.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context from catalog.extras import generate_order_id def charge(request): # new if request.method == 'POST': try: datetime_done = datetime.now() + timedelta(days=3) order_number = generate_order_id(18) PremiumPurchase = stripe.Charge.create( user = request.user, token = request.POST['stripeToken'], description = "Purchase of Premium", datetime_payment = datetime.datetime.now(), datetime_done = datetime_done, order_id=order_number, amount=2.99, success=True, ) PremiumPurchase.save() except: raise ValidationError("The card has been declined") return render(request, 'premium/charge.html') -
How to build a Django model where the data in one field varies based on the User
I have a Customer model in Django which is linked to a User by Foreign key, so each user (engineer) can have multiple customers: class Customer(models.Model): __tablename__ = 'Customer' engineer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='engineer') # other fields I now wish to add a JSONField to Customer which will hold some data I pull from a third party API: distance = JSONField(blank=True, null=True) This is great, as I can have distance information stored on a per customer basis. However this distance information would differ for each engineer/customer combination. I'm missing how I would create another model to accommodate this in an efficient manner. I suspect inheritance could be used here, but I'm struggling to figure out how to put this together. I would like to use {{customer.distance}} in the template and have the correct distance returned for the logged in user. -
Crispy Forms PrependedText and OptionsField
I am trying to put an € symbol in front of a select field but it will not render properly. That's what I would like to do: https://getbootstrap.com/docs/4.0/components/input-group/#custom-select And this is my result: This is my code that using crispy forms # This text input works perfectly Field(PrependedText("website", """<i class="fas fa-link"></i>""", css_class="col-12", wrapper_class="col-6")), # This one does not work properly Field(PrependedText('price_level', """<i class="fas fa-euro-sign"></i>""", css_class="col-12", wrapper_class="col-6")) -
Problem with ManyToManyField in other model's forms using Bootstrap
I would like to show possible choices from ManyToManyField (which I have in Homes model) in the Owners form. I have Owners <--Many2Many--> Homes with custom class HomesOwners. In Homes it works out of the box, I don't know how to make it work in Owners. I am using Django 2.2.4 with Bootstrap 4 and Postgresql. I started my project based on django-bookshelf project (also just Django and Bootstrap4). I do not use any render. Comment in django-bookshelf project mentioned How to add bootstrap class to Django CreateView form fields in the template?, so I stick to that if it comed to forms. I'm pretty new to Python (so Django too) and web technologies in general. I googled dozen of different questions/answers but I couldn't find any nice explanation of what is what and how to use it in real life. Most of them ended up with basic usage. I did some experimentation on my own, but no success so far... Here is the code I have two models - Homes/models.py and Owners/models.py Homes/models.py: class Homes(models.Model): id = models.AutoField(primary_key=True) # other fields some_owners = models.ManyToManyField(Owners, through='HomesOwners', through_fields=('id_home', 'id_owner'), related_name='some_owners') # end of fields, some other code in the class like …