Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering, ordering and pagination in clean architecture django rest
I recently used clean architecture for my project. The project is divided into several sections according to clean architecture, each of which performs its tasks. But what confused me is that, I do not know how can I use filter and pagination class in this architecture. -
"NodeAlreadySaved " error when using djangocms publishing page changes
Encounter an error when using djangocms publishing page changes. when I ran tail -f /var/log/apache2/error.log, it returned: treebeard.exceptions.NodeAlreadySaved: Attempted to add a tree node that is already in the database, referer: http://47.95.254.172/?edit And when I allowed the settings.py DEBUG= True and click the 'Publish page changes' button: NodeAlreadySaved at /admin/cms/page/1/en/publish/ Attempted to add a tree node that is already in the database Request Method: POST Request URL: http://47.95.254.172/admin/cms/page/1/en/publish/ Django Version: 3.1.7 Exception Type: NodeAlreadySaved Exception Value: Attempted to add a tree node that is already in the database Exception Location: /root/env1/lib/python3.8/site-packages/treebeard/mp_tree.py, line 326, in process Python Executable: /root/env1//bin/python Python Version: 3.8.5 I have run python manage.py cms fix-tree but it did not work. While python manage.py cms check returned 10 checks successful!. I deployed the djangocms project with: apache2.4.41 mod-wsgi 4.8.0 django 3.1.7 django-cms 3.8.0 The python version in venv is 3.8.5, and mod-wsgi was compiled by python3.8.5 in the venv. Thank you for the help! -
How can store Multiple checkbox value to single user
I am trying save multiple id of products from checkbox to a specific user, but i select multiple values and submit them it show the error. ' Field 'id' expected a number but got ['13', '14', '22']. ' when i select any category from drop down menu it just only show last added category, not show that category which i select view.py class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products, 'selectedCategory': categoryId} return render(request, self.template_name, args) def post(self, request, vendor_id): categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.POST.getlist("ProductSelect") try: vendor = VendorCategory( vendor_id=VendorModel.objects.get(id=vendor_id), category_id=categoryobj, product_id=productobj, ) vendorCate.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory" > <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yes, no"|safe }}"> Select Category</option> {% for category in categories %} <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}"> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> <form method="post"> <input type="hidden" value={{ selectedCateogry }} name="ProductSelect"> {% csrf_token %} <label> {% for product in products%} <input type="checkbox" name="ProductSelect" value="{{ product.id }}" >{{ product.name … -
How could i get an object correctly from database in a different server in python?
I am trying to work with a machine learning and a web server with django, and both my web and machine learning server use the same dockerized postgres database. Machine learning server creates machine learning models and writes them to the database by using pickle. I have a Regressor class in machine learning server like this: class Regressor: def __init__(self): self.predictions = [] self.yTrue = [] self.predDiffs = [] self.model = object self.name = "" #some methods below and i have a class that creates an appropriate database table for orm technique class RegressorTable(DeclarativeBase): __tablename__ = "ml_models" id = Column(Integer, primary_key=True) regressorName = Column(String) regressorModel = Column(LargeBinary) and both in machine learning and django web server, i have 2 functions in order to convert models to binary and binaries to model def modelToBinary(model): return pickle.dumps(model) def binaryToModel(data): return pickle.loads(data) Here is my method in the machine learning server to save the Regressor models for the database: def saveModelsToDb(predictorArray): for predictor in predictorArray: predictorForTable = RegressorTable() predictorForTable.regressorName = predictor.name predictorForTable.regressorModel = modelToBinary(predictor) DBSession.add(predictorForTable) DBSession.commit() The predictorArray in the above code contains Regressor objects. When i try to save and load models in machine learning server, i can successfully save, load and … -
Realtime sharing of Website content to other user
I have a django web application with a map view using openlayers. I have to develop a map sharing screen in real time to other user in the application for the real time view/suggestion for the edit. How to develop the real time web content sharing system. -
Django. Model function for avatar
I wrote a function for the profile model so that if the profile does not have an avatar, there will be a default picture. But this function works only when the profile has a picture, and when it does not exist, there is the absence of any image tag . How can I write the function correctly so that it displays a picture from the media folder of the project directory? @property def avatarURL(self): try: url = self.avatar.url except: url = 'media/avatar.svg' return url ── ./media │ ├── ./media/avatars │ ├── ./media/avatar.svg │ └── ./media/images HTML <img src="profile.avatarURL" alt="Profile picture class="round"/> -
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 …