Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: custom decorator: session or redirect
I have the following function view and I want to add a parameter, that redirects the user to another page if request.session.get('order_reference')is empty. Similar to the @login_required Anyone who can help me with that? def checkout_page(request): session_order_reference = request.session.get('order_reference') -
Django - formating/accessing a Pandas.to_dict() dataframe in a Template
I would like to highly customize a dataframe generated by Pandas in a Django view/template. I'm able to generate the dictionary that I would like to render, but accessing the elements using template tags has proven difficult. Here is an example of the dictionary: df_dict = { ('Key1', 'Key2'): { 'Line 1': '', 'Line 2': '', 'Line 3': 53000.0, 'Line 4': -120000.0, 'Line 5': 45000.0 }, ('Key3', 'Key2'): { 'Line 1': '', 'Line 2': 100.0, 'Line 3': '', 'Line 4': '', 'Line 5': '' }, ('Key4', 'Key2'): { 'Line 1': 1000.0, 'Line 2': '', 'Line 3': 2000.0, 'Line 4': '', 'Line 5': '' } } My desired template output (without regard to css formatting) is: Key1 Key3 Key4 Key2 Key2 Key2 Line 1 1000 Line 2 100 Line 3 53000 2000 Line 4 -120000 Line 5 45000 I've tired a simple template tag to iterate over the dictionary like this: {% for key, value in object %} <li>{{key}} : {{value}}</li> {% endfor %} but it only provides for: Key1 : Key2 Key3 : Key2 Key4 : Key2 I can't figure out how to get into the dictionary that is the value for the above key pairs. I've also worked through … -
Selenium chromedriver not working in production environment
I have a problem with selenium chromedriver which I cannot figure out what's causing it. Some weeks ago everything was working OK, and suddenly this error started to show up. The problem is coming from the following function. def login_(browser): try: browser.get("some_url") # user credentials user = browser.find_element_by_xpath('//*[@id="username"]') user.send_keys(config('user')) password = browser.find_element_by_xpath('//*[@id="password"]') password.send_keys(config('pass')) login = browser.find_element_by_xpath('/html/body/div[1]/div/button') login.send_keys("\n") time.sleep(1) sidebar = browser.find_element_by_xpath('//*[@id="sidebar"]/ul/li[1]/a') sidebar.send_keys("\n") app_submit = browser.find_element_by_xpath('//*[@id="sidebar"]/ul/li[1]/ul/li[1]/a') app_submit.send_keys("\n") except TimeoutException or NoSuchElementException: raise LoginException This function works with no problem in the development environment (macOS 10.11), but throws the following error in the production environment: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="sidebar"]/ul/li[1]/a"} (Session info: headless chrome=67.0.3396.79) (Driver info: chromedriver=2.40.565383 (76257d1ab79276b2d53ee97XXX),platform=Linux 4.4.0-116-generic x86_64) I already updated both Chrome and chromedriver (v67 & 2.40, respectively) in each environment. I also gave it more time.sleep(15). But the problem persists. My latest guess is that maybe the initialization of the webdriver is not working properly: def initiate_webdriver(): option = webdriver.ChromeOptions() option.binary_location = config('GOOGLE_CHROME_BIN') option.add_argument('--disable-gpu') option.add_argument('window-size=1600,900') option.add_argument('--no-sandbox') if not config('DEBUG', cast=bool): display = Display(visible=0, size=(1600, 900)) display.start() option.add_argument("--headless") else: option.add_argument("--incognito") return webdriver.Chrome(executable_path=config('CHROMEDRIVER_PATH'), chrome_options=option) Because, if the Display is not working, then there may not be the mentioned sidebar but some other button. So my questions … -
Pyinstaller with pyodbc and SQL server
I'm using Python 3.6 with Django 1.11. I've managed to get all of my modules installed using Pyinstaller, but i'm having an issue with pyodbc with SQL server. I get the following error message when attempting to runserver. Traceback (most recent call last): File "site-packages\django\utils\autoreload.py", line 228, in wrapper File "site-packages\django\core\management\commands\runserver.py", line 117, in inner_run File "site-packages\django\utils\autoreload.py", line 251, in raise_last_exception File "site-packages\django\utils\six.py", line 685, in reraise File "site-packages\django\utils\autoreload.py", line 228, in wrapper File "site-packages\django\__init__.py", line 27, in setup File "site-packages\django\apps\registry.py", line 108, in populate File "site-packages\django\apps\config.py", line 202, in import_models File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "c:\users\hfa9592\appdata\local\programs\python\python36\lib\site-packages\PyInstalle exec(bytecode, module.__dict__) File "site-packages\django\contrib\auth\models.py", line 4, in <module> File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "c:\users\hfa9592\appdata\local\programs\python\python36\lib\site-packages\PyInstalle exec(bytecode, module.__dict__) File "site-packages\django\contrib\auth\base_user.py", line 52, in <module> File "site-packages\django\db\models\base.py", line 124, in __new__ File "site-packages\django\db\models\base.py", line 331, in add_to_class File "site-packages\django\db\models\options.py", line 214, in contribute_to_class File "site-packages\django\db\__init__.py", line 33, in __getattr__ File "site-packages\django\db\utils.py", line 211, in __getitem__ File "site-packages\django\db\utils.py", line 115, … -
Django: return HttpResponseRedirect in get_queryset
I'm resolving a query in a search form. When the query yields only a single object, I want to redirect the user directly to the details page for that object. If not, they should land on the results page. I thought I'd do it as follows: class ResultsView(generic.ListView): template_name = "chars/results.html" context_object_name = "chars" slug_field = 'name' def get_queryset(self): char = self.kwargs.pop('slug', '') object_list = get_list_or_404(Char, name=char) if len(object_list) > 1: return object_list return HttpResponseRedirect(reverse('chars:details', args=(char,))) Unfortunately, this doesn't work and yields an empty bytestring (b'') to my template. Any ideas? -
register user in legacy database table
I am new to Django and would like to know if I would have to register a user in a table that I created in my database, or in the future I could register a table "Product" or "HelpDesk" view.py from .forms import Testecadastro def cadastro(request): form = Testecadastro(request.POST or None) if request.method == 'POST': form.save() return render(request, 'cad.html', {'form': form}) forms.py from django import forms from .models import Testecadastro class TesteCadastro(forms.ModelForm): class Meta: model = Testecadastro fields = ['username', 'password'] widgets = { 'username': forms.TextInput(attrs={'class': 'form-control', 'maxlength': 255}), 'password': forms.PasswordInput(attrs={'class': 'form-control', 'maxlengeth': 255}) } model.py class Testecadastro(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) username = models.CharField(max_length=100, blank=True, null=True) password = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = True db_table = 'Testecadastro' Error: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' -
Multi spiders on scrapy
I use django, celery, scrapy. My settings for celery: CELERY_BROKER_URL = 'amqp://****/myvhost' CELERY_TIMEZONE = TIME_ZONE CELERYD_CONCURRENCY = 1000 CELERYD_MAX_TASKS_PER_CHILD = 4 CELERY_IGNORE_RESULT = True # django celery CELERY_RESULT_BACKEND = 'django-db' # celery queues setup CELERY_DEFAULT_QUEUE = 'default' CELERY_DEFAULT_ROUTING_KEY = 'default' CELERY_QUEUES = ( Queue('get_context', Exchange('get_context'), routing_key='get_context'), Queue('get_article', Exchange('get_article'), routing_key='get_article'), ) CELERY_ROUTES = { 'parse.tasks.get_context': { 'queue': 'get_context', 'routing_key': 'get_context', }, 'parse.tasks.get_article': { 'queue': 'get_article', 'routing_key': 'get_article', }, } There are two tasks on celery: from api_parser import celery_app from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from scrapy_parser.scrapy_parser.spiders.map_links import MapLinksSpider from scrapy_parser.scrapy_parser.spiders.articles import ArticlesSpider from threading import Thread @celery_app.task def get_context(rules_id, rules): process = CrawlerProcess(get_project_settings()) process.crawl(MapLinksSpider, rules_id=rules_id, rules=rules) Thread(target=process.start).start() @celery_app.task def get_article(rules_id, link_id, rules, link): process = CrawlerProcess(get_project_settings()) process.crawl(ArticlesSpider, rules_id=rules_id, link_id=link_id, rules=rules, link=link) Thread(target=process.start).start() The first task is triggered by a signal and maps the links. The second task is started when a new link is added to the database. My signals in django: from django.db.models.signals import post_save from django.dispatch import receiver from parse.models.rules import Scheduler, Rules, ParseLinks from parse.tasks import get_context, get_article @receiver(post_save, sender=Scheduler) def create_task_get_context(sender, instance, created, **kwargs): if created: rules = Rules.objects.get(id=int(instance.rules.id)) get_context.delay(int(rules.id), str(rules.rules)) @receiver(post_save, sender=ParseLinks) def create_task_get_article(sender, instance, created, **kwargs): if created: parse_link = ParseLinks.objects.get(id=int(instance.id)) get_article.delay(int(parse_link.rules.id), … -
Django breaks on urls containing "logout"
I'm working on a Django web-app which has user accounts, and so has login and logout functions. What I would like to have is /accounts/login/ be the login page. This is working as expected right now. This issue is with logout- what I would like to have is /accounts/logout/ logout the user and redirect them to the login page. This, however, doesn't appear to work. Here is my url configuration in accounts/urls.py: from . import views urlpatterns = [ url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ] With this configuration, login works fine. But when I go to /accounts/logout/, I am just immediately sent back to the page I'm currently on. However, if I change the logout url: from . import views urlpatterns = [ url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logMeOutPlease/$', auth_views.logout, name='logout'), ] Then /accounts/login works as intended and /accounts/logMeOutPlease works as intended. Is there a reason the first configuration won't work? If I however move the logout functionality to the top level (i.e just /logout/), then it again works fine. I am using Django 2.0.6 and Python 3.5.2, and my laptop is on Ubuntu 16.04. -
Django: Protect single view with HTTP Basic Auth?
Short Version I want to achieve something similar to this here. In contrast, I would like to use the ordinary user model. Long Version I have a Django app with sessions and users can login and logout using standard facilities. However, I have one specific view where users should authenticate with HTTP Auth basic but their usual login (they copy and paste the URL to an external desktop application which supports HTTP Auth Basic only). How can this be achieved? -
FloatField __init__ got an unexpected keyword argument 'max_value'
I recently asked this question and solved my problem as originally stated. The following code works: class FloatRangeField (FloatField): """A FloatField constrained to a given range.""" def __init__ (self, minimum, maximum, **kwargs): minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)] self.minimum = minimum self.maximum = maximum kwargs ['validators'] = minmax FloatField.__init__ (self, **kwargs) def deconstruct (self): name, path, args, kwargs = super () .deconstruct () kwargs ['minimum'] = self.minimum kwargs ['maximum'] = self.maximum del kwargs ['validators'] return name, path, args, kwargs class AffinityField (FloatRangeField): """An affinity is a float from -1 (hate) to +1 (love).""" def __init__ (self, **kwargs): FloatRangeField.__init__ (self, -1.0, 1.0, **kwargs) def deconstruct (self): name, path, args, kwargs = super () .deconstruct () del kwargs ['minimum'] del kwargs ['maximum'] return name, path, args, kwargs However, I don't believe this is quite complete. I am new to Django, but my understanding is that adding validators constrains the data that the model is willing to save, but separately from this, as this answer indicates, there is validation at the form level. If you need constraint on form level you can pass min_value and max_value to form field: myfloat = forms.FloatField(min_value=0.0, max_value=1.0) I don't have any visible forms yet (just starting to … -
Django admin list_filter custom field error
I extended the user with extra option, such as department. But when i try adding filter for the derpartment at the admin panel. It throws this error: ERRORS: : (admin.E116) The value of 'list_filter[0]' refers to 'department', which does not refer to a Field. Refrence to how it looks: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user With this addition: class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) list_display = ('username', 'email', 'first_name', 'last_name', 'get_department') list_filter = ('department',) def get_department(self, instance): return instance.employee.department List display seems work fine. -
Multitable inheritance and reaching from parent to child
I have two models set up like such. class ModelA(models.Model): parent = models.ForeignKey("self") class ModelB(ModelA): def action(self): if self.parent is not None: self.parent.action() Typically, of course, when I save to the model I am saving as a type of ModelB. When I call action, and look at what is going on I see that self is indeed of type ModelB. self.parent, however, is of type ModelA. i am guessing this is because ModelA actually has the field 'parent'. What happens is I get an error that ModelA has no attribute 'action'. So, given that, how do I use the methods in ModelB when an object is of type ModelA? -
django inspectdb doesnt generate models of SSISDB SQL Server 2012
I am using django for a project with MS SQL Server 2012, the connection work great, actually i have two databases in the server, i try the other and the inspectdb generates all the models correctly, but when i use the SSISDB table dosnt generate the models. What i am doing wrong? Its a permission thing? -
how to make field editable in django model for superuser and default for user
class holiday(models.Model): start_date=models.DateField() end_date=models.DateField() type=models.ForeignKey(HolidayType, on_delete=models.CASCADE) note=models.TextField(max_length=400, null=False, blank=True, help_text='Optional to write reason if you want to writed') image_ref = models.FileField(upload_to='post_image', blank=True,verbose_name="Image",help_text='HOliday agreement or hosptile comfirmation') created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='last_updated_by') last_modified_by =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='created_by') employees = models.ManyToManyField(Employee) # To demonstrate select2 multiple def __unicode__(self): return u' %d = %s : %s ' % (self.created_by.id,self.type,' , '.join([str(x.employeeid) for x in self.employees.all()])) def __str__(self): return u' %d = %s : %s' % (self.created_by.id, self.type, ' , '.join([str(x.employeeid) for x in self.employees.all()])) i want superuser to select many user to the feild employee but the user can not select he just follow the default like requset.user employees = models.ManyToManyField(Employee) -
Get Django search query right
Im currently facing a problem since a couple of days for now. I simply want to implement a search view into my Django app. But when i try to search something on my App i get the following error: __init__() takes 1 positional argument but 2 were given i guess i simply don't pass the catagory selection to the view and i have no idea how to do it. In the end i want that my Query is a combination of category and searchword. So that the user can filter specific categories (Just like Amazon.com searchfield) e.g.: http://127.0.0.1:8000/search/?category=1&q=hallo base.html ... <div class="globalsearch"> <form id="searchform" action="{% url 'search' %}" method="get" accept-charset="utf-8"> <label for="{{ categorysearch_form.category.id_for_label }}">In category: </label> {{ categorysearch_form.category }} <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search for ..."> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> </form> </div> </div> ... categorysearch_form is a dropdown selector that gets his ID from the Database. views.py ... from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.views.generic import ListView class globalsearch(ListView): """ Display a Post List page filtered by the search query. """ model = Post paginate_by = 10 def get_queryset(self): qs = Post.objects.published() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) title_vector = SearchVector('title', weight='A') content_vector … -
Django Jquery bootstrap Display available time slots for provided start date time and end date time
I want to show available time slots for cars and user can pick the time to book the car . how to show available slots -
DRF ModelSerializer - How to add an additional field that is many primary keys?
I have a ModelSerializer named ExampleModelCreateSerializer accepting data for it's models fields. However, I would like to pass additional data that doesn't belong in the model. Specifically, I would like to include a list of primary keys of a different model. For that, I am using serializers.PrimaryKeyRelatedField(many=True) When I try to submit a POST request, I get this error. Got a `TypeError` when calling `examplemodel.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `examplemodel.objects.create()`. You may need to make the field read-only, or override the ExampleModelCreateSerializer.create() method to handle this correctly. I assume this is because of the additional field trying to be saved into the model instance. So I tried to pop the field right after the serializer runs is_valid. def create(self, request, *args, **kwargs): ... serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.validated_data.pop('listofkeys') ... This returns 'examplemodel' object has no attribute 'listofkeys' All I am trying to do is pass additional fields to this Serializer and not have those fields conflict with the saving and creation of the model instances. I've read in other answers to fairly similar questions to make these fields read-only but wouldn't that only work … -
django-import-export assign current user
Trying to assign added_by user while creating an instance and want to create another model instance referring to the current instance views.py class ImportFarmersView(APIView): parser_classes = (MultiPartParser,) def post(self,request,org_slug=None,format=None,*args,**kwargs): serializer=TmpFileUploadSerializer(data=request.data) if not serializer.is_valid(): return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST) entries=serializer.validated_data['file'] profile_resource=ProfileResource() dataset=Dataset() imported_data = dataset.load(open(entries.temporary_file_path(),'rb').read(),'xls') result = profile_resource.import_data(dataset, dry_run=True) # Test the data import if result.has_errors(): return Response(status=status.HTTP_406_NOT_ACCEPTABLE) profile_resource.import_data(dataset, dry_run=False) # Actually import now return Response(status=status.HTTP_202_ACCEPTED) resources.py class ProfileResource(resources.ModelResource): created_at=fields.Field(readonly=True) updated_at=fields.Field(readonly=True) class Meta: model=Profile skip_unchange=True report_skipped=False import_id_fields=('slug','email') Thanks in advance -
Django response that contains a zip file with multiple csv files
I have a algorithm that outputs a list of tuples which is ready to be written into a csv file. I'm trying to write 3 csv files (through StringIO so no writing to disk) and then zip them altogether. After that I want to attach that to the response of a django request. I'm not sure what's the most efficient way to do this. Should I use StringIO to store the 3 calls through my algo? Should I actually create the csv files first before zipping them? Can I directly use 1 zipfile call without the intermediate steps of calling 3 StringIOs? Thanks -
Django Python-social-oauth, LinkedIn user showing as anonymous user and not logging in
I'm successfully able to fetch all the user details from LinkedIn into the database and a new user is being created every time. How to 'login' the created user? These are the packages installed in my virtual enviornment: certifi==2018.4.16 chardet==3.0.4 defusedxml==0.5.0 Django==1.10.8 idna==2.7 oauthlib==2.1.0 pkg-resources==0.0.0 PyJWT==1.6.4 python-social-auth==0.3.6 python3-openid==3.1.0 requests==2.19.1 requests-oauthlib==1.0.0 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 urllib3==1.23 These are the changes I made in my 'settings.py': INSTALLED_APPS = [ 'accounts', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social.backends.linkedin.LinkedinOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'my_key' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'my_secret' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile','r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [('id', 'id'), ('firstName', 'first_name'), ('lastName', 'last_name'), ('emailAddress', 'email_address')] SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/' SOCIAL_AUTH_LOGIN_URL = '/' This is my main 'urls.py': from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('accounts.urls')), url(r'', include('social_django.urls', namespace='social')), ] This is another 'urls.py' inside 'accounts' app: from django.conf.urls import url,include from . import views urlpatterns=[ url(r'^$', views.login, name='login'), url(r'^home/$',views.home, name='home'), ] And this is my 'views.py': from django.shortcuts import … -
how to make one/{id}/two make post possible in django rest
models.py class Two(models.Model): abc=models.CharField(max_length=12) ab = models.IntegerField() class One(models.Model): xy = models.CharField(max_length=23) user = models.ForeignKey(User) one = models.OneToOneField(One, blank=True, null=True) Class Two is related to class One by Foreignkey and it is needed to make blank and null true. As Two is to be given later. serializers.py class OneSerializer(serializers.ModelSerializer): class Meta: model = One fields = '__all__' class TwoSerializer(serializer.ModelSerializer): class Meta: model = Two fields = '__all__' views.py class OneView(APIView): @staticmethod def get(request): one = One.objects.all() if type(one) == Response: return queries return Response(OneSerializer(one, many=True).data) @staticmethod def post(request): serializer = OneSerializer(data=request.data, context = {'request':request}) if serializer.is_valid(): user = request.user serializer.save() return Response(OneSerializer(serializer.instance).data, status=201) return Response(serializer.errors, status=400) class OneDetailView(APIView): @staticmethod def get(request, one_id): oni = get_object_or_404(One, pk=one_id) return Response(OneSerializer(oni).data) @staticmethod def patch(request, one_id): oni = get_object_or_404(One, pk=one_id) serializer = OneSerializer(oni, data=request.data, context={'request':request}, partial=True) if serializer.is_valid(): serializer.save() return Response(OneSerializer(serializer.instance).data) return Response(serializer.errors, status=404) @staticmethod def delete(request, one_id): oni = get_object_or_404(One, pk=one_id) if oni.user != request.user: return Response(status=401) post.delete() return Response(status=204) class TwoView(APIView): @staticmethod def get(request, one_id): oni= get_object_or_404(One,pk=one_id) two = Two.objects.get(one=oni) if type(two) == Response: return two return Response(TwoSerializer(two).data) @staticmethod def post(request, one_id): oni = get_object_or_404(One,pk=one_id) two = Two.objects.get(one=oni) serializer = TwoSerializer(data=request.data, context = {'request':request}) if serializer.is_valid(): user = request.user serializer.save() return Response(TwoSerializer(serializer.instance).data, … -
Django Rest standalone API + React Standalone SPA
So I wanted to create a standalone django API that accepts some data say in JSON form and then return JSON data after some processing, not storage in a model. I intend to run it through a lstm and serve as a chatbot API. All the tutorials I find online are about serializers pushing data to and fro models. I wanna process the data as it flows in 1st, then think of storing maybe... -
how to connect the backend and frontend of a web application with django?
I want to make a web application with django on windows, I have already created the interfaces of my application but now I would like that when I operate on a button of the page ca execute my python code that I had to write. but I do not know how to do it. someone can help me. -
Why does cloning this subclass of FloatField (with added validators) throw an exception?
I am new to Python and Django. I want my model to have range-validated floats. From this answer I wrote this: class FloatRangeField (FloatField): """A FloatField constrained to a given range.""" def __init__ (self, minimum, maximum, **kwargs): minmax = [MinValueValidator (minimum), MaxValueValidator (maximum)] print ("\n\t\tFloatRangeField({},{})".format(minimum,maximum)) # (A) FloatField.__init__ (self, validators = minmax, **kwargs) print ("\t\tFINISHED\n") This was causing errors in python3 manage.py migrate, I narrowed it down to a clone() call. Demonstration: print ("HERE 1") tmp1 = FloatRangeField (10, 20) print ("HERE 2") tmp2 = FloatRangeField (10, 20) print ("HERE 3") tmp3 = tmp1.clone () # (B) print ("HERE 4") It throws an exception from line # (B). Oddly, when this happens, the trace at line # (A) is not printed. Here is the output: HERE 1 FloatRangeField(10,20) FINISHED HERE 2 FloatRangeField(10,20) FINISHED HERE 3 Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() [...snip...] tmp3 = tmp1.clone () File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/__init__.py", line 470, in clone return self.__class__(*args, **kwargs) TypeError: __init__() missing 2 required positional arguments: 'minimum' and 'maximum' As well as the weirdness of nothing being printed at # (A), this is not the same as the error which I … -
How to create a unique-together constraint in Django that ignores NULL?
How does Django deal with NULL with its unique index? Is there a way to allow for many NULL rows, while enforcing uniqueness on non-null values? And then, the same question for unique_together. Is there a way to enforce unique_together, but if any of the fields are NULL, allow for that row?