Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Which database design is useful for me?
i have some entities in my website and they need: 1 - having some jsonfield (needs no-sql database like mongodb) 2 - having a relation to the other table that is for comments (it must to be stored in the separated table and not embedded document in mongodb so needs sql database,like mysql) now i don't know that which way is better? 1 - using multiple databases (mongodb,mysql) at the same time and relating documents from mongodb collection,to the mysql's table and vise a versa 2 - using just mongodb and creating two separated collections and relating them with refrenceField and dismissing all other sql based options in django as a negative point! 3 - using just mysql and creating a jsonfield in the model to store json model as a column in my table 4 - any other ways that i couldn't find Thanks -
Revisited: How to configure django (2.2.4+, no fastcgi world) with nginx for windows?
How to configure Django (2.2.4+, i.e. a version without fastcgi support) to run on nginx for windows. I understand years ago it was possible to use fastcgi. Is there another way as this is no longer an option. -
Error when using two matching foreignKeys in django
I'm trying to create an inventory management system in django for keeping track of equipment used in the live events area, and I have been hitting this error when I attempt to makemigrations. I have looked hard for typos (as all the solutions I have found have been typo related) and wasn't able to find anything. I'm assuming that this has something to do with using the same foreign key twice. from django.db import models from .tools import barutils from .tools import types as choices class venue(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False) desc = models.CharField(max_length=512, blank=True, null=True) class location(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False) venue = models.ForeignKey(venue, on_delete=models.CASCADE, null=True) class type(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=124, blank=False) class item(models.Model): id = models.BigIntegerField(primary_key=True) type = models.ForeignKey(type, on_delete=models.CASCADE, null=False) location = models.ForeignKey(location, on_delete=models.SET_NULL, null=True, related_name="current_location") home = models.ForeignKey(location, on_delete=models.SET_NULL, null=True, related_name="home_location") out = models.BooleanField(null=True) The code above produces this error. Traceback (most recent call last): File "F:\Documents\Home\Programming\Active\Vento\venv\lib\site-packages\django\db\models\fields\related.py", line 786, in __init__ to._meta.model_name AttributeError: 'ForeignKey' object has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "F:\Documents\Home\Programming\Active\Vento\manage.py", line 21, in <module> main() File "F:\Documents\Home\Programming\Active\Vento\manage.py", line 17, in main execute_from_command_line(sys.argv) … -
Django post-office setup
Perhaps it is just because I've never set up an e-mail system on Django before, or maybe I'm missing it... but does anyone have any insight on how to properly configure django post-office for sending queued e-mails? I've got a mailing list of 1500 + people, and am hosting my app on heroku - using the standard email system doesn't work because I need to send customized emails to each user, and to connect to the server one by one leads to a timeout. I've installed django-post_office via pip install, installed the app in settings.py, I've even been able to get an email to send by going: mail.send(['recipient'],'sender',subject='test',message='hi there',priority='now') However, if I try to schedule for 30 seconds from now let's say: nowtime = datetime.datetime.now() sendtime = nowtime + datetime.timedelta(seconds=30) and then mail.send(['recipient'],'sender',subject='test',message='hi there',scheduled_time=sendtime) Nothing happens... time passes, and the e-mail is still listed as queued, and I don't receive any emails. I have a feeling it's because I need to ALSO have Celery / RQ / Cron set up??? But the documentation seems to suggest that it should work out of the box. What am I missing? Thanks folks -
Trying to Extend Base User Model Mid-Project and Getting Unique Constraint Error
I'm trying to mimic this project: https://ruddra.com/posts/django-custom-user-migration-mid-phase-project/ Help! The problem is that I have the default base User model and want to extend that with the Profile model. I use a Django form to create the profile, when I try to save it to the Profile - it saves to base user and then I must input it myself to the Profile model, see view. After I create one profile, I am unable run create any more, I tried to update the model and am not longer able to run python3 manage.py migrate because I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: catalog_profile.username Here is my Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) key = models.CharField(max_length=25, null=True, blank=True) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) address1 = models.CharField(null=True, max_length=100, blank=True) address2 = models.CharField(null=True, max_length=100, blank=True, default="") zipcode = models.CharField(max_length=10, null=True, blank=True, help_text="zipcode") state = models.CharField(null=True, max_length=2, blank=True) email = models.EmailField(max_length = 250, unique=True, verbose_name = 'email_address') username = models.CharField(max_length = 25) password = models.CharField(max_length =25, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, omstamce, created, **kwargs): if created: Profile.objects.create(user=instance) def __str__(self): return f'{self.first_name} ({self.last_name}) ({self.email})' Here is my views.py. It does not work, I cannot seem to save this model to profile. … -
Is there a method to post form data from one url to another url, and then render the template based on the form data
I am trying to create a simple one item product store, in which customers would go to a product page and choose the quantity they would like to purchase in a form. After completing the form, I would then like for it to redirect to the checkout page and render the quantity they chose. Is there a simple way to do this? At the moment, I am posting the form data to the product page url and then redirecting the user to the checkout page, however I am unsure how to access that data. -
implementation of the project on the ubuntu server
I would like to implement my project created in django on a ubuntu server. I do not know how to do it, in the case of nodejs just delete the node_modules file and install the modules by typing npm install Does python (django) also provide this option? how can i do this without manually installing each module -
Django validation admin panel
problem is how to add custom validations in django admin site. my case is: if check box (day) is march 2 field must contain time first < second etc.. mon = models.BooleanField(default=False) mon_from = models.TimeField(auto_now=False, null=True,blank=True) mon_to = models.TimeField(auto_now=False, null=True,blank=True) mon_location = models.ForeignKey(location, related_name='gpn', on_delete=models.SET_NULL, blank=True, null=True, verbose_name="location") tust = models.BooleanField(default=False) tust_fromfrom = models.TimeField(auto_now=False, null=True,blank=True) tust_to = models.TimeField(auto_now=False, null=True,blank=True) tust_location = models.ForeignKey(location,related_name='gwt', on_delete=models.SET_NULL, blank=True, null=True, verbose_name="location")