Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply local time to Django form field
I have USE_TZ = True in my settings.py file, so (from my understanding) this causes dates to be stored in my database as UTC time. So to store a date automatically in a view I can do: from django.utils import timezone now = timezone.now() newGlucose = glucose(glucoseVal=currentGlucose,Dtime = now) #Dtime is a dateTime modelfield newGlucose.save() #saves to the DB as UTC (0.00 offset) And when I want to display this as local time on a template I can do: from django.utils.timezone import localtime glucoses = glucose.objects.filter() date = (glucoses[x].Dtime) #<----grab stored time from DB (#Dtime is a dateTime modelfield) date = localtime(date) #<-----convert to locatime for display on template This seems to work well, I don't know how Django is getting the correct timezone (from browser?) but it works. Now, How can I use this same methodology for a Django form with dropdown boxes for the dateTime? By default the HTML dateTime dropdown is in whatever timezone the current timezone is set as in the settings.py file, which obviously isn't helpful when my users are in different time zones. The only thing I can get to work is by creating a timezone model field for each user, then having the … -
how to get data from django rest framework
basically most requests are using [id] get : /[:id] post : /[:id] delete : /[:id] but if i want specific data by searching db example model "Warrior" race : string (maori, barbarian, valkiri... ) weapon : int (associated with Weapon(model)) health : int model "Clan" name : string warriors : int now want to search all clans that have maori how you implement with django rest framework? -
Saving Matplotlib figure to Django models.ImageField Instance
In Django I have a models.ImageField that takes in the user image & should output the modified image to the Model-Post instance. It instead uploads the original image to the model instance (saves in the 'media/Files folder) & outputs the converted image into the root directory, which is not accessible on the live server. Wondering how I could either replace the user-uploaded image with the converted image or add the matplotlib image to the Post instance. Any help would be awesome, as I've spent days trying to figure this out. -
How can I pring search results?
Since I'm new to fpdf I need some assistance with my dilemma: I have a view, that doing a search on website, and for now I need to print my search results using fpdf( I know about ctrl+p printing, I have pagination, so It didn`t work ). Could someone help me with the steps I have to take? This is my search view class SearchResidentView(AbstractSearchView): template_name = 'resident/search_resident.html' search_form = SearchResidentForm def get_filter_func(self): return resident_search_filter def get_queryset(self) -> 'QuerySet[CitizenshipRequest]': data = self.request.GET if any(data.values()): make_user_action_log(f'Resident search. Search data: {pretty_dict(data)}', self.request.user) filtered_qs: QuerySet[CitizenshipRequest] = super().get_queryset().annotate( dep_code=F('dep_add__code') ).only( 'last_name', 'first_name', 'middle_name', 'date_birth_str' ) return filtered_qs -
Django can't deploy the static files on Heroku if my folder name is assets instead of static
I followed a lot of questions I have searched and applied, but nothing worked. I made a lot of attempts. Here are the questions: Django can't find the static files Can't deploy Django + Heroku Heroku - Handling static files in Django app Django static files on heroku STATIC_ROOT setting in Django Heroku django app createsuperuser Observations: I know I should change STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') to STATIC_ROOT = os.path.join(BASE_DIR, 'assets'), but it did not work either. I know that I should run python manage.py collectstatic that Heroku deployed correctly the staticfiles folder and it rendered well, but it increased the storage size, with the assets folder. I want only to keep the assets folder. The tree looks like, and observe that I have a folder called assets and do not have the folder static because of assets: gusbemacbe.co.nz ├── assets │ ├── css │ ├── fonts │ ├── images │ ├── js │ ├── json │ └── yaml ├── commands ├── db.sqlite3 ├── gusbemacbe │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── home │ ├── admin.py │ ├── apps.py │ ├── tests.py │ └── views.py ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt ├── … -
How to run a code just before django restarts?
Here is the case. I start a telegram bot(using pyrogram framework) inside django and everytime that I modify a file and save it or django just restarts by any reason, I have to shut pyrogram down right before django starts again. If I do not shut down pyrogram right before server restart process, it gets stuck after printing a sentence like: <modified_file_address> changed, reloading. And after this line, nothing happens and django will not start itself again and I just found source of the problem. Pyrogram(v0.18.0 - synchronous version) is causing it because of multithreading lock keys.(a little bit complicated to describe and not related to the question) If I can shutdown pyrogram bot right before running the django server again(literally right before or after printing <modified_file_address> changed, reloading. message), I can fix it. After searching inside the django source code, this is the function that actually prints that message. # inside django.utils def trigger_reload(filename): logger.info('%s changed, reloading.', filename) sys.exit(3) And now this is my question: Is There Any Way To Overwrite trigger_reload Function Or Customize It Somehow? And if no: Is There Any Way To Run A Function Right Before trigger_reload Function? And if no again: Is It Possible … -
I am trying to install psycopg2-binary in windows and getting warning
I am trying to install psycopg2-binary in windows I get this warning. how can I solve this problem ?? PS C:\Users\zakoo> pip install psycopg2-binary WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) Requirement already satisfied: psycopg2-binary in c:\python39\lib\site-packages (2.8.6) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python39\lib\site-packages) when I run docker-compose up I get this error. web_1 | backend = load_backend(db['ENGINE']) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 111, in load_backend web_1 | return import_module('%s.base' % backend_name) web_1 | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module web_1 | return _bootstrap._gcd_import(name[level:], package, level) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 29, in <module> web_1 | raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) web_1 | django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' -
Redis performance in Django is very slow
A Django webapp reads a redis database and displays the data in a Plotly plot. When the redis database has a small number of rows (less than 20k), queries are very fast (less than a second). As the number of rows grows over 50k, queries slow dramatically (8 to 15 seconds). Threads also stumble over each and don't complete in sync. This redis database uses a timestamp as a key. Each value is a string in json format. Like this: key: 1621367811.769709000 value: {"timestampx": "1621367811.769709000", "length": "96", "dscp": "0", "srcip": "172.16.1.2", "destip": "172.17.4.2"} My code queries the database. It creates a dictionary where each key is one second. Each value is the total number of megabits transmitted in that second. Code snippet below: r = redis.StrictRedis(**redis_config) keys = r.keys(pattern="*") keys.sort() start = datetime.now() #keys = keys[0:1000] #For troubleshooting vals = r.mget(keys) end = datetime.now() print("There are " + str(threading.active_count()) + " active threads") print("The mget command took " + str(end - start) ) print("*******************************") """ Code to make a Pyplot scatter plot where the x axis is bps.keys() and the y axis is bps.values() """ Initial output looks something like this: There are 26966 keys in the database. There are … -
Django posrtgerql wrong DateTime
I have DateTimeField at my postgres db. And for ecample I have time 5/12/2021 4:00 PM django will save it as 5/13/2021 01:00+03:00 How can i resolve it? -
how can I fix Django cannot unpack non-iterable int object?
I am kind of a beginner and I'm doing an ecommerce web-site now and in views I have get_object_404 and parameters to go with it but I keep getting cannot unpack non-iterable int object with an id parameter. I searched the topic and mostly found same problem with pk and it didn't work with id(or maybe I couldn't make it work who knows). here's the code: views.py: from django.shortcuts import render, get_object_or_404 from .models import * from cart.forms import CartAddProductForm def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) context = { 'categories': categories, 'category': category, 'products': products, } return render(request, 'onlineshop/product/list.html', context) def product_detail(request, id, slug): product = get_object_or_404(Product, id, slug=slug) cart_product_form = CartAddProductForm() context = { 'product': product, 'cart_product_form':cart_product_form, } return render(request, 'onlineshop/product/detail.html') urls.py: from django.urls import path from . import views app_name = 'onlineshop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail') ] models.py: from django.db import models from django.urls import reverse class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('onlineshop:product_list_by_category', … -
Only allow unique email hosts while ignoring subdomains
I want to allow only unique user email addresses from a single host with the subdomain part ignored, no matter if it's submitted or not. I'm pretty sure my code is correct because all parameters are set as explained in the documentation and the regex pattern validates but it doesn't seem to work. email_pattern = r'^[^@]+@([^\.@]+\.)?google\.com$' class User(Model): class Meta: constraints = [ CheckConstraint(check=Q(email__iregex=email_pattern), name='check_google'), UniqueConstraint(fields=['email'], condition=Q(email__iregex=email_pattern), name='unique_user'), ] email = EmailField() My email_pattern should allow google.com and any *.google.com as email host. The first constraint checks if the email address has only the allowed hosts. The second constraint should check if any user with an email address host (google.com or *.google.com) already exists and therefor raise an database error if found. Example email addresses: john.doe@google.com john.doe@sub.google.com john.doe@sub2.google.com Any of the emails above be valid but only allowed for a single user. Currently I can create 3 users with 3 different emails... Is there something I'm missing out? -
Django: "Object has not attribute get" error in forms.Form
I am trying to create a forms.Form that loads an existing Trade record and allows users to update it. I believe the usual way to do this would be to use a forms.ModelForm, but ModelForms do not work with the widget I am using (django-autocomplete). When I load the url /update-buy/263/, it calls the views.update_buy function (shown below). I am getting the error 'ManyToOneRel' object has no attribute 'attname'. Form: class BuyUpdateForm(LoginRequiredMixin, forms.Form): desired_game = forms.ModelChoiceField( queryset=Game.objects.all(), to_field_name='desired_game', #todo widget=autocomplete.ModelSelect2( url='game-autocomplete', attrs={ 'data-minimum-input-length': 2, }, ) ) buy_price = forms.IntegerField() def __init__(self, data, *args, **kwargs): super(BuyUpdateForm, self).__init__(data, *args, **kwargs) if data is not None: self.fields['buy_price'].label = "Max. Buy Price" self.fields['buy_price'].initial = data['buy_price'] self.fields['desired_game'].initial = data['desired_game'] views.update_buy(method called when user loads the above url) @login_required def update_buy(request, pk): offer = Trade.objects.filter(id=pk).first() print('offer: ' + str(offer)) if request.method == 'POST': trade_form = BuyUpdateForm(request.POST, instance=offer) if trade_form.is_valid(): trade_form.save() messages.success(request, f'Your trade has been updated') return redirect('update-offer/' + str(pk)) else: #GET request data = {'desired_game': offer.desired_game, 'buy_price': offer.buy_price} trade_form = BuyUpdateForm(data) return render(request, 'blog/buy_form.html', {'form': trade_form, 'title': 'Update Trade Form'} ) relevant fields from the Trade model: class Trade(models.Model): name = models.TextField() # Unrestricted text desired_game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='desired_game', db_column='desired_game', null=True, blank=True) buy_price … -
Django get related object in one-to-one relationship without knowing the related model
How do I get the related object of a model in this case: class ModelA(models.Model): pass class ModelB(models.Model): a = models.OneToOneField(ModelA, related_name='b_object', on_delete=models.CASCADE) class ModelC(models.Model): a = models.OneToOneField(ModelA, related_name='c_object', on_delete=models.CASCADE) I know that if I do: ModelA.b_object # returns related b object ModelA.c_object # returns related c object But since this is a one to one relationship, a particular instance of ModelA will only be related to a single instance of one of those models, so: Is there a general way to get the related object without knowing if the related object is from one model or the other? Something like: ModelA.get_related_object Does Django provide this functionality? Should I build a custom method for this and how? Use case example (for clarity): in a DetailView template for ModelA, get the related object for that instance. -
How to fix relation does not exist -error when using class meta in model?
I have this class in my models.py: class Person(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) birthday = models.DateField(null=True) gender = models.CharField(max_length=20) height = models.CharField(max_length=3) id = models.CharField(blank=False, max_length=100) weight = models.CharField(max_length=3) class Meta: managed = False db_table = 'person' def __str__(self): return self.id Everytime I run migrate -command I get this error: psycopg2.errors.UndefinedTable: relation "person" does not exist. I've already dropped the db and destroyed the migration file but the error remains. How can I fix this and why this happens? -
OSError: [WinError 193] %1 is not a valid Win32 application. By reading captcha with using tr repository
I am using tr --> https://github.com/myhub/tr (this repository to read captcha). I am getting an errorr WinError 193 %1 is not a valid Win32 application. I have installed tr repository in my env as per the instruction mentioned in this repository. -
Convert Django DateField to usable value for React Calendar
I have read the documentation for the react-calendar: https://www.npmjs.com/package/react-calendar, I have read the documentation for django DateField, and I have read similar questions on stack overflow. My problem is trying to get the format YYYY MM dd that is saved in Django DateField to a usable value for the React calendar. I am currently trying to change the format using const value = (locale, date) => formatDate(date, 'YYYY MMM dd') and then calling the variable value when rendering the calendar component <Calendar value = {value}/> but I don't know where to put the date variable that I've saved. I currently have the date stored as a variable {club.next} which is dynamic for each page. -
Mailchimp integration with Django Tutorial not Working
I am trying to connect Mailchimp with my HTML form. I tried following this tutorial, but after writing everything up nothing is working. I don't receive any errors, but it won't add new emails to my list after submitting. here is the html: <section class="cta2"> <form action="{% url 'subscription' %}" method="POST"> {% csrf_token %} <div class="form-group"> <h2>Stay Up-to-Date</h2> <p>Join our newsletter to receive updates and first access to new features!</p> <input type="email" required id="email" placeholder="enter your email to subscribe"><input type="submit" id="submit" value="Join!"> </div> </form> <!-- message if email is sent --> {% if messages %} {% for message in messages %} <div class="my-5 alert alert-success"> <h5 class="m-0"> {{ message}} </h5> </div> {% endfor %} {% endif %} </section> here is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.conf import settings from mailchimp_marketing import Client from mailchimp_marketing.api_client import ApiClientError # Mailchimp Settings api_key = settings.MAILCHIMP_API_KEY server = settings.MAILCHIMP_DATA_CENTER list_id = settings.MAILCHIMP_EMAIL_LIST_ID # Subscription Logic def subscribe(email): """ Contains code handling the communication to the mailchimp api to create a contact/member in an audience/list. """ mailchimp = Client() mailchimp.set_config({ "api_key": api_key, "server": server, }) member_info = { "email_address": email, "status": "subscribed", } try: response … -
How to filter datetime from an interval of two dates in Django ORM
I'd like to filter an interval of two dates in one datetime on django ORM date_start = 2021-05-17 date_end = 2021-05-18 inspect_dt in database is datetime type, sample: 2021-05-17 06:56:59 2021-05-17 06:58:32 2021-05-18 06:58:37 2021-05-18 06:59:53 2021-05-18 07:00:25 I want to pass date_start and date_end, then filter it on inspect_dt What i tried: filteredDate= inspectionDate.objects.all().filter( inspect_dt__gt = date_start, inspect_dt__lt = date_end) filteredDate= inspectionDate.objects.all().filter( inspect_dt__contains = (date_start, date_end)) filteredDate= inspectionDate.objects.all().filter( inspect_dt__range = (date_start, date_end)) both returns were empty: [] -
Django-autocomplete-light not showing in bootstrap modal form
I am setting up a homepage which should include bootstrap modal forms. This part works fine. But as soon as I try to implement a Django-autocomplet-light (DAL) widget, things start to get complicated. I have this autocomplete view class TagAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Tag.objects.all() if self.q: qs = qs.filter(name_de__icontains=self.q) return qs which has the following url configuration urlpatterns = [ path('tag-autocomplete', views.TagAutocomplete.as_view(create_field='name_de'), name='tag-autocomplete'), path('sound-create/<int:category_id>', views.SoundCreateView.as_view(), name='sound-create'), path('image-create/<int:category_id>', views.ImageCreateView.as_view(), name='image-create'), ] I have two similar ModelForms: class ImageForm(forms.ModelForm): class Meta: model = Image form_tag = False fields = ('solution', 'image_file', 'difficulty', 'explicit', 'tags', 'category') widgets = {'tags': autocomplete.ModelSelect2Multiple(url='gamefiles:tag-autocomplete'),} class SoundForm(forms.ModelForm): class Meta: model = Sound form_tag = False fields = ('solution', 'sound_file', 'difficulty', 'explicit', 'tags', 'category') widgets = {'tags': autocomplete.ModelSelect2Multiple(url='gamefiles:tag-autocomplete'), } with the according views: class ParentCreateView(CreateView): def get_initial(self): return { 'category': self.kwargs['category_id'], } def form_valid(self, form): tags = form.cleaned_data["tags"] self.object = form.save() self.object.tags.add(*tags) return render(self.request, 'success.html', {'element': self.object}) class ImageCreateView(ParentCreateView): model = Image form_class = ImageForm template_name = 'image_create_form.html' def get_context_data(self, **kwargs): ctx = super(ImageCreateView, self).get_context_data(**kwargs) ctx['category_id'] = self.kwargs['category_id'] return ctx class SoundCreateView(ParentCreateView): model = Sound form_class = SoundForm template_name = 'sound_create_form.html' def get_context_data(self, **kwargs): ctx = super(SoundCreateView, self).get_context_data(**kwargs) ctx['category_id'] = self.kwargs['category_id'] return ctx My index.html loads some static … -
Indexing models and model fields in Django with managed=False
I have a simple question. Is there a way to create indexes for models and/or their fields if the models themselves are being imported from somewhere else, i.e., managed=False? I don't think Django will do it without migrating and I can't do that as the db is littered with tables that are not needed so I haven't created models for them. By the way, I'm using Postgresql. -
Does psycopg2.connect inherit the proxy set in this context manager?
I have a Django app below that uses a proxy to connect to an external Postgres database. I had to replace another package with psycopg2 and it works fine locally, but doesn't work when I move onto our production server which is a Heroku app using QuotaguardStatic for proxy purposes. I'm not sure what's wrong here For some reason, the psycopg2.connect part returns an error with a different IP address. Is it not inheriting the proxy set in the context manager? What would be from apps.proxy.socks import Socks5Proxy import requests PROXY_URL = os.environ['QUOTAGUARDSTATIC_URL'] with Socks5Proxy(url=PROXY_URL) as p: public_ip = requests.get("http://wtfismyip.com/text").text print(public_ip) # prints the expected IP address print('end') try: connection = psycopg2.connect(user=EXTERNAL_DB_USERNAME, password=EXTERNAL_DB_PASSWORD, host=EXTERNAL_DB_HOSTNAME, port=EXTERNAL_DB_PORT, database=EXTERNAL_DB_DATABASE, cursor_factory=RealDictCursor # To access query results like a dictionary ) # , ssl_context=True except psycopg2.DatabaseError as e: logger.error('Unable to connect to Illuminate database') raise e finally: logger.info('Successfully connected to Illuminate database') Error is: psycopg2.OperationalError: FATAL: no pg_hba.conf entry for host "12.345.678.910", user "username", database "databasename", SSL on Basically, the IP address 12.345.678.910 does not match what was printed at the beginning of the context manager where the proxy is set. Do I need to set a proxy another method so that the psycopg2 connection … -
Django CMS problemas url multilenguaje
Tengo un problema en una web multilengua con las urls al cambiar el idioma de la web. La web está montada con Django CMS 3.8 Únicamente me pasa con un las rutas de proyectos, al acceder en un determinado idioma, por ejemplo español y selecciono inglés, no me traduce el título del proyecto de la url y me aparece el siguiente error: Not Found The requested resource was not found on this server. Gracias -
Conditional column display, django-tables2
I have developed a table, using django-tables2 which shows records of a model. The last column of this table, is an "edit button" which leads user to the "edit page" of its row record. What I want is that the user can see the edit column only if she has permission to edit the model! Also I need to mention that currently I'm using SingleTableView to develop table view. -
Entries deleted from Django admin uploaded to Heroku reappears after a while
I created a project whose backend is handled by Django. While I was creating the project, I made few entries in the database for testing purposes. I uploaded the Django app to Heroku. Then I went to the admin page on my Heroku website to delete those test entries. The entries get deleted without any error but after few minutes all of the entries reappear and my new entries get deleted. I am using the SqlLite3 database. -
Creating and displaying pyvis graph from django app running sql backend
This is moreso a question about pyvis graphs, but also involves a django server running with a sqlite3 backend. One of my views needs to produce an interactive pyvis graph and display it in the clients browser. I can do this without the django app with the following code: import networkx from pyvis.network import Network nx_graph = networkx.Graph() network.from_nx(nx_graph) network.show('nx.html') As you can see with this method, pyvis creates an html file and save it to disk first. nework.show() simply opens the file in the browser. Because I will be running this on a django webapp, I would rather create the graph's html without saving it to disk, then just return it as a string in the HttpResponse for the view.