Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show Many-to-Many Field on Django Admin Panel?
I have 2 models, Product and Tag. The relation between product and tag is Many-to-Many Relationship. How to show "tags" field on django admin panel? Currently the value is None when I am using the code below models.py class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['id','name','price','category','tags'] list_display_links = ['name'] def tags(self): return self.tags.name -
REST Framework — Serializing many-to-many. Create and Save
I am using django-restframework for my API. My problems: I can't validate data. Need to create "regions" and nested with courier. Regions send as a list in json. But when validating the data, I get the following errors: error_valid {'regions': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')] How I can created models with this json POST request? The POST json: { "data": [ { "courier_id": 10, "courier_type": "foot", "regions": [1, 12, 22] }, { "courier_id": 11, "courier_type": "bike", "regions": [22] },.. ] } My models.py: class Regions(models.Model): region_id = models.PositiveIntegerField(unique=True) def __str__(self): return self.region_id class Courier(models.Model): courier_id = models.PositiveIntegerField(unique=True, ) courier_type = models.CharField(max_length=4, choices=TypeCourier.choices, blank=False, ) regions = models.ManyToManyField("Regions", through=RegionsCouriers, through_fields=("courier", "region" ), ) Regions will need to be created together with the post request my serializers.py class RegionsSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = Regions class CourierSerializerPost(serializers.ModelSerializer): regions = RegionsSerrializer(many=True) class Meta: model = Courier fields = "__all__" my View.py class CourierView(APIView): def post(self, request): data = request.data["data"] couriers_add = [] couriers_fail = [] for record in data: serializer = CourierSerializerPost(data=record) if serializer.is_valid(): courier_id = … -
Unable to update many to many fields in Django Rest Framework
I have a Product model which has many fields, some of them have many to many relationships with other models, for eg the Category model. I am able to update other fields but I am stuck at updating the m2m fields from the JSON payload sent from the frontend. I have the logic, but can't write the code. I have to first remove the existing categories which are associated with that product and add the new categories that are on the payload from the ids. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services',] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) #category_logic category_data = validated_data.get('category') #new_category = validated_data.pop('category') product = … -
Creating a pagination using Django
I'm working on a small project using Django Rest Framework and i'm looking for a way to create pagination using Viewset, i checked the DJR documentation but i couldn't find any answer about doing pagination with Viewsit class, this is my code : class ContactView(viewsets.ViewSet): def list(self, request): contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data) -
TypeError: __init__() got an unexpected keyword argument 'use_required_attribute' - django
django(3.1.7) python(3.9.0) I've been working on putting an input validation for my modelformset and this is what I had come up this code is working well until today I don't what happen but suddenly this error shows up and it seems it all point towards the django package in my virtual environment so if anyone have any idea to fix this thank you. Also, if anyone knows a better way to validate a modelformset your answer would be much appreciated thank you. Forms.py from django.forms import modelformset_factory, DateTimeField, BaseModelFormSet from django.contrib.admin import widgets class OrderFormSetValidation(BaseModelFormSet): def clean(self): products = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue product = form.cleaned_data.get('product') quantity = form.cleaned_data.get('quantity') theme = form.cleaned_data.get('theme') flavor = form.cleaned_data.get('flavor') text = form.cleaned_data.get('text') price = form.cleaned_data.get('price') products.append(product) if isInvalidInput(product): raise forms.ValidationError(("This field is has invalid value")) OrderFormSet = modelformset_factory( Order, form=OrderFormSetValidation, can_delete=True, fields=('product','quantity','theme','flavor','text','price'), widgets={ 'quantity': forms.NumberInput(attrs={'placeholder':'0',}), 'theme': forms.TextInput(attrs={'placeholder':'Theme','maxlength':256}), 'text': forms.TextInput(attrs={'placeholder':'Text','maxlength':256}), 'price': forms.NumberInput(attrs={'placeholder':'0.00','step':1}) } ) Error Traceback (most recent call last): File "C:\Users\John\Envs\test\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\John\Envs\test\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\John\Envs\test\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\John\Envs\test\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\John\Envs\test\lib\site-packages\django\template\backends\django.py", line … -
Django: How to use AUTH_USER_MODEL
I have seen several posts and read the documentation about how it's best practice to set AUTH_USER_MODEL in settings.py, but do not see any actual examples on how to do that. I have tried several configurations but keep getting this error: AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'auth.User' that has not been installed It doesn't even tell me where the error is occurring. Below are the methods I have tried: METHOD 1: from django.contrib.auth import get_user_model User = get_user_model() Then I would just reference my user like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) METHOD 2: from django.contrib.auth.models import User Neither worked, and I'm not sure how I would set AUTH_USER_MODEL in settings.py if I just want to use the standard user model. I'm not customizing the User object at all. I assume something like AUTH_USER_MODEL = 'django.contrib.auth.models.User' but i'm not sure. -
Setting up virtual environment in Django
i just started learning django and i am very confused in how to set up a virtual environment. i have successfully installed python: When i run python --version i get Python 3.8.1 and when i run python3 --version i get Python 3.8.1 My first problem is when i run which -a python3 i get this /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 /usr/local/bin/python3 /usr/bin/python3 Can someone help me understand why i have 3 locations where python3 exist? My 2nd problem is i have successfully installed virtaulenv and virtualenvwrapper when i run virtualenv --version i get: virtualenv 20.4.3 from /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/virtualenv/__init__.py and when i run virtualenvwrapper --version i get: -bash: virtualenvwrapper: command not found thats why when i run mkvirtualenv test i keep getting command not found. My third problem is what is the difference between virtualenv test and mkvirtualenv test? -
OSMWidget Django form location coodinates are incorrect
I have the following form field point = gis_forms.PointField(widget=gis_forms.OSMWidget( attrs={'map_width': 800, 'map_srid': 4326, 'map_height': 500, 'default_lat': 49.246292, 'default_lon'-123.116226, 'default_zoom': 7,})) The form is rendered in django as <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit">Submit for Review</button> </form> But when the data comes in POST the locations are incorrect. def register_storage(request): if request.method == 'POST': form = MyGeoForm(request.POST) if form.is_valid(): data=form.cleaned_data print(data.get('point')) print(data.get('point').srid) The SRID is showing up as 3857 and weird default coordinates -13645232.541356523 6283123.725041488 I thought it was my django version, but it is updated to 3.1.3 due to some functionality with GDAL. But no luck. Very lost here. -
multiple default values specified for column "id" of table "Transaction"
I'm trying to deploy a Django app to Heroku, and the moment I start doing the migrations with these commands: heroku run python manage.py makemigrations heroku run python manage.py migrate I get the following error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "Transaction" This is the code from my Transaction Model: class Transaction(models.Model): """Modelo de Transaccion""" id = models.CharField(max_length=8, primary_key = True) TnType = models.ForeignKey(TransactionType, on_delete=models.CASCADE, blank=True, null=True, related_name='id_tn_type') userReceiver = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user_receiver', blank=True, null=True) userTransmitter = models.ForeignKey(User,on_delete=models.CASCADE, related_name='user_transmitter', blank=True, null=True) amount = models.IntegerField(blank=True, null=True) creationTime = models.DateTimeField(default=datetime.now) concept = models.CharField(max_length=80, blank=True, null=True) STATUS = ( ('A','Active'), ('I','Inactive'), ) status = models.CharField(max_length=1,choices=STATUS, default='A') def __str__(self): return self.id class Meta: db_table = "Transaction" class TransactionAdmin(admin.ModelAdmin): list_display = ('id', 'userReceiver', 'userTransmitter', 'amount' ) I really don't understand this error, I've been trying a lot of things with no luck. I hope someone could help. -
Linking front-end to back-end in Django using vanilla javascript
I understand that you can use the fetch API to send data from the front-end to your backend to be processed by django views. I also know that you can use jquery API to do the "fetching of data. I am wondering if there are any other common methods using only javascript to send data from the front to the back without using the fetch api or jquery ajax. -
how to add otp authentication in django login page
Firstly, the login.html should ask for 'Enter OTP' once the email(username) is entered and submitted. This username is checked with user table if the user exists. If user exists , it should send OTP to the mobile registered for this user instance. On entry of the OTP, user should get appropriate message to reset password or get the home page. I don't want to use the django-otp app. What i have done so far: In the django accounts/registration/templates/login.html {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "admin/css/login.css" %}"> {{ form.media }} {% endblock %} {% block bodyclass %}{{ block.super }} login{% endblock %} {% block usertools %}{% endblock %} {% block nav-global %}{% endblock %} {% block content_title %}{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} {% if form.errors and not form.non_field_errors %} <p class="errornote"> {% if form.errors.items|length == 1 %}{% trans "Please correct the error below." %}{% else %}{% trans "Please correct the errors below." %}{% endif %} </p> {% endif %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p class="errornote"> {{ error }} </p> {% endfor %} {% endif … -
Is there anyway to clear Firebase notoficaion programitally?
I am new to Firebase, I want to control the notification from django which is going to the android devices of the customer. I want to make sure that if the email if seen from any device either from desktop or any other means, the Firebase notification should be deleted, as the email is already seen. Any help will be appriciated. -
Django - Protect media files with django-wiki
In the past I managed to protect my images in other projects in the following way: urls.py urlpatterns = [ ... path('media/<str:filename>/', views.media, name="media"), ] settings.py #MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py @login_required def media(request, filename): import os from mimetypes import MimeTypes content_type, encoding = MimeTypes().guess_type( os.path.basename(filename) ) if content_type is None or len(content_type) == 0: print(f'No content-type found for file: {filename}') content_type = 'text/plain' try: url = os.path.join( settings.MEDIA_ROOT, str(filename) ) with open(url.encode('utf-8'), 'rb') as f: resp = HttpResponse(f.read(), content_type=content_type) # resp['Content-Disposition'] = f'attachment; filename="{filename}"' resp['X-Robots-Tag'] = 'noindex, nofollow' return resp except IOError as ex: data = {'ERROR': str(ex)} print(data) return JsonResponse(data) With this, if someone tries to view for example an image via the url www.example.com/media/image.png, the user cannot see anything unless they are logged in. I need to use the django-wiki system https://github.com/django-wiki/django-wiki which I have installed in my existing project through pip install wiki. Now my project works together with the wiki system. Wiki system is installed in this path: /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ Is there any way to protect images in the same way for the wiki system? I think modifying .../site-packages/wiki/ views is not a good idea and perhaps there is a better solution to … -
django - relation already exists (special problem)
I made changes, created a new branch, committed, then migrated (after makemigrations). But in that commit, it contained changes that I pulled remotely and it looked like my own. I did not want this because I work on a team, so I made a new branch with only my changes. The problem is, our database kept the migrations, but the code didn't. So when I try to migrate, I get "migration already exists." What do I do here? Is this a case where --fake would be useful? Any help is appreciated. Thanks in advance -
Geonode paver setup not setting geonode correctly
i am installing geonode, when i came across the instruction of paver setup. It is not running properly. The error message given as shown below. (geonode) eidul@eidul-Virtual-Machine:/opt/geonode$ paver setup free(): invalid pointer Traceback (most recent call last): File "/home/eidul/.virtualenvs/geonode/bin/paver", line 8, in <module> sys.exit(main()) File "/home/eidul/.virtualenvs/geonode/lib/python3.8/site-packages/paver/tasks.py", line 890, in main _launch_pavement(args) File "/home/eidul/.virtualenvs/geonode/lib/python3.8/site-packages/paver/tasks.py", line 858, in _launch_pavement exec(compile(source, environment.pavement_file, 'exec'), mod.__dict__) File "pavement.py", line 62, in <module> from geonode.settings import ( File "/opt/geonode/geonode/settings.py", line 115, in <module> spatialite_version = int(spatialite_proc.stdout.decode()[0]) IndexError: string index out of range -
Two datetime columns in one line then the behind would not show the column name in django admin
I am a Django Developer. Now I am facing a problem, which is that if I put two datatimefield columns in on line in django admin, then the behind column's name will just be hidden unless highlighting it. For more detail please refer the below two pictures. I'd like to know is there any way to keep them in one line resolve this question? -
please any one tell me the solution ModuleNotFoundError: No module named 'django.core'; 'django' is not a package
while starting the django-admin startproject demoproject i'm getting ModuleNotFoundError: No module named 'django.core'; 'django' is not a package this error how can i solve this error -
Is it possible to monitize a blog on heroku's hobby account?
Is it possible to monetize a blog on Heroku's hobby account? Is it ideal for such purposes? I have one on the free tier & I'm not sure about upgrading. Better yet, what hosting service is most suitable (affordability, efficiency) for a Django blog expecting web-traffic? -
Invoice template: render html table "Discount" column only if any item has a discount
Disclaimer, I haven't worked with Django or Python before, so any help/guidance is appreciated. I'm working on a quote/invoice template using Jinja/Django syntax. A quote has multiple line items, some of which may have a discount on them. I'd only like to render the "Discount" column in the html table if any one of the items has a discount on it. The trouble I am having is figuring out if any one item has a discount (either dollar or percent), and telling the template to render or not render that html conditionally as a result. This is a simplified array/list of line item data available: lineItems=[ {acv=64000.0 discount= discount_percentage= price=64000 quantity=1 name=Item One id=0} {acv=44000.0 discount=1500 discount_percentage= price=64000 quantity=1 name=Item One id=1} {acv=2000.0 discount= discount_percentage= price=64000 quantity=1 name=Item One id=2} ] At first I thought to create a global "hasItemDiscount" variable, and then use a for loop to iterate through the list items and update the global variable if any had a discount value than 0. Something to this effect: {% set hasItemDiscount = false %} {% for item in lineItems %} {% if item.discount > 0 or item.hs_discount_percentage > 0 %} {% set hasItemDiscount = true %} {% endif … -
how to make static files works using django docker nginx and postgresql since its not serving them
Sorry for probably asking a similar question to other people here but i tried to read multiple similar questions here and still not able to serve the static files. when i try to access http://127.0.0.1:8000/admin, i get this. my folder structure is : django-react-nginx | |_ _ docker-compose.yml | > backend | |_ Dockerfile | |_ entrypoint.sh > languages | |_ settings.py > media > static # This folder appears after running docker-compose -d --build > nginx | |_ default.conf | |_ Dockerfile now here is the files Django Docker file FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /backend COPY requirements.txt /backend/ RUN pip install -r requirements.txt && \ pip install --upgrade pip COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] Django entrypoint.sh #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn languages.wsgi:application --bind 0.0.0.0:8000 Docker default.conf upstream django { server backend:8000; } server { listen 80; location / { proxy_pass http://django; } location /static/ { autoindex on; alias /static; } } Docker-compose version: "3.7" services: backend: build: ./backend/languages stdin_open: true # interactive tty: true # interactive restart: "on-failure" env_file: .env volumes: - ./backend/languages:/backend - ./backend/languages/static:/static ports: - 8000:8000 networks: - nginx_network - db_network depends_on: - db db: image: … -
How to paginate data from external api in Django?
I query external news api with Django. The api returns the total_results and by default 20 articles.Example response is in https://newsapi.org/docs/endpoints/top-headlines My Django view is def index(request): #default values us and general country = 'us' category = 'general' if request.method == "POST": try: country = request.POST['country'] category = request.POST['category'] except: #in case user does not choose country and/or category return HttpResponseRedirect(reverse("index")) news_request = requests.get(f"https://newsapi.org/v2/top-headlines?country={country}&category={category}&apiKey={env('API_KEY')}") news = json.loads(news_request.content) return render(request, "news/index.html", {"news":news}) Is there a way to paginate these kind of data? -
Install Django package via pip into another package (site-packages) instead of the main project
Let's say I have a project, ProjectA. In ProjectA, I installed the following package via PIP pip install wiki to embed a wiki system on my web page: https://pypi.org/project/wiki/ All wiki system files are stored in /Users/{my_username}/.virtualenvs/{my_virtualenv_name}/lib/python3.9/site-packages/wiki/ so when I want to do some modification, I have to do it in the path specified above (which I don't know if it is good practice). For now there has been no problem in modifying the templates, but the wiki will be used in an intranet, that means that I have to protect the files (especially the images) so that if a user wants to access an image, for example: http://projecta.com/img.png, the user has to be previously logged in to view that image. There are packages to protect media, like this one. The thing is, for that to take effect, I need to modify the models on my wiki (which are in a completely separate location from ProjectA) and replace ImageField with ProtectedImageField. My question is, how can I install (via pip) the django-protected-media package for wiki (previously installed via pip) instead of for ProjectA? Or, in other words, how can I install the package 'django-protected-media' and use it in 'wiki' instead … -
Django clear media files every 24hrs
Im creating a project where i require all media to be deleted at a 12am every day so there is a new fresh start. how would i go about doing this within my django project. -
Django view with two forms not posting one
Im trying to use one form to get data for two different models, to do so, I changed my create view get_context_data function like this: class tarea_crear(CreateView): template_name = "crud_tareas/tarea_crear.html" form_class = tareaForm success_url = reverse_lazy('tareas:crear-tarea') def get_context_data(self, **kwargs): context = super(tarea_crear, self).get_context_data(**kwargs) context['form'] = {'audiosForm':audiosForm,'tareaForm':tareaForm} return context This allowed me to call both forms on my template, like this: (Dont worry, I remembered the crfs tag and the form) {{form.tareaForm.as_p}} {{form.audiosForm.as_p}} <input type="submit" value="Crear Tarea"> I also needed to validate some informationfrom the first form, and I did it like this in the view: def form_valid(self, form): titulo = form.cleaned_data['titulo'] if not any(i.isdigit() for i in titulo): return super(tarea_crear, self).form_valid(self, form) return super(tarea_crear, self).form_invalid(self, form) The problem is that when I do the POST of the form, only the first half of the data is actually sent, I know this because I cant call form.cleaned_data['audios'] in the view without getting an error. Any idea how to handle a View with two forms? -
Get previous and next Child objects in ordered Parent queryset (where Children can also be parents)
Say I'm trying to build a library of Books. A Book can have many Chapters. A Chapter can also have many Chapters. (For example, if you look at the Tables of Contents for Les Miserables, you'll see that Les Miserables is divided into volumes, the volumes are divided into books, and the books are divided into chapters. So for our purposes, "Les Miserables" is our Book model and its volumes, books, and chapters are our Chapter model.) What is the best way (or any way!) to generate the correct "previous" and "next" object for any given Chapter? I've decided to use Single Table Inheritance proxy models as outlined in this article: class Text(models.Model): type = models.CharField(max_length=255) title = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) parent = models.ForeignKey( "self", related_name="children", default=None, blank=True, null=True, on_delete=models.CASCADE, ) order = models.IntegerField(blank=True, null=True) def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Meta: ordering = ["order", "pk"] …