Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django money - making a MoneyField in my model
So I've been trying to import A money field from django-money using this code from djmoney.models.fields import MoneyField but every time am getting the same error Import djmoney.models.fields" could not be resolved I added djmoney to installed apps in the settings file and I used pip install django-money as well but it's still giving me the same error django-money version: 2.1 django version: 3.2.7 -
Django create an object that has a reference to another object using serializers
I want to create an order that has multiple ads and each ad must have a reference to a display object. I did this kind of thing previously just by setting the object's id in the put method and it worked well. models.py class OrdersDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) user_id = models.CharField(max_length=45, blank=True, null=True) class Meta: ordering = ["dateplaced"] class AdsDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) order = models.ForeignKey(OrdersDj,on_delete=models.CASCADE, blank=False, null=True) display = models.ForeignKey(Displays, on_delete=models.CASCADE, blank=False, null=True) null=True) serializers.py class AdsSerializer(serializers.ModelSerializer): display = DisplaySerializer() class Meta: model = Ads fields = "__all__" class OrderSerializer(serializers.ModelSerializer): ads = AdsSerializer(source="adsdj_set", many=True) def create(self, validated_data): ads_data = validated_data.pop('adsdj_set') order = Orders.objects.create(**validated_data) for ad in ads_data: Ads.objects.create(order=order, **ad) return order class Meta: model = Orders fields = "__all__" the put method data { "user_id": "1", "ads": [ { "display_id": "10", // "display" : 10, // "display" : "10", } ] } Here in dependence of what I insert for display, it expects a dictionary and not any other types. { "ads": [ { "display": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } } ] } -
creation of a new script tag in shopify
I am sending the post request to https://mystore.myshopify.com/admin/api/2021-10/script_tags.json with the respective request body. request body params below:- { "script_tag": { "event": "onload", "src": "my_link_to_script", "display_scope": "order_status" } } however i am getting the successful creation response. But the tag is not get inserted into my store checkout page. I am inserting the image below where the tag should get inserted after the successful response. enter image description here -
want to get multiple values from dropdown after adding script tag in html page it stop working or using select and script tag togetherit stop working
This is my load clients function from where I pass value to clients.html page views.py def load_clients(request): CPA_id = request.GET.get('CPA_id') clients = CPA_Client.objects.filter(CPA_id=CPA_id) return render(request, 'crm/clients_dropdown_list_options.html', {"clients": clients}) # return JsonResponse(list(cities.values('id', 'name')), safe=False client.html <select id="ddselect" name="framework[]" multiple class="form-control"> <option value="----">------</option> {% for Client_of_CPA in clients %} <option value="{{ Client_of_CPA.pk }}">{{ Client_of_CPA.name }}</option> {% endfor %} </select> In this code i am getting my output but need to select multiple values from a dropdown thats why i want to add some functionality of bootstrap jquery due to which i need script tag. After adding script tag page stop working -
How to style crispy forms with bootstrap4 in django?
I'm trying to style upload form used from crispy forms. Can you give me simple solution, and not to get too crazy about css. This is how it looks now! This is upload_document.html {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <h1>Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Upload</button> </form> {% endblock content %} models.py from django.db import models class UploadFile(models.Model): excel = models.FileField(upload_to="excel/", max_length=250) def __str__(self): return self.title forms.py from .models import UploadFile class GlForm(forms.ModelForm): class Meta: model = UploadFile fields = ('excel',) -
Reuse Django field definitions in other models
I'm having a few fields throughout different models. E.g. class A(models.Model): field_1 = models.CharField(max_length=5, blank=False) field_2 = models.CharField(max_length=100, blank=False) field_3 = models.CharField(max_length=200, blank=False) class B(models.Model): field_4 = models.CharField(max_length=5, blank=False) field_5 = models.CharField(max_length=100, blank=False) field_6 = models.CharField(max_length=200, blank=False) In addition of these classes, I want to create a lead class. This class contains data that will be potentially copied into the other models in the future. The data constraints are therefore the same but since this is optional data, some might be missing. I want to use DRY, but I also want to update the blank field. Any tips on how to use the exact field definitions from those original classes? class Lead(models.Model): field_1 = A.field_1 # but with updated blank field field_3 = B.field_3 # but with updated blank field I considered class dependency, but in reality I'm using fields from 5 classes which I fear will become an unreadable mess if the lead class depends on these. -
Django wagitail backend oracle migrate ORA-00907: missing right parenthesis
Django 3.2.9 Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production cx_Oracle 8.3.0 Python 3.7.6 I create a new project Wagtail and i change in setting.py Database section DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1526)) (CONNECT_DATA = (SERVER = DEDICATED) (SID = XXXX)))', 'USER': 'ZZZZZZ', 'PASSWORD': 'ZZZZZZZ', 'HOST': '', 'PORT': '', } } when execute python manage.py migrate show this error: WARNINGS: wagtailcore.WorkflowState: (models.W036) Oracle does not support unique constraints with conditions. HINT: A constraint won't be created. Silence this warning if you don't care about it. Operations to perform: Apply all migrations: admin, auth, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying wagtailcore.0059_apply_collection_ordering...Traceback (most recent call last): File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\db\backends\oracle\base.py", line 523, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-00907: missing right parenthesis The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\A262556\Documents\PROGETTI\prj-intranet-new\cms-prova\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute … -
Is there a way to allow blank data for Django restframework
I have a products model that I want to have optional fields that are not required by the user whenever i try to input empty data it throws an error 400 back to the user meaning the serialized data is not valid views.py def products(request): if request.method == 'GET': products = Product.objects.filter(user=request.user) serializer = ProductSerializer(products, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data) serializer.initial_data['user'] = request.user.pk if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' models.py class Product(models.Model): name = models.CharField(max_length=50) description = models.TextField(blank=True) price = models.FloatField() quantity = models.IntegerField(blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING) discount = models.FloatField(default=0) -
unicode_to_repr - depricated package of "rest_framework"
While upgrading Django 2.2 to 3.2.9 I've encountered a couple of dependencies that were deprecated, of which "unicode_to_repr" is the one I couldnt find sufficient information about, neither on its usage or of its substitutes. Can someone advise how to proceed? Is there a valid replacement for this module? Thank you, Lior. -
Put data from form to database - Django - sqlite3
I'm trying to solve this problem. I have buttons, which values send to this form- So it's that initial. And user instance. And I want to send the data to databse and I don't know how... I will be glad that you help me views.py def form_create(request, pk): form = Message() user = User.objects.get(username=request.user.username, first_name=request.user.first_name, last_name=request.user.last_name, email=request.user.email) undermessage = Undermessage.objects.get(id=pk) if not request.user.is_anonymous: # it is pre-filled form = Message(request.POST or None, initial={'email': user.email, 'sender': user.username, 'name': user.first_name, 'surname': user.last_name, 'm1': undermessage.m1, 'm2': undermessage}) if request.method == "POST": if form.is_valid(): form.save() return redirect("/") context = { 'undermessage': undermessage, 'form': form } return render(request, 'form.html', context=context) models.py class Message(models.Model): time = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, null=True, blank=False, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=False) surname = models.CharField(max_length=100, null=True, blank=False) m1 = models.ForeignKey(M1, null=False, blank=False, on_delete=models.CASCADE) undermessage = models.ForeignKey(Undermessage, null=True, blank=True, on_delete=models.CASCADE) text = models.TextField(blank=True) some error: Cannot assign "'usr1'": "M1.sender" must be a "User" instance. thank you a lot!! -
set an objects boolean in views (django)
I want to set a booleanfield to True. this is the code in views: def iniciarTorneo(request, id): torneo = Torneo.objects.get(pk=id) torneo.iniciado = True torneo.save() return render(request, 'torneos/detalle.html', {'torneo': torneo}) I come from here: path('iniciar_torneo/<int:id>', iniciarTorneo), But the boolean is not changing. -
Nginx Django and ReactJS
Here is Nginx config file: server { server_name atlasalgorithms.com www.atlasalgorithms.com; root /home/ubuntu/tc/react/build; index index.html index.htm index.nginx-debian.html; location /api { limit_req zone=one; limit_conn addr 10; include proxy_params; proxy_pass http://unix:/home/ubuntu/tc/config.sock; } location / { try_files $uri /index.html; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/atlasalgorithms.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/atlasalgorithms.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.atlasalgorithms.com) { return 301 https://atlasalgorithms.com$request_uri; } # managed by Certbot if ($host = atlasalgorithms.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name atlasalgorithms.com www.atlasalgorithms.com; return 404; # managed by Certbot } The issue is that Django is reading that /api path, I have /dashboard API endpoint when I go to https://atlasalgorithms.com/api/dashboard/ Django reads the path as api/dashboard/ which results in Page not found (404) The current path, api/dashboard/, didn’t match any of these. how can I fix this? -
Django queryset annotate if SearchQuery is found in field
I have a model like this: (With a trigger in Postgres that populates vector_column) class Article(models.Model) content = models.TextField() vector_column = SearchVectorField(null=True) I query this model like this: Article.objects.filter( Q( vector_column=SearchQuery( "cat", config="english", search_type="phrase" ) | vector_column=SearchQuery( "dog", config="english", search_type="phrase" ) ) ) So it will filter out all articles with "dog" and "cat" in the content. I've been trying to figure out how I can annotate the articles by if the word is found in the vector_column. I can not do two separate queries because, in reality, I have a lot more conditions in the query than this. The optimal output would be something like this: [ { "content": "cats", "words_found": ["cat"] }, { "content": "dogs", "words_found": ["dog"] }, { "content": "dogs and cats", "words_found": ["dog", "cat"] } ] -
Django ListView how to make query I need in class as I had it before in my function
I'm new at django and did my first project using book Eric Matthews python crash course, but now I'm trying do it better and change function that works perfectly into class, but can not get how to make it in Class the same query by filtering public and not public "topics" for users. Could somebody give me advice please how it works in classes? The function which is works perfectly and then the class I need worked like this function: def topics(request): """Provide list of topics.""" public_topics = Topic.objects.filter(public=True).order_by('date_added') if request.user.is_authenticated: private_topics = Topic.objects.filter(owner=request.user).order_by('date_added') topics = public_topics | private_topics else: topics = public_topics context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) And there is the class I need that it worked like the previous function. Could you advice what should be in queryset with public, owner and request? class TopicsHome(ListView): model = Topic template_name = 'learning_logs/topics.html' context_object_name = 'topics' def get_queryset(self): return Topic.objects.filter(public=True).order_by('date_added') -
Why do localize template tag and USE_L10N sometimes produce different results?
According to Django docs, the localize template tag allows for more fine-grained control of localization in templates than the general USE_L10N = True setting. However, turning localize on doesn't always produce the same result as setting USE_L10N = True. For example, # USE_L10N = True in settings.py {% load l10n %} {{some_datetime_value|date}} # Date is shown and localized vs # USE_L10N = False in settings.py {% load l10n %} {% localize on %} {{some_datetime_value|date}} {% endlocalize %} # Date is shown and NOT localized Why are the two results different? And is there a way to make the localize tag localize correctly in those cases? -
Django serialization get foreign key table value istead of id
recently i started on django framework and i am stuck at this situation tried reading documentation but my lack of experience i am not able understand much is there any way we can get response how we wanted with keeping django default checks,validation as much as possible. i tried using def to_representation but still it's giving me reponse as null when i debug. use case: i have mention model below i want foreign key value as text what stored in table status_lookup.name from product table class product_serializer(serializers.ModelSerializer): status = status_lookup_serializer(read_only=True,many=False) class Meta: model = product fields = ('id','name','status_id','status') model.py class status_lookup(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True) activation_date = models.DateTimeField(auto_now_add=True) deactivation_date = models.DateTimeField(blank=True,default=None) def __str__(self): return self.name class product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) img_url = models.CharField(max_length=255,blank=True) status_id = models.ForeignKey(status_lookup, related_name='status', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(blank=True) activation_date = models.DateTimeField(auto_now_add=True) deactivation_date = models.DateTimeField(blank=True,default=None) def __str__(self): return self.name o/p I want [ { "id":1, "name":"xxx", "status":pending } ] -
How to correctly use Django defer() when CONCAT to large textfield
I have a textfield with lots of data (>400000 lines of text). I think this is the reason that my server sometimes suddenly denies service when many users append new text lines. I am using so far Item.objects.filter(pk=iitem.pk).update(html=Concat("html", Value(msg))) to append a new msg. But I think the problem is that beforehand I have to check some other fields of iitem, so I do iitem = IMPALitem.objects.get(pk=p["iibox"]). Am I correctly assuming, that this is where all the data (40MB) gets unnecessarily loaded from the DB (postgres) into memory!? Is changing the get to iitem = IMPALitem.objects.get(pk=p["iibox"]).defer("html") all I need to do? (Does the defer() need to go left/in-front-of the get()?)? -
Django REST generic ListCreateView GET request is working but POST request is not working
I created a generic ListCreateAPI view. I am able to execute a GET request to the view but not a POST request. Here is my model: class InvoiceEntry(models.Model): SERVICE_OR_EXPENSE_CHOICE = [('SER', 'Service'),('EXP', 'Expense')] TYPE_CHOICE = [('BPA', 'BPA'),('CAE', 'CAE'),('MEC', 'MEC'),('TRA', 'Travel')] invoice_number = models.CharField(max_length=20) description = models.CharField(max_length=200) rate = models.FloatField() units = models.FloatField() discount = models.FloatField(default=0) amount = models.FloatField() service_or_expense = models.CharField(max_length=10, choices=SERVICE_OR_EXPENSE_CHOICE) type = models.CharField(max_length=10, choices=TYPE_CHOICE) def __str__(self): return '[' + str(self.invoice_number) + '][' + self.description + '][' + self.service_or_expense + '][' + self.type + ']' Here is my view: class InvoiceEntryListCreate(ListCreateAPIView): queryset = InvoiceEntry.objects.all() serializer_class = InvoiceEntrySerializer And here is my serializer: class InvoiceEntrySerializer(serializers.ModelSerializer): class Meta: model = InvoiceEntry fields = ['invoice_number', 'description', 'rate', 'units', 'discount', 'amount', 'service_or_expense', 'type'] I get the following error when trying a post request: { "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" } -
Cannot import name 'BlobClient' from 'azure.storage.blob. Django
Although, there are many similar questions to the one I am asking, but non of them have helped me. I am trying to store the file into my azure storage blob through directly through my system using Django. can some help me? Here is the result of pip freeze: azure-nspkg==3.0.2 azure-servicebus==0.21.1 azure-servicefabric==6.3.0.0 azure-servicemanagement-legacy==0.20.7 azure-storage-blob==1.5.0 azure-storage-common==1.4.2 azure-storage-file==1.4.0 azure-storage-queue==1.4.0 I got the following importerror: from azure.storage.blob import ( ImportError: cannot import name 'BlobClient' from 'azure.storage.blob' -
How to prevent Django TestCase creating SQL table with prefixes?
I have started building TestCase for API which used Django Rest Framework. But the moment I started, I realized the database TestCase created included prefixes in my table. I know I can change the table name to be more Django-friently but I don't think it will work with my current MySQL setup. This is the error I got. django.db.utils.ProgrammingError: (1146, "Table 'test_db.foo' doesn't exist") And when I run with --keepdb, the table it created is api_foo, where api is where the models.py is stored Is there a way to prevent Django from renaming my table name at all? -
Django reverse foreign key constraint
I have 2 models, Asset and Trade. The Trade model has Asset linked by a foreign key, which allows null values depending on the status of the Trade. An Asset always needs to be linked to a Trade by the foreign key. An Asset can have many Trades, but a Trade can only have 1 Asset. The problem is that sometimes an Asset is created without a Trade, and this needs to fail because it then causes further errors as it shouldn't be possible. How can I ensure the reverse foreign key is never null for the Asset model, but keep the on_delete parameter as SET_NULL? class Trade(models.Model): status = models.CharField(max_length=10) asset = models.ForeignKey( Asset, on_delete=models.SET_NULL, blank=True, null=True, ) class Asset(models.Model): price = models.DecimalField(max_digits=16, decimal_places=2) -
Got No such file or directory while using uWSGI
Ubuntu 20.04 Desktop, uWSGI 2.0.18-debian, Django 3.2.9, NGINX 1.18.0-0ubuntu1.2, Python 3.8.10; here is my uWSGI configuration file /etc/uwsgi/apps-enabled/mysite.ini [uwsgi] http-socket = 127.0.0.1:8081 stats = 127.0.0.1:8082 stats-http=true uid = www gid = www chmod-socket = 666 chown-socket = www chdir = /home/www/mysite home = /home/www/.python3.8_mysite pidfile = /run/uwsgi/app/mysite/pid socket = /run/uwsgi/app/mysite/socket py-tracebacker = /tmp/tbsocketmysite touch-chain-reload = /home/www/mysite/reload module = mysite.wsgi plugin = python3 master = true vacuum = false memory-report = true lazy-apps=true listen = 65535 buffer-size = 32768 workers = 1 enable-threads = true threads = 1 When i try to restart the uWSGI service: service uWSGI restart It goes wrong: Job for uwsgi.service failed because the control process exited with error code. See "systemctl status uwsgi.service" and "journalctl -xe" for details. So i go to check the uWSGI log file /var/log/uwsgi/app/mysite.log Fri Nov 26 16:17:20 2021 - *** Starting uWSGI 2.0.18-debian (64bit) on [Fri Nov 26 16:17:20 2021] *** Fri Nov 26 16:17:20 2021 - compiled with version: 10.0.1 20200405 (experimental) [master revision 0be9efad938:fcb98e4978a:705510a708d3642c9c962beb663c476167e4e8a4] on 11 April 2020 11:15:55 Fri Nov 26 16:17:20 2021 - os: Linux-5.11.0-40-generic #44~20.04.2-Ubuntu SMP Tue Oct 26 18:07:44 UTC 2021 Fri Nov 26 16:17:20 2021 - nodename: ubuntu-desktop Fri Nov 26 16:17:20 2021 - … -
How can I automatically generate a url for a specific item in Angular
For example i have different items from the database and would like to share a link that will let someone to specific item only without showing other related items, eg i have football, volleyball among others, so you are playing football, you should get a link to take you to football page to register there. -
I am trying to add many to many feild in django but getting error
models are- class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) seller=models.ForeignKey(Seller,null=True,on_delete=models.CASCADE,) category = models.ForeignKey(Category,null=True, on_delete=models.CASCADE,) description = models.CharField(max_length=200, default='' , null=True , blank=True) image = models.ImageField(upload_to='uploads/products/') rating=models.FloatField(null=True) people=models.IntegerField(default=0,null=True) customers=models.ManyToManyField(Customer,blank=True) class Customer(models.Model): user_name = models.CharField(max_length=50) phone = models.IntegerField(default='8928') email = models.EmailField() password = models.CharField(max_length=500) qq=Product.objects.get(id=8) print(qq) print(Customer.objects.all().first()) qq.customers.add(Customer.objects.all().first()) print("qq.customers is",qq.customers) """ Product object (8) Customer object (1) qq.customers is store.Customer.None""" I want to know how we can add customers in product.customers which is showing none in this problem .Please help me to solve this -
Update field on another table when add new record - django
I have a form where adding appointments. I would like to update a field in another table during submission. Let me illustrate: accounts model (Custom user model) class Account(AbstractBaseUser): patient_status = ( ('No Patient', _('No Patient')), ('New Patient', _('New Patient')), ('Patient', _('Patient')), ) first_name = models.CharField(_('First Name'), max_length=50) last_name = models.CharField(_('Last Name'), max_length=50) username = models.CharField(_('Username'), max_length=50, unique=True) ... # required is_patient = models.CharField(_('Patient'), max_length=20, choices=patient_status) ... views.py adding appointment: def add_appointment(request): form = AddAppointmentForm(request.POST or None) if request.method == 'POST': if form.is_valid(): appoint_user = form.cleaned_data.get('user') appoint_seat = form.cleaned_data.get('seat') appoint_start_appointment = form.cleaned_data.get('start_appointment') appoint_end_appointment = form.cleaned_data.get('end_appointment') # If Appointment already exist if Appointment.objects.filter(user=appoint_user, seat=appoint_seat, start_appointment=appoint_start_appointment, end_appointment=appoint_end_appointment).exists(): messages.warning(request, "This appointment already exists.") else: form.save() messages.success(request, 'Appointment was added successfully!') return redirect('appointments:add_appointment') else: form = AddAppointmentForm() I would like to update is_patient after is_valid(), something like: patient = Appointment.objects.filter(user=appoint_user).count() if patient > 0: patient.user__is_patient = 'Patient' patient.save() How can i access is_patient from Account's table in order to update and also where is the right place to put the code, in the view?