Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to develop big projects?
I just have interesting question. Is it safety to use open cource systems (CMS) and/or frameworks (any) to build an e-commerce projects like Amazon, E-bay etc to make international online-shopping? How are the big projects developing nowadays? And do you know any famous apps, web-sites, projects used only frameworks? -
Django chained foreign key forms
Apologies ahead of time if there is an easy answer to this in the docs or elsewhere, but I'm working on my first django project, I think I'm on my last big obstacle, and my eyes are bleeding from digging through examples, tutorials and docs that aren't related to what I'm trying to do. https://www.youtube.com/watch?v=NiWAiIiNYDc This video is probably the closest to what I'm trying to do, but it requires mysql stored procedures, and it seems I should be able to do this in sqlite. At a high level, here is what I want: If we have a store with multiple items, I want to categorize each item on two levels Upper_Category: name Sub_Category: name parent -- foreign key: Upper_Category So, each item would look like: Item: name description ...etc... category -- foreign key: Sub_Category Filled in, they might be: Upper_Categories-- Food Drink Dishes Sub_Categories: Meat: parent=Food ... Beer: parent=Drink It seems to me that I should be able to wrap this all into an editable formset based on 'Item' where each item includes a reference to what Upper_Category it belongs to Category | Sub-Category | Name | Description ... "Drink" | "Beer" | "Something IPA" | "beer description.." ...etc … -
Django Cant Catch error from pandas dataframe
I try to catch an error that shows in the template that said: ArrowTypeError at /user_area/absent/2840 Atlantic Ave/ ("Expected bytes, got a 'int' object", 'Conversion failed for column ZipCode with type object') Request Method: GET Request URL: http://127.0.0.1:8000/user_area/absent/2840%20Atlantic%20Ave/ Django Version: 3.2.12 Exception Type: ArrowTypeError Exception Value: ("Expected bytes, got a 'int' object", 'Conversion failed for column ZipCode with type object') Exception Location: pyarrow/error.pxi, line 122, in pyarrow.lib.check_status my code is like : try: return pd.read_feather(os.path.join(cache_folder, file)) except Exception as e: print(e) return get_api_info(request_items, url_requested, now) what I want is to as soon the ArrowTypeError comes up, the Except return get_api_info(). is there anyway way I can do that? thanks -
Forbidden (CSRF token missing or incorrect.): /audio
i have website with button to upload audio mp3 on a post. the problem, when i clicked the button, it's open new / (http://localhost:8000/audio) actually just http://localhost:8000. and when i see terimal, there's error message Forbidden (CSRF token missing or incorrect.): /audio at the same time, there's error at my website with error message Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because … -
Unable to get primary key in django model
I am trying to create an invoicing app in django class CustomerDetailsModel(models.Model): Customer_ID = models.IntegerField(unique=True,auto_created=True,primary_key=True) Civil_ID = models.CharField(max_length=50,unique=True) Customer_Name =models.CharField(max_length=200,unique=True) phone_number_1 = models.CharField(max_length=20,blank=True) phone_number_2 = models.CharField(max_length=20,blank=True,null=True) Customer_Disc = models.TextField(blank=True,null=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.Customer_Name class InvoiceModel(models.Model): Invoice_ID = models.IntegerField(unique=True,auto_created=True,primary_key=True) Customer_ID = models.ForeignKey(CustomerDetailsModel,on_delete=models.CASCADE) Civil_ID = models.IntegerField(unique=True) Customer_Name =models.CharField(max_length=200,unique=True) phone_number_1 = models.CharField(max_length=8) InvNo = models.IntegerField() Item_ID = models.IntegerField() Item_Name = models.CharField(max_length=200) Rate = models.DecimalField(max_digits=8,decimal_places=2) TotQ = models.DecimalField(max_digits=8,decimal_places=2,default=0.0) TotAmount = models.DecimalField(max_digits=8,decimal_places=2,default=0.0) Status = models.CharField(max_length=200) Date = models.DateField(auto_created=True) Month = models.CharField(max_length=3) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.BookNo) This are the the two models the I use. I had no issue creating a new customer but when it came to creating the invoice it was showing the value error for Customer_ID 'ValueError: save() prohibited to prevent data loss due to unsaved related object 'Customer_ID'.' After using breaker points in VS Code, I found out out that Customer_ID field was returning 'None'. I tried deleting the db and start over but I was still getting the same results this is the function for creating invoice def update_invoice(cid,data): inv = InvoiceModel( Customer_ID = cid, Civil_ID = cid.Civil_ID, Customer_Name =cid.Customer_Name, phone_number_1 =cid.phone_number_1, InvNo = data['incno'] … -
Connect Django with Azure postgres sql wusing managed identity in azure
How to configure Azure postgres sql database in django settings.py using Managed Identity In Azure -
Django AdminInline on many-to-many relationship
I have two models like this: class ArtCollection(models.Model): # nothing important in this case class Artwork(models.Model): ... name = models.CharField(max_length=200, null=True, blank=True) art_collections = models.ManyToManyField("ArtCollection", related_name="artworks") image = models.ImageField(...) Recently, I've change the relationship between them from FK for ArtCollection on Artwork model to m2m (as seen as above). What I would like to have now is something that I had before, particulary ArtworkInline in admin panel on ArtCollection change view (editable artwork fields like name, image change and so on). But it doesn't work. The only solution I've came across is this one (I know I should make an image preview rather than display its name - but its just an example): from inline_actions.admin import InlineActionsMixin, InlineActionsModelAdminMixin class ArtworkInline(admin.StackedInline): model = ArtCollection.artworks.through extra = 0 fields = ['artwork_image'] readonly_fields = ['artwork_image'] def artwork_image(self, instance): return instance.artwork.image artwork_image.short_description = 'artwork image' class ArtCollectionAdmin(InlineActionsModelAdminMixin, admin.ModelAdmin): ... inlines = [ArtworkInline] Is it possible to have the editable fields in m2m relationship in inline django panel? I also use grappeli and custom template for inline (which are useless after changing the relationship - they have worked pretty well with FK, now I can have only readable_fields on default template). {% extends 'admin/stacked_inline.html' %} … -
Python Django cx_Oracle stored procedure output parameter get data
I am able to successfully call the stored procedure but unable to retrieve the data in the OUT parameter. The out_var variable does not contain the result. What am I doing wrong? I have the following code in Django: def call_stored_procedure(in_var_1: int, in_var_2: str): with connections['DB_KEY'].cursor() as cursor: out_type = connections[db].connection.gettype("CUSTOM_SCHEMA.CustomTableOfType") out_var = cursor.var(out_type).var x = cursor.callproc("CUSTOM_SCHEMA.CUSTOM_PACKAGE.CustomProc", (in_var_1, in_var_2, out_var )) return x, out_var The following database settings in settings.xml DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'DB_KEY': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxxx.xxxx.xxxx:1111/XXX', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxxxx', } ] The following is the stored procedure that I call: PROCEDURE CustomProc( in_var_1 IN number, in_var_2 IN varchar2, out_var OUT CUSTOM_SCHEMA.CustomTableOfType ) IS ... BEGIN ... END The CUSTOM_SCHEMA.CustomTableOfType looks like this: TYPE CustomTableOfType AS TABLE OF CUSTOM_SCHEMA.CustomType; CUSTOM_SCHEMA.CustomType looks like this: TYPE CustomType FORCE AS OBJECT ( XXX NUMBER(6), YYY DATE, ZZZ NUMBER(3), CONSTRUCTOR FUNCTION CustomType RETURN SELF AS RESULT); The data in the out parameter is missing from the bound object. -
How to use prefetch_related in django rest api with foreying key and heritage
I am working on this Django project, it uses heritage and foreign keys for its models. These are the models: class SetorFii(models.Model): name = models.CharField(max_length=255) class Asset(models.Model): category = models.ForeignKey( Category, related_name='categories', on_delete=models.CASCADE) ticker = models.CharField(max_length=255, unique=True) price = models.FloatField() class Fii(Asset): setor_fii = models.ForeignKey( SetorFii, null=True, default=None, on_delete=models.CASCADE, related_name="setor_fiis") Class Crypto(Asset): circulating_supply = models.FloatField(default=0) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) I would like to get the field setor_fii in the PortfolioAssetSerializer, That is what I tried without success. I get this error message: Cannot find 'setor_fii' on PortfolioAsset object, 'setor_fii' is an invalid parameter to prefetch_related() Would like some help to achieve that. The serializer: class PortfolioAssetSerializer(serializers.ModelSerializer): category = serializers.CharField(source='asset.category.name') setor_fii = serializers.CharField(source='asset.setor_fii') class Meta: model = models.PortfolioAsset fields = ( 'id', 'category', 'setor_fii' ) The view class PortfolioAssetList(generics.ListAPIView): serializer_class = serializers.PortfolioAssetSerializer def get_queryset(self): return models.PortfolioAsset.objects.filter(portfolio_id=self.kwargs['pk']).prefetch_related('setor_fii') -
1054, "Unknown column" exception upon adding nonexisting field in Django 4.0
I have struck upon a problem of adding additional field. I want it to be boolean, but it doesn't actually matter which type the field will be, because I also tried to create an integer field instead of boolean with getting the same exception. The exception I get is: django.db.utils.OperationalError: (1054, "Unknown column 'salary_profile.confirmation_link_sent' in 'field list'") And here is the model I am talking about with the field already added in the last line: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) birth_date = models.DateField(null=True) employment_date = models.DateField(null=True) position = models.ForeignKey('Position', on_delete=models.PROTECT, null=True) attestation_date = models.DateField(blank=True, null=True) dismiss_date = models.DateField(blank=True, null=True) photo = models.ImageField(blank=True, null=True, upload_to=user_directory_path) email_is_confirmed = models.BooleanField(default=False) confirmation_link_sent = models.BooleanField(default=False) This problem encountered both in sqlite and mysql. So far the only answers to the problem I found on the internet were "to delete the whole base and start again", which to put it lightly - ridiculous, but also adding this field manually in the database itself. But I hardly see it as a solution because imagine I have to add 20 of such fields tomorrow, I will have to do those manual additions as well? And I must add that many answers are getting back to django … -
TypeError:unsupported format string passed to Series.__format__
I am trying to print time in 12 hour clock format but django throws TypeError. works fine for python but shows error in django Thanks is Advance def solve(s, n): h, m = map(int, s[:-2].split(':')) h =h% 12 if s[-2:] == 'pm': h =h+ 12 t = h * 60 + m + n h, m = divmod(t, 60) h =h% 24 if h < 12: suffix = 'a' else: suffix='p' h =h% 12 if h == 0: h = 12 return "{:02d}:{:02d}{}m".format(h, m, suffix)``` -
how to get response with message,error, status in django rest framework
HI Everyone i am creating api using drf but i want response with different formet, below i have mention my current response and expected response.how can achieve me my expected api response formet. views.py class TeamlistViewset(viewsets.ViewSet): def list (self,request): team=Team.objects.all() serializer=TeamSerializer(team,many=True) return Response(serializer.data) api response [ { "id": 1, "name": "Deadly Shark" } ] expected api response { "message": "list retrieval", "error": false, "code": 200, "results": { "totalItems": 1, "pageData": [ { "id": 1, "name": "Deadly Shark" } ], "totalPages": null, "currentPage": 0 } } -
python manage.py makemigrations says table already exists in Django project
I am trying to get a coworker of mine up and running with a project I have already created. When we try to run the server it says one of the tables already exists. We googled it and tried to makemigrations and migrate --fake from posts like this Django : Table doesn't exist but still get the same result. Deleting the tables in the database isn't an option because its connecting to some production data. How can I get around this? The traceback is below. Traceback (most recent call last): File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'xpotoolsdb.xpotoolshome_site' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line … -
django authentication check.password doesn't work
check.password doesn't work and this is the error message : Internal Server Error: /api/login Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python310\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Python310\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Python310\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Python310\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\test\auth\users\views.py", line 24, in post if not user.check_password(password): File "C:\Python310\lib\site-packages\django\contrib\auth\base_user.py", line 115, in check_password return check_password(raw_password, self.password, setter) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 55, in check_password must_update = hasher_changed or preferred.must_update(encoded) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 332, in must_update decoded = self.decode(encoded) File "C:\Python310\lib\site-packages\django\contrib\auth\hashers.py", line 308, in decode algorithm, iterations, salt, hash = encoded.split("$", 3) ValueError: not enough values to unpack (expected 4, got 3) [10/May/2022 18:10:48] "POST /api/login HTTP/1.1" 500 101753 this is the views: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from .serializers import UserSerializer from .models import User class RegisterView(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class LoginView(APIView): … -
Is there a way to get if the user is on a particular heading, paragraph or a div etc
I was trying to find a way to start an animation only if the user is on it, at first I tried getting screen size, and its works. Once I was googling I found something where we could get ID (by the ID tag) while scrolling, if somehow I could get the ID while scrolling down, I could use a simple JavaScript function to play the animation. is there any way? -
request.COOKIES is empty when Django Rest Framework API hit from React JS but works in Postman
I have implemented JWT Authentication in Django Rest Framework and using React JS as frontend. The issue is, When i test my API in Postman everything works. I send email and password to /login, it returns jwt token and set_cookies with http_only = True, UserView simple fetches that jwt token form cookies and returns the user. See the image of working backend. JWT token returned and COOKIE is set. And userview gives the User back as shown in image... But when i call this API into React JS, The Login Works but UserView doesn't get any Token hence gives error 401. Why this happening? Please see my code -
AWS Beanstalk Django Web App not serving static files when using CLI - Works fine using AWS Console UI
I am trying to use AWS Beanstalk CLI to deploy a Django web application using the command line but I am not able to serve properly the static files. This is my configuration file (.elasticbeanstalk/config.yml): branch-defaults: aws-cli: environment: gather-api-environment group_suffix: null environment-defaults: gather-api-environment: branch: null repository: null global: application_name: gather-api-application branch: null default_ec2_keyname: beanstalk default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: eu-central-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: DataArchitect repository: null sc: git workspace_type: Application option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cdm_api.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: /static/ packages: yum: postgresql-devel: [] However, when I load this folder as a zip file using the AWS UI console ("Upload and deploy button"), it works. Here is my .ebextensions/django.config file: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cdm_api.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: /static/ Any suggestions? Let me know if more information is needed. Thanks in advance! -
re-write a function-based view to a class-based view
I am trying to re-write my Django Application, so it is using the Django Rest Framework, but I need a little help to understand how I re-write a post view function to a class-based view. first a have the function-based view I would like to re-write: def make_transfer(request): assert not request.user.is_staff, 'Staff user routing customer view.' if request.method == 'POST': form = TransferForm(request.POST) form.fields['debit_account'].queryset = request.user.customer.accounts if form.is_valid(): amount = form.cleaned_data['amount'] debit_account = Account.objects.get(pk=form.cleaned_data['debit_account'].pk) debit_text = form.cleaned_data['debit_text'] credit_account = Account.objects.get(pk=form.cleaned_data['credit_account']) credit_text = form.cleaned_data['credit_text'] try: transfer = Ledger.transfer(amount, debit_account, debit_text, credit_account, credit_text) return transaction_details(request, transfer) except InsufficientFunds: context = { 'title': 'Transfer Error', 'error': 'Insufficient funds for transfer.' } return render(request, 'BankApp/error.html', context) else: form = TransferForm() form.fields['debit_account'].queryset = request.user.customer.accounts context = { 'form': form, } return render(request, 'BankApp/make_transfer.html', context) The TransferForm look like this: class TransferForm(forms.Form): amount = forms.DecimalField(label='Amount', max_digits=10) debit_account = forms.ModelChoiceField(label='Debit Account', queryset=Customer.objects.none()) debit_text = forms.CharField(label='Debit Account Text', max_length=25) credit_account = forms.IntegerField(label='Credit Account Number') credit_text = forms.CharField(label='Credit Account Text', max_length=25) def clean(self): super().clean() # Ensure credit account exist credit_account = self.cleaned_data.get('credit_account') try: Account.objects.get(pk=credit_account) except ObjectDoesNotExist: self._errors['credit_account'] = self.error_class(['Credit account does not exist.']) # Ensure positive amount if self.cleaned_data.get('amount') < 0: self._errors['amount'] = self.error_class(['Amount must be positive.']) return self.cleaned_data … -
How to use fcm-django?
I'm just new in django-fcm. Can anyone give a step by step how to setup django-fcm package ? I want to push notification to web browser, when user allow notification from my website. Thank You -
How to send list of dictionaries on Httpresponse back to ajax client and unpack the lot received
I want to send a List of dictionaries from Httpresponse in Json back to the ajax and from there unravel the pack so that I can produce a list of tables. I have the code to send for 1 dictionary as well as to unravel one dictionary And to produce One table. Since I need to produce several tables (one for each model, I don't know what the syntax is for unpacking the list of dictionaries received in json format. Once I have them unpacked, I already know how to make a table out of one in Javascript. For 1 dictionary and 1 table I do like this: dictionary = { "key1": "value1", "key2": "value2" } json_dict = json.dumps(dictionary) return HttpResponse(json_dict) and then unpack like this: . ... .... datatype:'json' }).done(function(data) { obj = JSON.parse( data); How can I get obj1, obj2, obj3 etc (corresponding each to a dictionary, a model and will become a table) -
Django didn't create table fields in MySQL
I'm working on a blog project. There is an app called "blog" with one single model. The code of the models.py is below: from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Articles(models.Model): title = models.CharField(max_length=200), author = models.ForeignKey(User, on_delete=models.CASCADE), text = models.TextField(), created_date = models.DateTimeField(timezone.now), published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title I added the app to the INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] Still, Django only created the id field (created automatically) and the published_date field. This never happened before. Any idea about what's the problem here? -
Django: Crispy forms on django-filters removes selected on drop-down lists
Why does | crispy remove the selected attribute on drop-down lists of my filters? It does not show the currently applied filter. Given the following filter.py: from .models import Task import django_filters class TaskFilter(django_filters.FilterSet): class Meta: model = Task fields = ["status"] I'm calling the following URL: http://localhost:8000/task/?status=30 With {{ filter.form }} is generated the following output: <select name="status" id="id_status"> <option value="" >---------</option> <option value="10" >Overdue</option> <option value="20" >Due</option> <option value="30" selected>Pending</option> <option value="40" >Inactive</option> </select> ... With {{ filter.form | crispy }} is generated the following output, which is missing the selected value: <select class="bg-white ..." name="status" > <option value="" >---------</option> <option value="10" >Overdue</option> <option value="20" >Due</option> <option value="30" >Pending</option> <option value="40" >Inactive</option> </select> Any idea why the selected is no longer in place and the id="id_status" is gone? -
How to save ProductAttributesvAlues in Django Oscar Commerce
I'm trying to save m2m relation in Product model on Django Oscar Commerce package, the model has an many to many relation through the ProductAttributeValues model. Making Postan POST method query to url 127.0.0.1:8000/api/products/1/update/ serializers.py: class ProductAttributeValueSerializer(OscarModelSerializer): class Meta: model = ProductAttributeValue fields = '__all__' class ProductSerializer(OscarModelSerializer): attributes = ProductAttributeValueSerializer(many=True, read_only=False) class Meta: model = catalogue_models.Product fields = '__all__' The json content: { 'title': 'Producto 4', 'is_public': True, 'description': 'descripción', 'attributes': [ {'value_text': 'contenido', 'attribute': 1, 'product': 1}, {'value_text': 'contenido', 'attribute': 2, 'product': 1} ] } Anybody could help me please ? Thanks in advance. -
ArangoDB query find name consisting of two or more parts
i am quite new to arangodb and AQL. What i am trying to do is to find names and surnames with query that have two or more parts that may or may not include spaces (" ") to divide those said parts. As i went through documents, I figured that those fileds should be indexed as full-text indexes and query would be something like FOR u IN FULLTEXT(collection, field, "search") RETURN u Now my question is how to utilize the above query for a Persian/Arabic names such as سید امیر حسین Keep in mind that this name comes from an input of a user and it could be in the following formats such as سید امیر حسین/سید امیرحسین/سیدامیر حسین/سیدامیرحسین Note the various types of names with/without spaces. I tried the follwoing query F FOR u IN FULLTEXT(collection, field, "سید,|امیر,|حسین,|سیدامیرحسین") RETURN u But the problem is this will also result of fetching the name because i reckon the use of OR ( | ) operator. سید محمد which is not my intention. So what am i doing wrong or missing here ? Many thanks in advance and excuse my noobiness PS : arango 3.8.3 -
How to add two foreign keys in message table of same(user) table as foreign keys?
I am trying to design a chatting app using Django rest at the backend My Model class MessageModel(models.Model): message = models.CharField(max_length=200) msg_from = models.ForeignKey(UserModel,on_delete=models.CASCADE) msg_to = models.ForeignKey(UserModel,on_delete=models.CASCADE) but it gives the following error SystemCheckError: System check identified some issues: ERRORS: message_api.MessageModel.msg_from: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_from' clashes with reverse accessor for 'message_api.MessageModel.msg_to'. HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_from' or 'message_api.MessageModel.msg_to'. message_api.MessageModel.msg_to: (fields.E304) Reverse accessor for 'message_api.MessageModel.msg_to' clashes with reverse accessor for 'message_api.MessageModel.msg_from'. HINT: Add or change a related_name argument to the definition for 'message_api.MessageModel.msg_to' or 'message_api.MessageModel.msg_from'. How can I design a database table for chatting? I am using MySQL database.