Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Custom Admin Form Starts to Show Editable Password Field and No Password Reset Form Link
When I use a custom Admin form the password field hash becomes editable and it is missing the password reset form like in this example image: https://cloud.githubusercontent.com/assets/4695692/3880996/d27b1d22-2189-11e4-8d50-09ce60a18946.png. How can I make the password field look like in the image? Admin.py: class ProfileAdmin(UserAdmin): form = ProfileAdminForm fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'timezone', ...)}), (_('Permissions'), {'fields': ('is_verified', 'is_active', 'is_staff', 'is_superuser', ...)}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), (_('Subscription type'), {'fields': ('is_premium', ... )}), ) list_display = ['id','username', 'email', 'date_joined', 'is_verified', ...,] actions = [....] def changelist_view(self, request, extra_context=None): # Aggregate new subscribers per day chart_data = ( Profile.objects.annotate(date=TruncDay("date_joined")) .values("date") .annotate(y=Count("id")) .order_by("-date")[:30] ) # Serialize and attach the chart data to the template context as_json = json.dumps(list(chart_data), cls=DjangoJSONEncoder) extra_context = extra_context or {"chart_data": as_json} # Call the superclass changelist_view to render the page return super().changelist_view(request, extra_context=extra_context) admin.site.register(Profile, ProfileAdmin) Forms.py: class ProfileAdminForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['native_language'] = forms.ModelMultipleChoiceField( required=False, queryset=Language.objects.all()) self.fields['studying_language'] = forms.ModelMultipleChoiceField( required=False, queryset=Language.objects.all()) def clean_native_language(self): languages = self.cleaned_data['native_language'] language_list = [lang.id for lang in languages] return language_list def clean_studying_language(self): languages = self.cleaned_data['studying_language'] language_list = [lang.id for lang in languages] return language_list -
Need help for django live Graph plotting
I am new in django & python. Trying to make a Live generic graph plotting app. The data are coming from Mysql server(Phpmyadmin table). For that I'm badly in need of a documentation which will help me to make the project properly. Thanks for your attention . -
How can i validate DateTimeField using custom validators in models.py in django?
In models.py -> def validate_date_time(value): if value > timezone.now().date(): raise validationError(" date/time cannot be in past") Scheduled_date_time=models.DateTimeField(validators=[validate_date_time]) I am getting error message : Enter a Valid date/time. Plz help .... -
Python global variable not working in Django
I'm passing kwargs from a function to another function and declare the variable as global to use it in query but not working. def do_stuff_then_call_taxman(**kwargs): employee_id = kwargs['employee_id'] ''' doing stuff''' taxman(employee_id=employee_id) def taxman(**kwargs): global employee_id #<--- ATTENTION HERE employee_id = kwargs['employee_id'] qs = Employee.objects.filter(id=employee_id).values() #Error occurs here for global_variable in qs: '''variables''' I can't figure out what I'm doing wrong. Help will be appreciated. -
Unable to symlink '/usr/bin/python3' to '/home/ubuntu/my-env/bin/python3'
I have Django application which is getting deployed on Code Deploy. In logs i get an error saying 'Unable to symlink '/usr/bin/python3' to '/home/ubuntu/my-env/bin/python3' Any clues anyone, how to fix this issue,,..? -
Django click streams and Django packages in general
I am really new to coding and Django. I had two questions. I want to know more about Django clickstreams and if it is possible to achieve it? I researched using google. However the max I found was this Django package called django-clickstreams..however I don't see any updates around this. I wanted to know if there is a way to achieve user actions on a site using django and If so, is there any direction you can point me to? This brings me to the question around Django packages. Can they be trusted once they are added to your project ? Or there are any risks? Thank you -
Redirect to email_confirm.html after signup using django-allauth
I have a custom signup page and I would like to send email verification after user creation. However, I would like to redirect users to a different template after signup which shows them a message that they need to verify their email address. Currently my view is: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) #user.is_active = True user.save() send_email_confirmation(request, user, True) else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) How can I redirect users to a the template verification_sent.html? I have also implemented a method for users to change the email address if incorrect but I cannot find how I can integrate that in my verification_sent.html template. -
is there a way to sett return value to an variable in django
I have an custom template tag with something like this: @register.simple_tag def getLikesByUser(likedFilter, loggedInUserID): likedPeople = likedFilter personLoggedIn = loggedInUserID for personLiked in likedPeople: if personLoggedIn == personLiked.id: return True return False this will return true or false in my template, is there an option to set this return to an variable in my template? this is how a call this: {% getLikesByUser Post.likes.filter request.user.id %} I would like to have this in a variable so I can further check if is true show button if false don't. thanks -
Django - Templates and Views: Adding a button that takes you to Checkout
I'm very new to Django and was wondering how to add a button to each row for the following table. When pressing the button, it should take add it to a cart. Here's some of my code: In templates: {% extends "bobs_cafe/base.html" % {% block content %} <br> <div class="row"> <div class="col-md"> <div class="card card-body"> <h5>Products</h5> </div> <div class="card card-body"> <table class="table"> <tr> <th>Product</th> <th>Price</th> <th><button class="btn btn-primary" type="submit">Button</button></th> </tr> {% for product in products %} <tr> <td>{{product.name}}</td> <td>{{product.cost}}</td> </tr> {% endfor %} </table> </div> </div> </div> <br> {% endblock content %} In views: class CatalogView(ListView): model = Item template_name = 'bobs_cafe/menu.html' context_object_name = 'products' class ProductDetailView(DetailView): model = Product This is my attempt so far: 1st attempt Any suggestions for what to do? Thanks -
Is any way to share variables among view in django
How to share an object among different views in django? I create a instance and wanna use it in another view when a different request coming. for example: def view1(request): a=A() def view2(request): #here I wanna use a a.run('test') -
Django / Python "frozen importlib._bootstrap" error - is this a generic error messaging?
I encountered the following error messages when trying to run Django manage.py runserver. Turns out I had forgotten to add a variable 'LOG_FILE' to an imported custom config file. remote: Traceback (most recent call last): remote: File "/home/myproject/myproject/manage.py", line 21, in <module> remote: main() remote: File "/home/myproject/myproject/manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute remote: settings.INSTALLED_APPS remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 983, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 728, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/home/myproject/myproject/config/settings.py", line 32, in <module> remote: LOG_FILE = django_config["LOG_FILE"] remote: KeyError: 'LOG_FILE' The clue that it was about the config 'LOG_FILE' variable is the last 3 lines: remote: File "/home/myproject/myproject/config/settings.py", line 32, in <module> remote: LOG_FILE … -
Django allauth redirect users that signup to email confirmation page by tracking their session
I have implemented an application which uses django-allauth. When users initially signup, it asks them for email verification on the page. Without authentication them (It doesn't authentication after they have signup. My intention is that based on the user session, the website will redirect users to an html page that they can change their email address (Something that Facebook does on signup and keeps track of you when you recently signup). My sign up view is: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=user.username, password=raw_password) user.is_active = False user.save() send_email_confirmation(request, user, True) return render(request, 'account/custom_snippets/verification_sent.html', {'email': user.email}) else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) Now I would always like to redirect users to verification_sent.html if they recently signed up and the application is waiting on for user to verify their app. My email update view for newly signed users is: def update_user_email_on_verification(request): data = dict() user = request.user if request.method == "POST": new_email = request.POST.get('email') user.add_email_address(request, new_email) return render(request, 'account/custom_snippets/verification_sent.html', {'email': new_email}) else: context = { 'email':'' } data['form'] = render_to_string('account/email/update_email.html',context,request=request) return JsonResponse(data) my login view: @user_passes_test(lambda user: not user.username, login_url='/home/', redirect_field_name=None) def user_login(request): message = … -
How can i add datapicker to forms Django
how can i add datapicker to my form, this is my form. <form action="." method="POST"> {% csrf_token %} <div class="row"> {% for field in form %} <div class="form-group col-md-6" > {{ field.errors }} <label for="{{ field.id_for_label }}"> {{ field.label }} </label> {{ field |add_class:'form-control '}} </div> {% endfor %} And this is my code for datapicker, first the script and then the HTML <script> $(document).ready(function(){ $('#data_1 .input-group.date').datepicker({ todayBtn: "linked", keyboardNavigation: false, forceParse: false, calendarWeeks: true, autoclose: true }); }); </script> HTML <div class="form-group" id="data_1"> <label class="font-noraml">Simple data input format</label> <div class="input-group date"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control" value="03/04/2014"> </div> </div> -
In Django, how would you have an html page that lists all objects in the database with a common attribute?
First off, I'm a rookie on the field so if I miss out any necessary details, please do let me know and I'll update ASAP. Working with Django framework and SQLite database, I would like to have two html pages that list all items with the same "type" attribute. Right now models.py looks like this (there are more attributes after this, but that doesn't matter here, I think): class Articulo(models.Model): MEDICINAL = 'med' AUTOCULTIVO = 'cul' TIPO_PROD = [ (MEDICINAL, 'Medicinal'), (AUTOCULTIVO, 'Autocultivo'), ] tipo = models.CharField( max_length=3, choices=TIPO_PROD, default=MEDICINAL, ) So I'd like for one of the html pages to list all the items with 'med' and another for all the items with 'cul'. What I have tried is to write something similar to the search function to bring up those items by filtering that attribute, like this: def medicinal(request): items = Articulo.objects.filter(tipo__icontains=med) return render(request, 'medicinales.html', {'articulos': articulos}) However, I'm really not sure how to continue from there. I also want to add CSS to the list once it's displayed, but for that I will replicate the one I use for the search function, since I want them to retain the same style. Thank you very much in advance … -
get() returned more than one Comment -- it returned 2
I was trying to add a new post and I got the error code in the title. It seems that when I click on a post with one comment it shows the detail page but if it has more than one I get the error. I think it has something to do with my detail view. I have been changing the kwargs in my comment variable and I have been getting different errors thats why I think it has to do with the detail view. views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Post, Comment from django.utils import timezone from .forms import PostForm def post_index(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by("published_date") return render(request, "blog/post_index.html", {"posts" : posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) comment = get_object_or_404(Comment, post=post.pk) return render(request, "blog/post_detail.html", {"post" : post, "comment" : comment}) def post_create(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("post_detail", pk=post.pk) else: form = PostForm() return render(request, "blog/post_create.html", {"form" : form}) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def … -
Why is my Order Items not showing in the Template?
I need help to know what is wrong with my code as I am trying to figure out the reason why the Order objects are not showing in the template although I have tried the same thing in other templates with emails and it is working just fine. Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing----------------> <<-------------------------From here nothing is showing--------------------------> {% for order_item in order.items.all %} <tr> <th scope="row">{{ forloop.counter }}</th> <td> {{ order_item.item.title }}</td> <td> {% if order_item.item.discount_price %} <del>${{ order_item.item.price }}</del> {{ order_item.item.discount_price }} {% else %} ${{ order_item.item.price }} {% endif %} </td> <td>{{ order_item.quantity }}</td> <td>{% if order_item.variation.all %} {% for variation in order_item.variation.all %} {{ variation.title|capfirst }} {% endfor %} {% endif %} </td> <td> {% if order_item.item.discount_price %} $ {{ order_item.get_total_discount_item_price }} <span class="badge badge-primary" style="margin-left:10px">Saving ${{ order_item.get_amount_saved }}</span> {% … -
How to solve an "OfflineGenerationError: You have offline compression enabled but key ..." served up by Windows 2019 IIS?
My code with django-compressor works on my local machine with DEBUG=True or False, but when I push to production, which is a Windows Server 2019 served by IIS, then it only works with DEBUG=True. If I set to False, then I get this error: OfflineGenerationError: You have offline compression enabled but key is missing from offline manifest. I have looked at many different other posts regarding this same issue but none solve it for me so far. Here are my details: I am using pipenv [requires] python_version = "3.8" [packages] django = "3.1.2" django-compressor = "2.4" whitenoise = "5.2.0" {extras = ["brotli"], version = "1.0.9"} wfastcgi = "3.0.0" Production Details Windows Server 2019 IIS for 2019 settings.py INSTALLED_APPS = [ ... 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'compressor', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/assets/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets') ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" COMPRESS_FILTERS = { "css": [ "compressor.filters.css_default.CssAbsoluteFilter", "compressor.filters.cssmin.rCSSMinFilter", ], "js": ["compressor.filters.jsmin.JSMinFilter"], } STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' WHITENOISE_MAX_AGE = 31536000 if not DEBUG else 0 # 1 year COMPRESS_ENABLED = True COMPRESS_OFFLINE = True Any thoughts on how I can debug why it won't work with DEBUG = … -
Sending information from webhook to views.py Django
I am developing my first Django website and I have the following scenario. I get user input, then I make a call to an external API in the backend and I receive something using a webhook. Here, I need to send a 200 response to the API. But I also need to return something to the user, after processing what I get in the webhook. My question is how do I implement this inside my views.py? Making my views wait for the webhook to be triggered and then return a response to the user? -
problem restricting deletion of a Django model value
I have a foreign key, that when the object it references gets deleted will be filled with a default value via a callable on_delete=models.SET(callable).. however I have problem with that because in the Django admin site I'm able to delete the callable value that it has passed to the foreign key and since my foreign key can't be null this is going to raise a server error which I don't like.. so I want to handle that error through the Django admin site itself if that could be possible and I know it is.. also if you have better thoughts on this, I really appreciate your help. as a temporary solution I had overrode the QuerySet > delete() method of the referenced model to skip deleting the object through the Django admin site bulk deletion, I'm sure that there is a better way than this. The foreign key: class Product(models.Model): marektplace_tag = models.ForeignKey('tags.MarketplaceTag', on_delete=models.SET(default_marketplace_tag)) the callable: # Model: Product def default_marketplace_tag(): from tags.models import MarketplaceTag tag = MarketplaceTag.objects.get_or_create(name='None') return tag[0].id The referenced model: class MarketplaceTag(models.Model): objects = MarketplaceTagQuerySet.as_manager() name = models.CharField(max_length=32, validators=[only_letters]) -
Understanding Full Join in Django
I have two models in my app: # Create your models here. class Melody(models.Model): notes = models.JSONField() bpm = models.IntegerField() aimodel = models.CharField(max_length=200) score = models.IntegerField(default=0) person = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="melodies") date_created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) class Vote(models.Model): user_score = models.IntegerField(validators=[MaxValueValidator(1), MinValueValidator(-1)]) melody = models.ForeignKey(Melody, on_delete=models.CASCADE, related_name="scores") person = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="voters") def __str__(self): return f"{self.person} - {self.melody} - {self.score}" And I get the melodies of the current user by # Get melodies of current user melodies = Melody.objects.all().filter(person=person).order_by('-score')[start:end+1].values() I would like to add to this results the vote of the user to each melody, if there is one, otherwise just null so I can loop over the melodies and retrieve the values: melody.notes = ... melody.bpm = ... melody.user_score = This is the values I do not know still how to get, Null if user has not voted I was reading about select_related but when I use it it always says "Invalid field name(s) given in select_related: 'xxxx'. Choices are: (none)" What am I missing? -
Adding another context to a Function in Django
Hellooo, I am trying to add OrderItem context for the following function, it is currently passing only Order but I am trying to include another to appear in the template. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() class OrderItem(models.Model): <----------I want to add the context related to this model item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing Title: {{ order.orderitem.item.title }} -
Django modelformset not validating due to hidden field
I'm having a really hard time trying to discover the root of this whole error. So in my project i have two models. 1. AllergiesInformation 2. AntecedentsInformation These have a foreign key to another model called "Patient", so for each patient there can be many allergies and antecedents, i decided to use modelformsets to create as many instances as needed once, i also have two views. 1. Create View 2. Update View For my Create View, my modelformsets work like a charm, they save all the insatnces as it supposed to be, the problem comes when, i try to update these instances in the Update View, the already created and new instances are not validated due this error. id * Select a valid choice. That choice is not one of the available choices. This error appears the same times as the forms appear in my template, what i can see is that it comes form the "Allergies" modelformsets, i already read the documentation and other similar posts but no success. I would leave all my code below. I rendered manually the Forms ID's in the template already. Models #Allergies Information class AllergiesInformation(models.Model): allergy_type = models.ForeignKey(Allergies, on_delete=models.CASCADE, null=True, blank=True, verbose_name='allergy type', … -
Writing a Class Based View to replace a Function
I am in the learning process and I am trying to write a class based view instead of my function. Here is the function: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is what I have tried to reach so far but I don't know how to continue with the response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) and the remaining. @staff_member_required class admin_order_pdf(DetailView): model = Order template_name = 'pdf.html' def get_context_data(self, **kwargs): context = super(admin_order_pdf, self).get_context_data(**kwargs) # add extra context if needed return context def render_to_response(self, context, **kwargs): pdf = render_to_string(self.template_name, context) return HttpResponse(pdf, content_type='application/pdf') -
Python[DJANGO] : Send Whatsapp messages
i'm working on a django project for a restaurant booking and delivery and i want to send a whatsapp message to the user once he'll order something , is there any tutorial or api i can use to do that ? btw i've tried lot of tutorial but most of them they receive messages from a random number , i want to create a conversation between me and the client who will insert his number in the form . Thanks ! -
Converting from Function to Class Based View
There is a function-based view, that looks like this: @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response The question is: how to convert this to class based view? What generic Django view to use as the base?