Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Excluding elements from the queryset on a inlineformset
So lets say I have these models: class Club(models.Model): name = models.CharField(max_length=100) members = models.ManyToMany(User) class Event(models.Model): name = models.CharField(max_length=100) date = models.DateField() club = models.ForeignKey(Club, models.CASCADE) So what I need is to get all the club's events, but on an inlineformset, or any kind of formset. I could create a working formset with this: from django.forms import inlineformset_factory def my_view(request): ... CustomFormset = inlineformset_factory(Club, Event, fields=('name', 'date')) actual_formset = CustomFormset(instance=Club.objects.get(pk=1) ... Now that works but I get every single event related to the club, but what I actually need to get elements that fit some parameters, for example I want only elements with date greater than today. I haven't found a way to accomplish this and would appreciate any guidance. Thanks for your time -
Implementing a django forum app without cstarting from scratch
I'm looking to add a forum to my site, I have a custom User model that helps me with my own apps (quizzess, uploads etc). I really don't want to create a forum from scratch and there are many wonderful packages for django forums. Does anyone know a good package or implementation where I can get the best of both worlds (not start fresh with the user model from the forum and get the functionalities from the forum package). If not whats the best recourse? -
ERRORS: blog.Post: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'publish'. How do i fix this?
Anytime I try migrating my models. I keep getting this error: ERRORS: blog.Post: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'publish'. Here's my models file. from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts', ) body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title The lines causing the error. class Meta: ordering = ('-publish',) i Would like a quick solution to this. Thanks in advance -
django upload multilple files fields not save
I am trying to upload multiple files but somehow other fields are saved, only the files that were uploaded were saved. I don't know what I did wrong. def company_form(request): if request.POST: form = CompanyFrom(request.POST, request.FILES) files = request.FILES.getlist('Supporting_Documents') if form.is_valid(): for f in files: file_instance = InternationalCompany(Supporting_Documents=f) file_instance.save() messages.info(request, 'Record was successfully added to the database!') return HttpResponseRedirect('/company_form') else: form = CompanyFrom() return render(request, 'company_form.html', locals()) class InternationalCompany(models.Model): International_company_Name = models.CharField(max_length=50) International_company_Id = models.CharField(max_length=50) options = ( ('Yes', 'Yes'), ('No', 'No'), ) Does_it_have_a_Financial_Dealers_License = models.CharField(max_length=20, choices=options, null=True) Register_Office = models.TextField(max_length=500, null=True) Beneficial_owner = models.CharField(max_length=100, null=True) Beneficial_owner_id = models.FileField(upload_to='passport/pdf/',null=True) Supporting_Documents = models.FileField(upload_to='support_doc/pdf/', null=True) expire_date = models.DateField(null=True) BO_Phone_number = models.IntegerField(null=True) BO_Email_Address = models.EmailField(null=True) BO_Residential_Address = models.TextField(max_length=200, null=True) def __str__(self): return self.International_company_Name -
how i can limit choices to django ManyToManyField
how i can limit number of choices to django ManyToManyField ? in my situation this is needed to choose one from many pick-up points pickup = models.ManyToManyField(PickUpPoint,related_name='orders') or how i can do another choice system -
Django Celery shared_task singleton pattern
I have a Django based site that has several background processes that are executed in Celery workers. I have one particular task that can run for a few seconds with several read/writes to the database that are subject to a race condition if a second task tries to access the same rows. I'm trying to prevent this by ensuring the task is only ever running on a single worker at a time but I'm running into issues getting this to work correctly. I've used this Celery Task Cookbook Recipe as inspiration, trying to make my own version that works for my scenario of ensuring that this specific task is only running on one worker at a time, but it still seems to be possible to encounter situations where it's executed across more than one worker. So far, in tasks.py I have: class LockedTaskInProgress(Exception): """The locked task is already in progress""" silent_variable_failure = True @shared_task(autoretry_for=LockedTaskInProgress], default_retry_delay=30) def create_or_update_payments(things=None): """ This takes a list of `things` that we want to process payments on. It will read the thing's status, then apply calculations to make one or more payments for various users that are owed money for the thing. `things` - The list … -
Django how to filter for producer
I have some issues in filtering the producer of the products. I want to display all producers in current category. So far I managed to display all producers when I put in my views 'myForm = Produkty.objects.all()' but it repeats producer name couple times as there is more products in that category from this producer. If I put in my views 'myForm = Producent.objects.all()' it doesn't display multiple times the name of producer but still I don't know how to filter for producer in current category so I can receive only producers in current category. *models: class Producent(models.Model): def __str__(self): return self.name name = models.CharField(max_length=60) description = models.TextField(blank=True) class Meta: verbose_name_plural = "Producent" class Produkty(models.Model): def str(self): return name + ' ' name = models.CharField(max_length=35) description = models.TextField(blank=True) producer = models.ForeignKey(Producent, on_delete=models.CASCADE, null=True) category = models.ForeignKey(Kategoria, on_delete=models.CASCADE, null=True, blank=True) price = models.DecimalField(max_digits=12,decimal_places=2) image = models.ImageField(upload_to="images", blank=True) class Meta: verbose_name_plural = "Produkty" *views: def kategoria(request, id): kategoria = Kategoria.objects.get(pk=id) kategoria_produkt = Produkty.objects.filter(kategoria=kategoria) kategorie = Kategoria.objects.all() paginator = Paginator(kategoria_produkt,3) page = request.GET.get('page') kategoria_produkt = paginator.get_page(page) # myForm = Produkty.objects.filter(kategoria=kategoria) # myForm = Producent.objects.all() produkt = Produkty.objects.get(pk=kategoria) myForm = Producent.objects.filter(id=produkt) dane = {'kategoria':kategoria, 'kategoria_produkt':kategoria_produkt, 'kategorie':kategorie, 'myForm':myForm, } return render(request, 'kategoria_produkt.html', dane) *html: <select … -
Heroku Django migration - ModuleNotFoundError: No module named 'settings'
I am trying to deploy this app to heroku, but i'm getting the following error ModuleNotFoundError: No module named 'oxm_crm.settings' when i run heroku run python manage.py migrate wsgi.py import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oxm_crm.settings') application = Cling(get_wsgi_application()) manage.py import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oxm_crm.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Error: Traceback (most recent call last): File "/app/manage.py", line 20, in <module> main() File "/app/manage.py", line 16, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 343, in run_from_argv connections.close_all() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 232, in close_all for alias in self: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 226, in __iter__ return iter(self.databases) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 153, in databases self._databases = settings.DATABASES File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 177, … -
Django serializer share models and pk with models fields
When sending the data in json format, send the following: [{"model": "callserviceapp.item", "pk": 1, "fields":{.....}} As you can see, the model fields are sent but before "model" is sent: "callserviceapp.item", "pk": 1 Why that? def home (request , data=None): data = serializers.serialize("json", item.objects.filter(radius__lte=data)) if len(data)>0: return HttpResponse(data) else: return HttpResponse(401) -
LoadBalancer - how to intercept queries so that I can send them to all databases? [Python][Django]
I'm creating LoadBalancer package for Django. I wonder how can I intercept quiries so that I can send them to all my databases? I mean CREATE, UPDATE, DELETE queries. -
Django HTML: iteratively generate a new checkbox for each row in a table
I have a view in my Django app that displays a table of all of the factor model objects which are associated with a particular reference model object (indicated by ref_id in views.py below) through a foreign key relationship. This is the HTML for the table (key snippet from the full version of view_factors.html). The third column (Select) is where I would like to render a checkbox for each row. All examples I've found have hinged on knowing the number of checkboxes needed beforehand, but in my case, this number depends on how many factors are related to the reference at hand--the checkboxes must be generated iteratively. Using the code as is below, the Select column renders as blank--no checkboxes appear. <table id="factorTable" class="table table-bordered table-sm" cellspacing="0" width="100%"> <thead> <tr> <th>Title</th> <th>Description</th> <th>Select</th> </tr> </thead> <tbody> {% for factor in ref_factors %} <tr> <td>{{ factor.factor_title }}</td> <td>{{ factor.factor_description }}</td> <td> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input"> </div> </td> </tr> {% endfor %} </tbody> </table> So, I assumed I needed to assign the checkbox an id that can change iteratively, but something like <input type="checkbox" class="custom-control-input" id={{ factor.id }}> does not work as I'm not sure how to parse that factor.id … -
Trying to fix an issue returned by my program
i have an add to cart and place order website everything is smooth i place the order with false shipping address and credit card information and the order is placed but when i log into the admin pannel and try to pick that order up it returns this. TypeError at /admin/core/order/11/change/ str returned non-string (type NoneType) str returned non-string (type NoneType) 9 {% for field in line %} 10 <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 {% if field.is_checkbox %} 13 {{ field.field }}{{ field.label_tag }} 14 {% else %} 15 {{ field.label_tag }} 16 {% if field.is_readonly %} 17 <div class="readonly">{{ field.contents }}</div> 18 {% else %} 19 {{ field.field }} 20 {% endif %} 21 {% endif %} 22 {% if field.field.help_text %} 23 <div class="help">{{ field.field.help_text|safe }}</div> 24 {% endif %} 25 </div> 26 {% endfor %} 27 </div> 28 {% endfor %} 29 </fieldset> my models from django.conf import settings from django.db import models … -
Python/Django: Where in the cloud to store my log files for analysis/visualization?
I have a Django web app nearing deployment. I've been logging to .log files. Rather than CTRL+F, I want some way to export these logs to a cloud service for analysis and visualization. I already have sentry configured for errors but need more granular logging. How can I achieve what I want to do? -
What is wrong with my logic in for loops - django templates
This is my home.html, problem is with the if block: {% for menu in menus %} <div class="dropdown show"> <a class="btn dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ menu.main_menu_item }} </a> <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% for item in menu.items.all %} {% for second_item in item.items_second_level.all %} {% if item.items_second_level.all != None %} <li class="dropdown-submenu"><a class="dropdown-item dropdown-toggle" href="#">{{ item.sub_menu_item }}</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">{{second_item.sub_menu_item}}</a></li> </ul> </li> {% else %} <li><a class="dropdown-item" href="#">{{ item.sub_menu_item }}</a></li> {% endif %} {% endfor %} {% endfor %} </ul> </div> {% endfor %} Namely, {% else %} part always "blanks". When I change condition to {% if item.items_second_level.all == None %} again, only items which satisfies the if condition get showed (obviously this time the ones that were not shown before). it behaves like there is no else. Does anyone know what could be the issue here? -
Django CORS header ‘Access-Control-Allow-Origin’ missing despite being in Response Headers
I have a webpage with a Django Backend API and an angular frontend SPA. I have django-cors-headers==3.5.0 installed and set up (configurations at the end). When trying to load an .mp3 file from my angular frontend SPA from localhost:4200, and only when loading the mp3 file, I receive the following error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.aldrune.com/media/session_audio/2020-12-01_-_Session_28.mp3. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Please note that at the same time I am able to take a look at the HTTP Request and I can see that contrary to the given error message, the response DOES have the header: Access-Control-Allow-Origin: * What gives? How can I have the header in my response and yet my browser claims it's not there? And why does this only happen with the .mp3 file, while all my media and static-file images, that stem from the exact same application- and http-server are unaffected? I am aware a lot of similar questions about Djanog and CORS have been asked before, but I couldn't find any that asked while seeing very clearly that the header that supposedly isn't there is very visible in the request. Below the setup on my … -
Getting TypeError: Failed to Fetch error. even though data is available at backend
I am trying to get data with fetch request but getting 'Typeerror: fail to fetch'.My front end is in react and the backend is in Django.There is no cors issue and when I am firing the query from the frontend, I am able to make data available at the backend but it is not able to reach the frontend. below is my code: try{ const data1 =await fetch( `http://localhost:8000/api/Manual_doc/?year=${e.target[0].value}&number=${e.target[1].value}&label=${e.target[2].value}` ) } catch(err) { alert(err.message); } }``` I am calling manual search on click on the button. Any help will be appreciated. -
TypeError: Movie() got an unexpected keyword argument 'actors'
I am working on a school project using Django and Python. Now I have created a website for using rest-apis. However, while testing I encountered an error that I simply can't seem to be able to solve. It occurs whenever I try to create a movie with POSTMAN using the api.I get the following error over and over again and I can't find what is wrong. Error message: raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Movie() got an unexpected keyword argument 'actors' My serializer class MovieSerializer(serializers.ModelSerializer): # Queryset gets all the data from the Actor model as specified with objects.all() actor_pks = serializers.PrimaryKeyRelatedField(queryset=Actor.objects.all(), source='actors', write_only=True, label='Actors', many=True) rent_pks = serializers.PrimaryKeyRelatedField(source='rent', read_only=True, label='Rent') # Change image-options to allow post/put/patch without an image image = serializers.ImageField(allow_null=True, required=False) def __init__(self, *args, **kwargs): # Get additional parameters from constructor depth = kwargs.pop('depth', None) fields = kwargs.pop('fields', None) # Add diffrent pks to fields if field is not None from constructor fields.append('actor_pks') if fields is not None else None fields.append('rent_pks') if fields is not None else None fields.append('image') if fields is not None else None # Overwrite meta tags self.Meta.depth = depth if depth is not None else 1 self.Meta.fields … -
How to check if value is None
I want to check if the "nilai" is None/Null cursor.execute('SELECT s.kode_ktg_id,(SUM(n.nilai_angka * S.nilai_mk)/SUM(s.nilai_mk)) as nilai_ktg FROM mahasiswa_khs k, mahasiswa_convert_nilai n, mata_kuliah_si s WHERE k.nilai = n.nilai_huruf AND k.nim = "%s" AND k.kode = s.kode GROUP BY s.kode_ktg_id',[nim]) nilai = cursor.fetchall() I check with this if nilai[0] is None: But I got error tuple index out of range -
Django authenticate returning none but login works?
When I run the below code, it prints "done." However, when I check if user is returning anything, it doesn't - it returns None. Is this a problem, if dj_login() is running without any errors? def login(request): if request.method == 'POST': try: username = request.POST.get('username') password = request.POST.get('password') try: user = authenticate(request, username=username, password=password) dj_login(request, user, backend='django_auth_ldap.backend.LDAPBackend') messages.success(request, "You have been logged in.") print("done") return render(request, "app/login.html") except Exception as e: print(e) messages.error(request, "Failed to Login Errors: {}".format(e)) return render(request, "app/login.html") except Exception as e: messages.error(request, "Failed to Login Errors: {}".format(e)) return render(request, "app/login.html") return render(request, 'app/login.html') -
Django rest_framework with custom User model - duplicate key value violates unique constraint
I start to learn django (rest_framework) and build an app. I created a custom user model and manager, below the code: class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_('username'), max_length=255, unique=False, blank=True) mobile = models.CharField(_('mobile'),max_length=255, blank=True) picture = models.ImageField(upload_to='images/thumbnail/%Y/%m/%d/', null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] @property def picture_preview(self): if self.picture: return mark_safe('<img src="{}" width="300" height="300" />'.format(self.picture.url)) return "" objects = CustomUserManager() I have also customize the view for the admin..and everything work fine. Now when I register a new user from the admin and for instance I put two … -
Loadbalancer - multiple databases in django
I am writing a loadbalancer project, where I am supposed to catch all sql requests and execute them with my methods, but not while using decorators (@loadbalancer) as I would have to use them in each model. Is there a way to write it once and it will work for all? -
Filter ManyToMany by user from current model
I'm bit stuck on one stuff. How I can reach all Rerservation from the current Main model which belongs to the current user? Any help will be be appreciate class ReservationPay(generic.DetailView): model = Main def get_context_data(self, **kwargs): context = super(Reservation, self).get_context_data(**kwargs) context['user_rea'] = Main.objects.filter(all_resa__user=self.request.user).all() class Rerservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) class Main(models.Model): all_resa = models.ManyToManyField('Rerservation',blank=True, related_name='all_resa_reservation') -
Define list of objects in models.py in postgeSQL & Django-rest project
I mostly work with Node.js & MongoDB and I am pretty new to SQL dbs especially postgreSQL I am writing an application that makes use of django-rest-framework & postgreSQL as a DB. This is how my data structure as .json should look like. { id: "19eea956-34e5-11eb-adc1-0242ac120002" picture: [{ url: "", mimeType: "" }, { url: "", mimeType: "" }] } For the above data I am currently writing models.py which looks like as follows. from django.db import models from django.contrib.postgres.fields import ArrayField class Picture(models.Model): url = models.CharField() mimeType = models.CharField() class A(models.Model): id = models.CharField(max_length=120, primary_key=True) picture = ArrayField(Picture) def __str__(self): return self.id What I am trying to do in my models.py is to have picture as an Array of Objects or in python terminology List of Dictionaries. I read about ArrayField in postgreSQL but unable to find any example about how to define Array of Objects in models.py, any help here would be appreciated. Thanks :) -
Django form not showing except for submit button
I'm having this issue where the django form isn't showing up on the webpage. The only thing that shows up is the submit button. I cannot figure out the issue. Views.py class NewThreadView(CreateView): model = Thread form_class = NewThreadForm template_name = 'thread/newthread.html' def get_context_data(self, *args, **kwargs): context = super(NewThreadView, self).get_context_data(*args, **kwargs) forms.py class NewThreadForm(forms.ModelForm): class Meta: model = Thread fields = ('name', 'body', 'author', 'thread_forum') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter title'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'author', 'type': 'hidden'}), 'thread_forum': forms.Select(attrs={'class': 'form-control', 'type': 'hidden'}), } newthread.html <div class="form-group"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" name="thread_submit">Create Thread</button> </form> </div> -
I need help correcting that issue
i have that error when im trying to access an object on my admin. TypeError at /admin/core/order/11/change/ str returned non-string (type NoneType) my model for the order class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete= models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete= models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total= 0 for order_item in self.items.all(): total += order_item.get_final_price() return total i cannot have access on the admin what should i do please?