Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate Django Data query according to date
This is my models.py file. class CustomerInfo(models.Model): customer_name=models.CharField('Customer Name', max_length=50) customer_mobile_no = models.CharField('Mobile No', null=True, blank=True,max_length=12) customer_price=models.IntegerField('Customer Price') customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10) customer_sell_date = models.DateTimeField('date-published') customer_product_id=models.CharField('Product ID',max_length=150,null=True, blank=True) customer_product_name=models.CharField('Product Name', max_length=50) def __str__(self): return self.customer_name When I find data query information by date, I want to calculate "customer_price" by only selected date. Then I will show to my HTML page. This is my search query by date. customers = CustomerInfo.objects.filter(customer_sell_date__day=datelist) Now, Calculate all ""customer_price"" within my selected date. -
Heroku sais: "Requested setting LOGGING_CONFIG" but it is set?
I'm trying to setup a Django site on Heroku. I get this error message: 2017-10-07T21:03:33.416585+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. But if I run Heroku config, the var is set. Why is it not recognized? === dagenssalg Config Vars DISABLE_COLLECTSTATIC: 0 LOGGING_CONFIG: off Many answers in here mention the wsgi.py file, but I can't see anything wrong with that: import os from django.core.wsgi import get_wsgi_application from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) os.environ.setdefault("DJANGO_SETTINGS_MODULE","dagenssalg.settings") application = get_wsgi_application() Any help is most appreciated. Best regards Kresten -
Filter objects by exact position of character through a variable
code: 1)CSE-101 2)CSE-102 3)CSE-101 4)CSE-204 5)CSE-106 6)CSE-201 position: 012345678 i want to make a search for the value which is stored in variable . suppose,I want' to make a search for all the codes with 2 at position 4. So the search should return the 4th and 6th code. I've looked at django look_up functions. Is there a way to make a search like this? this is correct regular expression for desired output,in the case of direct use of numerical number 2. Model.objects.filter(code__regex=r'^.{4}2') but i want make a regular expression like that .suppose s=2, then i want to include s with this regular expression. -
how to solve django social auth error on facebook?
i installed social-auth-app-django and followed the guide here to integrate facebook login to django 1.8.18 .The problem is when i go to "http://localhost:8000/social-auth/login/facebook/" I get below error Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Here is my settings.py file # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print (BASE_DIR) SECRET_KEY = 'x220#z=kwd)kjiu#u+p$)v0lu+rspyosg+)l*k$ux9j)1h' DEBUG = True ALLOWED_HOSTS = ['localhost'] INSTALLED_APPS = ( ... 'account', 'social_django', #social classes ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) ROOT_URLCONF = 'bookmark.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', # <-- ], }, }, ] WSGI_APPLICATION = 'bookmark.wsgi.application' STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') from django.core.urlresolvers import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_URL = reverse_lazy('logout') AUTHENTICATION_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', #< --facebook 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', ) SOCIAL_AUTH_FACEBOOK_KEY='1742581762468139' SOCIAL_AUTH_FACEBOOK_SECRET='eae7dsfdsfdsf90b219becb84' urls.py file from django.conf.urls import include, url from django.contrib import admin from django.conf import … -
Using another apps model as Foreign Key
The error I'm getting. insert or update on table "soccer_game" violates foreign key constraint "soccer_game_match_id_7834e80f_fk_soccer_match_id" DETAIL: Key (match_id)=(6) is not present in table "soccer_match". I have an app for creating matches called home. It has a Match model in it. # home.models.py from django.db import models class Match(models.Model): pick = models.CharField(max_length=30, choices=GAMES) name = models.CharField(max_length=30) created = models.DateTimeField(auto_now_add=True) players = models.IntegerField(choices=NUM_PLAYERS) def __str__(self): return self.name class Meta: verbose_name_plural = "matches" The GAMES choices is a list of all the other sport/game apps. One of them is soccer which has these models. # soccer.models.py from django.conf import settings from django.db import models from home.models import Match class Player(models.Model): name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number = models.IntegerField(default=0) score = models.IntegerField(default=0) def __str__(self): return self.name.username class Settings(models.Model): match = models.ForeignKey('home.Match') time = models.IntegerField(default=0) class Meta: verbose_name_plural = 'settings' def __str__(self): return self.match.name class Game(models.Model): match = models.ForeignKey('home.Match') player = models.ForeignKey(Player) def __str__(self): return self.match.name Then in the home app the view to create a match. # home.views.py from .forms import MatchForm from home.models import Match from soccer.models import Game, Player, Settings # Create your views here. @login_required def create_match(request): form = MatchForm(request.POST or None) context = { 'form': form, } if request.method == 'POST': … -
Fail to create a superuser in django, when use a router
I tring to create mongodb/mysql project on Djago 1.11.4 with python3. I intended to use mysql for user authentification and mongodb for all other purposes. I master to create a users but failed in creating a superuser. Here is what happend, when I tried to create a superuser: $ python3 manage.py createsuperuser username=Admin System check identified some issues: WARNINGS: ?: (urls.W001) Your URL pattern '^$' uses include with a regex ending with a '$'. Remove the dollar from the regex to avoid problems including URLs. Email address: admin@example.com Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 170, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 153, in _create_user user.save(using=self._db) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 834, in save_base with transaction.atomic(using=using, savepoint=False): File "/usr/local/lib/python3.5/dist-packages/django/db/transaction.py", line 158, … -
Django include - render content inside block
How can I render contents of header-actions block in page.html to master template. Currently, the block isn't rendered. header.html <header> {% block header-actions %}{% endblock %} </header> master.html <html> <body> {% include 'header.html' %} Some content </body> </html> page.html {% extends 'master.html' %} {% block header-actions %} Extra action {% endblock %} -
Consume kafka messages from django app
I'm designing a django based web application capable of serving via Web sockets data that need to be consumed from Kafka topic. At this time, I came up with a solution splitted in two components: one component which consumes from kafka, perform some basic operations over retrieved data, and send the result to the django app using an http request. After request have been received, a message is written over a specific django channel. Is there a better architecture to address this kind of scenario? Should I enclose all the Kafka part in a "while True" loop in a celery async task? Should I spawn a new process when django starts? If so, can I still use the django signals to send the data via web socket? Thanks, Fb -
Setting up sockets on Django
Have a django project with django-channels (using redis) allows uset to start background process and should get back a live feed of this on the page. Here's a recording of this: https://youtu.be/eKUw5QyqRcs Sockets disconnects with a 404. Here's the socket's code: $('.test-parse').unbind().click(function() { ... $.ajax({ url: "/start-render-part", type: "POST", dataType: 'json', beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, data: JSON.stringify(data), success: function(response){ if (response['status'] == 'ok') { if (response['unique-id']) { unique_processing_id = response['unique-id']; } if (response['task_id']) { task_id = response['task_id']; } var add_to_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'task_id': task_id, 'command': 'add_to_group', }); var socket = new WebSocket("ws://{HOST}/render-part/".replace('{HOST}', window.location.host)); socket.onopen = function() { console.log('opened'); var add_to_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'task_id': task_id, 'command': 'add_to_group', }); socket.send(add_to_group_msg); var get_status_msg = JSON.stringify({ 'task_id': task_id, 'unique_processing_id': unique_processing_id, 'command': 'check_status', }); socket.send(get_status_msg); }; socket.onmessage = function(event) { console.log("onmessage. Data: " + event.data); var data = JSON.parse(event.data); if (data.state == 'PROGRESS') { console.log(data.status); update_progress(data.current); } else if (data.state == 'FINISHED') { var remove_from_group_msg = JSON.stringify({ 'unique_processing_id': unique_processing_id, 'command': 'remove_from_group', }); socket.send(remove_from_group_msg); unique_processing_id = … -
SECURE_SSL_REDIRECT in Django forwarding traffic to localhost
I have introduced SSL in my website, and I need make redirection from HTTP to HTTPS. I have website on Django 1.4.5. I have installed djangosecure package using pip and added to settings.py MIDDLEWARE_CLASSES = ( ...., 'djangosecure.middleware.SecurityMiddleware', ) INSTALLED_APPS = ( .... 'djangosecure', ) SECURE_SSL_REDIRECT = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') ALLOWED_HOSTS = ['*'] but now when when I'm trying open website I have redirection to https://127.0.0.1:8756 instead of my domain with https. -
DRF view returns Invalid username/password with @permission_classes((AllowAny, ))
So I have this method-like api view with AllowAny as permisson class decorator: @api_view(['POST']) @permission_classes((AllowAny, )) But when I reach with the browser to the url it renders the DRF api template with a 403 HTTP 403 Forbidden Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Invalid username/password." } What I am missing? I dont need to specify a setting DEFAULT_PERMISSION_CLASSES if I am forcing one through the decorator right? -
Heroku Deployment Issue - Python version
I have been working on a Django project that I am trying to deploy to Heroku. I've followed a tutorial from Python Crash Course. When I enter git push heroku master, I get the following as a response: Counting objects: 73, done. Delta compression using up to 4 threads. Compressing objects: 100% (65/65), done. Writing objects: 100% (73/73), 26.20 KiB | 0 bytes/s, done. Total 73 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.2 (you are using Python-2.7.12, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.2). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing Python-2.7.12 remote: ! Requested runtime (Python-2.7.12) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fathomless-scrubland-11916. remote: When I Python --version the cmd line returns 2.7.14 which is the most up-to-date version. I feel like this error is telling me I need to use Python3 but their site says that 2.7.14 is … -
Holoview chart won't appear in Django site
i know there is probably something simple i am doing wrong, but i don't know where else to get an answer. I created a django site and the following function returns holoview html: from django.shortcuts import render from django.http import HttpResponseRedirect from charts.models import Ord from IPython.display import display_html import pandas as pd import holoviews as hv hv.extension('bokeh') renderer = hv.renderer('bokeh') # Create your views here. def displayChart(request): df = pd.DataFrame(list(Ord.objects.using('DB').all().values('ordtyp')[:500])) df = df.groupby([df.ordtyp]).size().reset_index(name='counts') bars = hv.Bars(df, kdims=[('ordtyp', 'Order Type')], vdims=[('counts', 'Count of Orders')]) hv.Store.registry['bokeh'][hv.Bars] html = renderer.html(bars) return render(request, 'charts/charts.html', {'html': html}) i put a block in the charts.html file as: {{ html |safe }} and all i get is a blank page. i then took the raw html that the renderer is returning and tried to copy and paste it directly into my html file, and got the same thing. the html is below. Also, the chart does work in Jupyter Notebook... can you tell me what i am doing wrong? charts.html: > <!DOCTYPE html> > <html> > <head> > <title>Charts</title> > </head> > <body> > {{html|safe}} > </body> > </html> raw html that the renderer returned: <div style='display: table; margin: 0 auto;'> <div class="bk-root"> <div class="bk-plotdiv" id="0dd69ef6-4d30-48f5-a95a-1201437920de"></div> … -
Load Content automatically in Django app
I'm working on a Django (1.10 & Python3) project in which I need to implement a logic as: We have articles from various categories, the user needs to tag these articles, mean when user read articles then he needs to provide his feedback rather it's relevant or irrelevant to his situation. We have to provide user's a list of categories when user select a category then all of the articles from that particular category will be available one by one to the user, mean it will show the first article to the user, when he tagged this article it will load next article automatically and also keep the user's tagging info because it's not necessary to tag all articles at once, user can tag few at a time when he can start from where has was stopped again. In simple: Would it be possible to send the user straight from their choice of a Category to the "Article Tagging" page with the next article to be tagged automatically loaded up and ready to be tagged, and the system keeps track of what the next article is that needs to be tagged? How can I accomplish this bit of functionality in … -
django admin listfilter dropdown
I'm currently trying to implement dropdown list filters in my django app but somehow can't get it to work. Tried at first with the diy approach but decided to try the django-admin-list-filter-dropdown app but still no succes settings.py INSTALLED_APPS = [ ... 'django_admin_listfilter_dropdown', ... ] admin.py from django_admin_listfilter_dropdown.filters import DropdownFilter, RelatedDropdownFilter @admin.register(models.Project) class ProjectAdmin(admin.ModelAdmin): list_display = ( "name", "entry_date", ) list_filter = ( ("name", DropdownFilter), "entry_date", ) Any suggestions? Thanks in advance -
Django Main Page Not Loading in IE
Recently discovered my Django site will not load in IE. It is only the index page. I can browse every other page without issue. Chrome and Firefox load the site without issue. When in IE, visiting the main page prompts a download with a random file name which contains the rendered html code. -
Django + Arduino
I am trying to build a project that involves Arduino, GSM module and Django. If someone texts the number of the sim in the GSM module, I want to see it in my local web app(Django) and be able to reply to the sender's number using the web app. Is there any way that my GSM module connected on Arduino can connect/communicate with my Django project? Any Advice or Suggestions will be greatly appreciated. -
Javascript go to Django URL without redirecting the user
i created a upvote button in my blog, that send the user to a url then redirect the user to the previous page but i want to know if i can do this without redirecting the user in javascript i mean without using the a tag but using 'onClick' the button: <a href="{% url 'upvote' Post.id %}"><button>upvote</button></a> my view: def upvote(request, post_id): post = Post.objects.get(id=post_id) post.votes += 1 post.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
How to detect if CloudinaryField in django model is empty in template
picture = CloudinaryField('image', blank = True, null = True) I have the above line in my django models file. And I am rendering the picture in my template with the cloudinary tag {% cloudinary "filename" %} But in cases where the model objects don't contain the picture, I want to forgo the template tag. Right now, my template renders a empty image if the model instance doesn't have a picture. How can I detect if the model instance contains a picture, so that I can render it selectively using the ` {% if condition %} -
setting Primary key in Django model
I have changed primary key in my model class lab(models.Model): IP = models.CharField(max_length=250 , primary_key = True) PingStatus = models.CharField(max_length=250) SSHConnectivity = models.CharField(max_length=250) SSHLogin = models.CharField(max_length=250) DeviceType = models.CharField(max_length=250) DeviceVersion = models.CharField(max_length=500) I am trying to make two entries by assigning two different "IP" values for lab object. But somehow only one object is there in model >>> a=lab(IP="1.2.3.4") >>> a=lab(PingStatus="1.2.3.4") >>> a=lab(SSHConnectivity="1.2.3.4") >>> a=lab(SSHLogin="1.2.3.4") >>> a=lab(DeviceType="1.2.3.4") >>> a=lab(DeviceVersion="1.2.3.4") >>> a.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> a=lab(IP="1.2.3.5") >>> a=lab(PingStatus="1.2.3.4") >>> a=lab(SSHConnectivity="1.2.3.4") >>> a=lab(SSHLogin="1.2.3.4") >>> a=lab(DeviceType="1.2.3.4") >>> a=lab(DeviceVersion="1.2.3.4") >>> a.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> b=lab(IP="1.2.3.5") >>> b=lab(PingStatus="1.2.3.4") >>> b=lab(SSHConnectivity="1.2.3.4") >>> >>> b=lab(SSHLogin="1.2.3.4") >>> b=lab(DeviceType="1.2.3.4") >>> b=lab(DeviceVersion="1.2.3.4") >>> b.save() >>> lab.objects.all() <QuerySet [<lab: lab object>]> >>> Can someone check ? Am I missing something here ? -
django - split project to two servers (due to Cloudflare) without duplicating code
I currently have a Django project running on a server behind Cloudflare. However, a number of the apps contain functionality that requires synchronizing data with certain web services. This is a security risk, because these web services may reveal the IP address of my server. Therefore I need a solution to prevent this. So far I came up two alternatives: using a proxy or splitting the project to two servers. One server responsible for responding to requests through Cloudflare and one server responsible for synchronizing data with other web services. The IP address of the latter server will be exposed to the public, however attacks on this server will not cause the website to be offline. I prefer the second solution, because this will also split the load between two servers. The problem is that I do not know how I should do this with Django without duplicating code. I know I can re-use apps, but for most of them counts that I, for instance, only need the models and the serializers and not the views etc. How should I solve this? What is the best approach to take? In addition, what is an appropriate naming for the two servers? … -
How to implement the Django's server to listen to POST requests from Webhook? I am using NGROK to expose my localhost to the Internet
I have already created a Webhook in my Github repository. I have set my payload URL to: localhost:4567/payload As I am using my localhost, I need to expose it to the Internet. For this purpose, I am using ngrok and I have also executed this command: ./ngrok http 4567 I am following all the steps written in this link to create a successful webhook for receiving notification whenever any action on commits is done in the repository. Link => https://developer.github.com/webhooks/configuring/ I am using Django framework to receive POST requests from the Webhook. However, in the tutorial given in above link, they have used Sinatra (to create web application in Ruby). I am not familiar with Ruby. I wish to continue working in Django, so could you please help me how can I use Django's server to listen to POST requests from Webhook? By far what I have done, I have got following error in my Webhook. Error in my Webhook -
How do I obtain user fields from Facebook login
I'm busy implementing Facebook login for my django site. I'm not sure if I'm on the right track or way off the ball at the moment. I have implemented the full code as seen in the FB doc example https://developers.facebook.com/docs/facebook-login/web. Basically inserted script on the template. I have the button and once logging in I have the "Welcome fetching your information" "successful login for Joshua Raphael" in my console.log. How do I now obtain the required email, username and profile pic? Is it a part of the response object? Also if I have email login, is it possible to obtain the response email and check my current database to see if the user is already registered? Prefer not to use pre-made django apps but if you highly recommend one I may try it.Thanks -
loose data in disabled form fields or template fields after raisevalidationerror
i have disabled fields in django forms. when the form gets raisevalidationerror these fields are emptied. i used template (html) fields instead of disabled form fields but they are also emptied... how can i solve it, how can i send data to template fields or disabled form fields after raisevalidationerror.... view.... else: # for GET ....form is intialized deneme_1 = obje.id deneme_2 = obje.demirbasadi deneme_3 = obje.proje form = HareketForm() form.fields["hidd_proje"].initial = obje.proje form.fields["dem_id"].initial = obje.id form.fields["dem_adi"].initial = obje.demirbasadi form.fields["dem_proj"].initial = obje.proje return render(request, 'giris/hareket_yarat.html', {'form': form, 'deneme_1': deneme_1, 'deneme_2': deneme_2, 'deneme_3': deneme_3}) form.... class HareketForm(forms.Form): dem_id = forms.IntegerField(label='Demirbaş id....:', disabled=True, required=False ) dem_adi = forms.CharField(label='Demirbaş adı....:', disabled=True, required=False) dem_proj = forms.CharField(label='Mevcut proje....:', ) har_tipi = forms.ChoiceField(label='Hareket tipi........:', widget=forms.Select, choices=TIPI,) sonraki_proj = forms.ModelChoiceField(label='Sonraki proje.......:', queryset=proje.objects.all()) aciklama = forms.CharField(label='Açıklama', widget=forms.Textarea(attrs={'cols': 50, 'rows': 8}),) hidd_proje = forms.CharField(required=False, widget=forms.HiddenInput()) def clean(self): cleaned_data = super(HareketForm, self).clean() cc_dem_id = self.cleaned_data.get("dem_id") cc_dem_adi = self.cleaned_data.get("dem_adi") cc_dem_proje = self.cleaned_data.get("dem_proje") cc_hidd_proje = self.cleaned_data.get("hidd_proje") cc_har_tipi = cleaned_data.get("har_tipi") cc_sonraki_proj = cleaned_data.get("sonraki_proj") cc_aciklama = cleaned_data.get("aciklama") a = str(cc_sonraki_proj) if (cc_hidd_proje == a): raise forms.ValidationError(" two projects can not be the same.... ", ) -
Django-rest-framework and unique_together
I am writing and API, and due to the fact that it is based on the microservice architecture, and components run asynchronously, I cannot return an object id when the client creates an object. Some time later the client may wish to update the object, however, they don't know the id/pk. That said, there are several fields with the unique_together constraint on them. My initial idea was to override the create method and compare these fields on the objects that I receive with the ones in my DB, and, if I find any, update them, if I don't — create the object. However, that fails because the validation is run before the create method, and the validation fails for the "update" objects, because they break the unique_together constraint. I can't use those unique fields as a compound primary key for the table, because Django does not support that. Is there a way I can get a validated serializer to do the logic I described above, or is there a better way? (I am also thinking of trying to create and updating in except, but so far it looks a but cumbersome.