Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
General params in Django templates
Django==2.2.3 In some of my cases this is a correct code: {% comment %}First example{% endcomment %} {{ set.name }} {{ set.id }} But for more general use I'd like to use param_a and param_b. Something like this: {% comment %}This will not work. It is just a wish.{% endcomment %} <p>{{ set.param_a }}</p> <p>{{ set.param_b }}</p> And then I'd like to transfer values to the context. Something like this: class SomeListView(TemplateView): template_name = "general_list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["param_a"] = "name" context["param_b"] = "id" return context Is it possible to use context in this case or I'll have to write a custom filter? Anyway, what is the most elegant solution for making an analogue for code in the first example? -
Add placeholder to Django2's AutocompleteSelect widget
I want to add additional attributes to an autocomplete field. # File: admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): search_fields = ['name'] @admin.register(Work) class WorkAdmin(admin.ModelAdmin): autocomplete_fields = ['persons'] The autocomplete widget uses Select2 and I want to add the placeholder attribute (see: select2 data-attributes) to the select element. Where or how do I configure additional attributes for a autocomplete field? Can I do this with a formfield_overrides or do I need to insert JavaScript via class Media in admin.py? I tried to add a form and use it in my admin model. I used this Django test as a template: test_autocomplete_widget.py. This had no effect on the field behavior. I except to see a placeholder text in the autocomplete widget. -
Mail sending through python file
Is there any limit to send mail through outlook using python file?. Like limit on number of mail sent?. After some tries I'm getting error of unsuccessful authentication. -
How to update formset that contains multiple form
I want to update an existing formset, but when I try to save the data, there is a validation problem, please help. my model for that formset is given as: class ProductforOrder(models.Model): order=models.ForeignKey(Order,on_delete=models.CASCADE) order_product=models.ForeignKey(Product,on_delete=models.PROTECT) order_count=models.IntegerField(default=1) and the form field is given as: class PoroductforOrderform(forms.ModelForm): class Meta: model = ProductforOrder fields = [ f.name for f in ProductforOrder._meta.fields ] fields.remove('order') creation of formset given as: orderformset = modelformset_factory(ProductforOrder,form=PoroductforOrderform,extra=0) formobj = Order.objects.get(pk=pk) form=Orderform(instance=formobj) formsetobj = ProductforOrder.objects.filter(order=formobj) formset = orderformset( queryset=formsetobj) print(formset.is_valid()) That gives me "False" that I cant update my formset. Please help. -
How to annotate on a Many-to-Many field a specific value
I'm having trouble annotating my queryset. It has a many-to-many relationship in which I only want the data from one specific item. When using an F object on the field, I'm only getting the last item from this many-to-many field. I tried to filter on the type I'm interested in, but got the same result. In: anomalies.annotate(week=F('production_item__template__bacitem__bacs__printing_date')).values('week') Out: [{'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}] In: anomalies.filter(production_item__template__bacitem__bacs__type__in=[BAC_TYPE.PRINTING, BAC_TYPE.LASER_CUTTING]).annotate(week=F('production_item__template__bacitem__bacs__printing_date')).values('week') Out: [{'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}, {'week': datetime.date(2019, 4, 23)}] I'm getting the last printing_date from bacs and not the one which has the 'type' I filtered on. -
REACT build not referencing renamed files
I'm new to react and attempting to build a react frontend to compliment my Django website. It's going well for the most part, but I'm having an issue with images. In my package.json I'm renaming files to remove the hash so my local Django static directories don't become bloated with multiple versions of the same file. This works, however, when I render the web page, it can't find the image I've renamed because it's looking for the image using the name prior to the rename. I'm guessing because the files are being renamed after the build is created. Is there a way to update the build files? If you need more information, please let me know. Any help you can provide would be much appreciated. Issue: The file name was changed to twitter.png but the page is rendering .../twitter.bdda731e.png, and the build files all use the latter rather than the former file name. package.json "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject", "collect": "react-scripts build && npm run build-rename && npm run copy-buildfiles && npm run collectstatic", "build-rename": "npm run build-rename-js && npm run build-rename-js-map && npm run build-rename-2-chunk-js && npm run build-rename-2-chunk-map … -
Objects all doesn't give ms anything inside the view method
I'm developing a new web app. I want to display data from the database to the html template. I don't get any errors but I don't get the data inside my views methode using 'Objects.all()'. When I tried the django shell it works. I am using postgres database #models.py from django.db import models from datetime import datetime class Catégorie(models.Model): désignation = models.CharField(max_length=200) Description = models.TextField(blank=True) Quantité_de_Stock = models.IntegerField() photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') est_publié = models.BooleanField(default=True) date_de_modification = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.désignation #views.py from django.shortcuts import render from .models import Catégorie def index(request): Catégorie_list=Catégorie.objects.all() context = { 'Catégorie_list':Catégorie_list, } return render(request,'articles/Category.html',context) [enter image description here][1][enter image description here][1] -
How can I monitor which routes and urls commonly requested?
We have an app made from reactjs and django and it is hosted on heroku. We use axios in reactjs to make and get and post request to the django side, now are there any method in heroku that we could monitor these url requests, e.g. which url path is most commonly requested and how much are they costing at the end of the month. -
Not able to delete the cookie in Django
Not able to delete the Cookie in Django. I have set the Cookie like this, response.set_cookie('login_cookie', enc_token_id) Now I have deleted the cookie like this, response.delete_cookie('token_redirect') Example Scenario: I have logged in and landed on https://www.my-profile.com In the profile page, I moved to the next page https://www.personal-info.com which is a completely different domain Now I click on logout button in the personal-info page it will go to logout view, there I'm deleting the cookie like above and redirect to a login page In login page when I click back button, it redirected to the https://www.personal-info.com, the cookie didn't get deleted. Here cookie is the identifier whether the person logged in or not. -
How to resolve 'invalid literal for int() with base 10' error when the identified value is intended to be a string
Upon creating a new object from a model, my site is supposed to redirect to a detailed view of that object. However, it keeps returning the error message: "invalid literal for int() with base 10: 'The name granted to my object'". I've looked online and seen that often people receive this error when they have parsed some digits as a string rather than an int or float, but in my case the value identified is clearly intended to be a string. I've examined the error message and the offending piece of code is detailed below. Python appears to be taking issue with the self variable, which I have used to filter the number of objects from another model that are aggregated. Some context: This is a method within my 'accelerator' model intended to determine the average rating of the accelerator object by aggregating the overall rating from each review of that particular accelerator. In my review model the subject field is a foreign key to the accelerator model. @property def avg_rating(self): result = Review.objects.filter(subject=self.name).aggregate(avg_rating=Avg('overall')).avg_rating return result if result > 0 else 0 -
Problem regex, How to handle multiple View URL with optional parameters with Search form
I'm trying to learn Django since few weeks, and I'm completely lost at this point. I don't know much about regex, and I don't see where my mistakes are. I build an app who makes research in different class fields. I created a first view with templates and url. then in the way to learn the management of URL with regex, I decided to make another view with just a different filter. (I have 2 templates links to the 2 different views to display each the correct informations). Here's the URL file with the regex: from django.urls import path, re_path from . import views urlpatterns = [ path('search/', views.index_client, name='dashboard'), re_path('^search/(?P<param>\w+)/$', views.index_client, name='dashboard'), path('dash/', views.test_api, name='test_dash'), re_path('^dash/(?P<param>\w+)/$', views.test_api, name='test_dash'), ] the two first urls are for my view 1 and to handle the search form. The two lasts are for my second view. Before putting the two lasts URLs everything was working fine, when clicking on my search form, I was redirected to my view 1 and the search was successful. But since I put the two last urls I'm always redirected to the second view. Even if I don't go to "127.0.0.1:8000/dash/", my view2 is handle, not my view … -
Why aI getting this errror for AWS ElasticBeanStalk Django project?
I've a Test and Production version on an application on AWS ElasticBeanStalk. I have been trying to put into Production the latest version. This works in the Test instance but when I try to deploy in Production I'm getting this error message: Collecting numpy==1.13.1 (from -r /opt/python/ondeck/app/requirements.txt (line 39)) Downloading https://files.pythonhosted.org/packages/c0/3a/40967d9f5675fbb097ffec170f59c2ba19fc96373e73ad47c2cae9a30aed/numpy-1.13.1.zip (5.0MB) Collecting packaging==16.8 (from -r /opt/python/ondeck/app/requirements.txt (line 40)) Downloading https://files.pythonhosted.org/packages/87/1b/c39b7c65b5612812b83d6cab7ef2885eac9f6beb0b7b8a7071a186aea3b1/packaging-16.8-py2.py3-none-any.whl Collecting pandas==0.20.3 (from -r /opt/python/ondeck/app/requirements.txt (line 41)) Downloading https://files.pythonhosted.org/packages/ee/aa/90c06f249cf4408fa75135ad0df7d64c09cf74c9870733862491ed5f3a50/pandas-0.20.3.tar.gz (10.4MB) Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 20, in <module> File "/tmp/pip-build-lYL8sj/pandas/setup.py", line 729, in <module> **setuptools_kwargs) File "/usr/lib64/python2.7/distutils/core.py", line 111, in setup _setup_distribution = dist = klass(attrs) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 268, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 313, in fetch_build_eggs replace_conflicting=True, File "/opt/python/run/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 836, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/opt/python/run/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1081, in best_match return self.obtain(req, installer) File "/opt/python/run/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1093, in obtain return installer(requirement) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 380, in fetch_build_egg return cmd.easy_install(req) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 638, in easy_install return self.install_item(spec, dist.location, tmpdir, deps) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 668, in install_item dists = self.install_eggs(spec, download, tmpdir) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 851, in install_eggs return self.build_and_install(setup_script, setup_base) File "/opt/python/run/venv/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 1079, in build_and_install self.run_setup(setup_script, setup_base, args) File … -
How to translate field in Django filter?
From the client I get values. They come in Russian. How can I substitute them in the filter? It is necessary either to translate incoming values into English, or field values to translate into Russian (there are translations already in django.po). Is this possible with Django? Or do I need to do something with the client? models.py BORROWER_CATEGORY_STANDARD = _('standard') BORROWER_CATEGORY_PAYROLL = _('payroll') BORROWER_CATEGORY_CHOICES = ( (BORROWER_CATEGORY_STANDARD, _('Standard')), (BORROWER_CATEGORY_PAYROLL, _('Payroll')), ) views.py request.POST - dict of russian values cps = cps.filter(borrower_category=request.POST.get('borrower_category')) settings LANGUAGE_CODE = 'ru' LANGUAGES = ( ('ru', gettext('Russian')), ('kk', gettext('Kazakh')), ) MODELTRANSLATION_DEFAULT_LANGUAGE = 'ru' USE_I18N = True 'django.template.context_processors.i18n', SOLID_I18N_USE_REDIRECTS = True -
How can i initialize data(variables) in django forms with a FBV?
I have a contact form where users fill their information to send emails/feedback Forms.py subjects = ( (1, 'Bug/error reporting'), (2, 'Enhancement suggestion'), (3, 'Support and help') (4, 'Geral feedback') ) class ContactForm(forms.Form): name = forms.CharField(initial=) email = forms.CharField(initial=) subject = forms.CharField(max_length=720,label="Subject",required=True) message = forms.ChoiceField(required=True,choices=subjects) how can i provide the initial data of this form to every current user with their data (email/name) views.py def emailView(request): user = request.user if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = user.email message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) i tried in the view to make it like this but this isn't editable and isn't filled in the form. -
How to pass naive time objec
I am a beginner to Django, and am making a website that records the time of an event. I have a model that store the time as a datetime in UTC, and when the information is sent to my template it shows as timezone specific. However, when I pass the information to an external api, it is sent in UTC. What is the best way to overcome this? Is there a way to change the timezone to the local time (like when it's sent to a template) inside of views.py, to pass it to the api call? -
Cards declined because of authentication
I'm using stripe to manage payments on my site and it works fine when I'm using dummy cards that don't require authentication but when I use them I get an error. I'm using test version of stripe to do everything so I don't know are the errors occurring because of that or there is something else that is causing the cards to be declined. @csrf_exempt def charge(request): if request.method == 'POST': charge = stripe.Charge.create( amount=int(str(request.POST["am"])), currency='usd', description=str(request.POST['desc']), source=request.POST['stripeToken'], ) return redirect("pay_app:completed") -
iterate over specific amount of element in queryset that was passed through to template
Im passing a queryset (in my case usercomments) to a template. This queryset could theoratically contain a lot of comments. Now i want to show the elements of the query as a list. I can show a specific amount eg. 3 with the help of the slice function in django template language, thasts no problem(I iterate with a for loop over the queryset(as shown in the code)). But now i want a Button that says "Show More", and everytime the button gets pressed the list expands by 3 elements. I simplified the code shown below a bit. If some information is missing or this post does not match the "stackoverflow ruels" let me know it (its my first post). I tried to change somehow the number in the for loop but i think that wont work with django template language {% for com in comments|slice:":3" %} //I want to increas that number with a button <li> <span class="name">{{com.name}}</span> </li> {% endfor %} -
Function that takes any queryset and a string and that does operation on queryset.string
it's probably more of a python object programming problem but I'm not sure. I have tried to create the tupling_object function below but adding a string parameter "country_name" in the case of the countries object but it didn't work. The first functions are working fine but I would like to generalize it. countries = country.objects.all() categories = category.objects.all() sectors = sector.objects.all() def tupling_countries(countries): list = [('','')] for country in countries: list.append((country.country_name, country.country_name)) return list def tupling_categories(categories): list = [('','')] for category in categories: list.append((category.category_name, category.category_name)) return list def tupling_sectors(sectors): list = [('','')] for sector in sectors: list.append((sector.sector_name, sector.sector_name)) return list #here's what I would like to do def tupling_object(objects): list = [('','')] for object in objects: list.append((object.something ,object.something )) return list # COUNTRY_CHOICES = tupling_countries(countries) CATEGORY_CHOICES = tupling_categories(categories) SECTOR_CHOICES = tupling_sectors(sectors) country = forms.CharField(label='Select a country', widget=forms.Select(choices=COUNTRY_CHOICES)) category = forms.CharField(label='Select a category of activities', widget=forms.Select(choices=CATEGORY_CHOICES)) sector = forms.CharField(label='Select a sector', widget=forms.Select(choices=SECTOR_CHOICES)) Also is there a better way to create dropdown form than tupling my data like that. Thanks for your time. -
How to Save All Values Returned by For Loop
I have a simple for loop which iterates over all of the objects in a local database. I want to reference an ID and pass that value to an API call to retrieve a JSON response. My issue is only the last value to be iterated over is being saved. I tried to use a zip and store all of the values returned by the loop in a list, but it is not working properly. note: also, how many different lists can I store in a zip...as I have multiple instances where this logic may be applied throughout my project views.py objects = Opportunity.objects.all() for object in objects: account_manager_obj = cwObj.get_member_by_id(object.accountManager) account_managers = [account_manager_obj[0]['firstName']] object_zip = zip(objects, opportunities, account_managers, times) template.html {% for object, opportunity, account_manager, time in object_zip %} <div class="select"> <select name="account_manager" id="account_manager"> <option value="{{ object.accountManager }}">{{ account_manager }}</option> </select> </div> -
Django ORM - Subquery slower than two separate Queries
I have two models like that: class MyDevice(models.Model): device_id = models.AutoField(primary_key=True) insert_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) class MyDeviceMeasurement(models.Model): device_id = models.AutoField(primary_key=True) insert_time = models.DateTimeField(auto_now_add=True) -> Indexed update_time = models.DateTimeField(auto_now=True) parent_device = models.ForeignKey(MyDevice, on_delete=models.CASCADE, null=False, blank=False, data = JSONField(null=False, blank=False, verbose_name="Data from device") Now, i want to do a subquery that annotate to the MyDevice model the latest measurement data property from the MyDeviceMeasurement table. So, i've tried to follow the official Django Docs, that talks about subqueries and i've implemented the following query: MyDevice.objects.annotate( latest_measurement=Subquery( MyDeviceMeasurement.objects.filter(parent_device=OuterRef('device_id')).order_by( '-insert_time').values('data')[:1])) But, unfortunately, the query is VERY, VERY slow (the MyDeviceMeasurement queryset counts milions of rows): 57 seconds to complete. Instead, using a simple python foor loop for every MyDevice and getting the latest MyDeviceMeasurement object by ordering by date, it's very fast, something like 20 milliseconds per device, in total, for 10 devices circa, it takes around 120 milliseconds. This is very strange, and i'm not able to figure out why. -
Missing Media Files Reference
I cant figure out how to reference the media files. models.py def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance,filename): new_filename = random.randint(1,353434335) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "media/media-serve/{new_filename}/{final_filename}".format(new_filename=new_filename,final_filename=final_filename) ... image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) settings.py MEDIA_ROOT = '/home/django/django_project/media-serve' MEDIA_URL = '/media/' home.html <img src="{{ object.image.url }}" alt="profile-image" class="profile"/> Thank you for any help -
Web development using Python and Django [on hold]
I want to create a website using python and django. So, I have learnt a little of them but I am not having a clarity regarding how to actually create a real-time website. Can any one please suggest how to create a real-time website using python and django or provide any website links to understand more clearly about web development using python and django? -
how can i add an expiration date function on a model?
i am trying to make a key verification app that when accepted it would create the same app on the user's profile, so i have done everything but i have struggled making the expiration date part, i want the expired boolean become true when the date is expired, but i have no idea on how to implement it #models.py class ProductKey(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, unique=False) key = models.CharField(max_length=14) valid_from = models.DateTimeField(default=timezone.now) valid_to = models.DateTimeField() expired = models.BooleanField(default=False) -
Why is the static files giving 404 in the production server?
I have a Django server setup on development as well as the production server. The development server loads the static files but the production server gives 404 on loading (although it renders the URL). I have already used the collectstatic method to accumulate my static files. settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' urls.py (main_project) from django.contrib import admin from django.urls import path, include from django.conf import settings # new from django.conf.urls.static import static # new urlpatterns = [ path('', include('stock_management.urls', namespace='stock_management')), path('auth/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), ] # if settings.DEBUG: # new # urlpatterns += static(settings.STATIC_URL, # document_root=settings.STATIC_ROOT) # urlpatterns += static(settings.MEDIA_URL, # document_root=settings.MEDIA_ROOT) urls.py (App: stock_management) : from django.urls import path, include from .views import * from django.conf import settings app_name = 'stock_management' urlpatterns = [ # Stock: path('', stock_list, name='homepage'), path('stock/', stock_list, name='stock_list'), path('stock/add', stock_create_view, name='add_stock'), path('stock/<pk>/edit', stock_edit, name='stock_edit'), # Item: path('items/', item_list, name='item_list'), path('item/<pk>/edit', item_edit, name='item_edit'), path('item/<pk>/delete', item_delete, name='item_delete'), # API path('api/items', item_list_API, name='item_list_API'), # Gallery: path('items/gallery', item_gallery, name='item_gallery'), ] # if settings.DEBUG: # # test mode # from django.conf.urls.static import static # urlpatterns += static(settings.STATIC_URL, # document_root=settings.STATIC_ROOT) # urlpatterns += static(settings.MEDIA_URL, # document_root=settings.MEDIA_ROOT) I want my static files to load in the server also. -
How to add hyperlink into Django easy_pdf
I can't find solution for inserting hyperlink into generated pdf from Django easy_pdf. Link is displayed on pdf but as text. How to make this link clickable? part of template.html: <a href="{{campaign_url}}">{{item.campaign_name}}</a> part of view.py: from easy_pdf.rendering import render_to_pdf_response return render_to_pdf_response(request, template_name, context) campaign_url is in context dictictionary Thank you for your time