Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pre_save signal is being called before full_clean method
I'm moving from overriding save methods to signals and I came across one problem. This is my save method: def save(self, *args, **kwargs): logger.info('AFTER PRESAVE') # self.full_clean() super(Occurence, self).save(*args, **kwargs) And this is the signal: @receiver(pre_save, sender=Occurence) def occurence_parse_url(instance, **kwargs): logger.info('PRE SAVE') if not instance.pk: url = parse_base_url(instance.url) name = parse_site(url).capitalize() instance.site = Site.objects.get_or_create(name=name, defaults={'url': url})[0] Object has to have site attribute not NULL which signal should create. The problem is that full_clean is called before the signal so it raises ValidationError. According to Django docs: django.db.models.signals.pre_save This is sent at the beginning of a model’s save() method. Do you know how to solve this issue? -
Download a file in django with a button using xmlhttprequest
I looked at many same questions but none resolved my problem, I'm trying to download a file generated in my view using a button. Problem : I get an empty file while clicking on download button My view: class dumpView(View): template_name = 'download.html' def get(self, request): file = open("/home/test.pdf", "rwbt") response = HttpResponse(file.read(), content_type="application/pdf") response['Content-Disposition'] = 'attachement; filename=%s' % file return render(request, 'download.html') My url: url(r'^dump/', dumpView.as_view()), My template: {% extends 'base.html' %} {% load staticfiles %} {% block content %} <div class="container"> <div class="row"> <div class="jumbotron"> <div class="row"> <center> <a href="javascript:void(0)" class="btn btn-primary btn-lg dump">Download</a> </center> </div> </div> </div> </div> {% endblock %} {% block javascript %} <script src="{% static 'js/home.js' %}"></script> {% endblock %} My Django view is rendering the response. I did add an on click handler to the button with class dump in the UI to make a XHR request to the “/dump” URL and recieve response as a blob and download the file with custom name and date. My js : $(".dump").on("click", function() { xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { var a, today; if (xhttp.readyState === 4 && xhttp.status === 200) { a = document.createElement('a'); a.href = window.URL.createObjectURL(xhttp.response); today = new Date(); a.download … -
Create a User and ExtendedUser object in one form using an Inline formset?
I have a model Sachbearbeiter which extends my User model. from django.contrib.auth.models import User class Sachbearbeiter(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) verein = models.ForeignKey(Verein) Now I need CreateView form to create a new Sachbearbeiter instance that is immediately linked to a new User instance. The form should have the following fields: First Name: [textfield] Last Name: [textfield] Email Address: [textfield] Verein: [Dropdown that lists `Vereine`] What I tried is this: class SachbearbeiterForm(ModelForm): class Meta: model = Sachbearbeiter fields = '__all__' # Go into detail once it's working class UserForm(ModelForm): class Meta: model = User fields = '__all__' # Go into detail once it's working SachbearbeiterFormSet = inlineformset_factory(User, Sachbearbeiter, fields='__all__') class SachbearbeiterCreate(CreateView): form_class = SachbearbeiterFormSet But this gives me a form that looks like this: Verein: [Dropdown that lists `Vereine`] Delete? [checkbox] Is this even possible, or do I have to create a custom form for that? -
django template / File name too long error/ when getting models objects
I am getting an error which lokks like this: IOError at /url/ [Errno 36] File name too long: "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/ <user_prefs: user_prefs object>,<user_prefs: user_prefs object>,<user_prefs: user_prefs object> etc.. my views.py look like this def show_interests(request): current_user = request.user.id output = user_prefs() output.save() outputs = user_prefs.objects.all().filter(userID=current_user) return render('showme.html',{'outputs':outputs}) and my template( i use a very basic html form just to test things as for now.) <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <title>Hi, it's a test</title> {% for outputs in output %} {{ outputs.Cuisine }} {{ outputs.Cuisine1 }} {{ outputs.LunchPref }} {{ outputs.DinnerPref }} {{ outputs.Friday }} {{ outputs.Sunday }} {% endfor %} <body> </body> </html> Never ever seen an error like this, and my other models that i have work just fine. -
What is a more efficient way to accomplish validate/save()'ing a Django object while abstracting away the repetition?
I highly doubt that the way I put this together is best practice, or even secure. It is a FBV that allows users to POST update their profiles by way of using the provided ModelForm. The view: def profile_edit(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): instance = Profile.objects.get(user=request.user) instance.activity1 = form.cleaned_data.get("activity1") instance.activity2 = form.cleaned_data.get("activity2") instance.activity3 = form.cleaned_data.get("activity3") instance.subject1 = form.cleaned_data.get("subject1") instance.subject2 = form.cleaned_data.get("subject2") instance.subject3 = form.cleaned_data.get("subject3") instance.introduction = form.cleaned_data.get("introduction") instance = form.save(commit=False) instance.save() return redirect('/profile/edit') else: form = ProfileForm(instance=request.user, initial={ 'activity1': Profile.objects.get(user=request.user).activity1, 'activity2': Profile.objects.get(user=request.user).activity2, 'activity3': Profile.objects.get(user=request.user).activity3, 'subject1': Profile.objects.get(user=request.user).subject1, 'subject2': Profile.objects.get(user=request.user).subject2, 'subject3': Profile.objects.get(user=request.user).subject3, 'introduction': Profile.objects.get(user=request.user).introduction, }) context = { 'user': request.user, 'form': form, } return render(request, 'profile_edit.html', context) The form: class ProfileForm(forms.ModelForm): activity1 = forms.CharField(max_length=54, label='Activity 1') activity2 = forms.CharField(max_length=54) activity3 = forms.CharField(max_length=54) subject1 = forms.CharField(max_length=54) subject2 = forms.CharField(max_length=54) subject3 = forms.CharField(max_length=54) introduction = forms.CharField(widget=forms.Textarea) def clean(self): cleaned_data = super(ProfileForm, self).clean() return cleaned_data Is there a better way to get this accomplished? I would think there's a way to retrieve the entire cleaned form data at once, and then update the instance with the all new POSTed data in fewer statements as well. And what about pre-populating a form with data already stored in the database? Is querying … -
Django, permission error saving on disk, why?
I'm getting a Permissions Error [Errno 13] Permission Denied when a workbook on disk using openpyxl: wb.save(path) No file is uploaded. It's a request then the file is generated and delivered (downloaded), and that part works fine. What I'm trying to do is save a copy of that file on disk. So far I have rw to both group and others. Same error. Has anyone tried this before? Is this a Django issue or Linux/Permission? Thank you for the help. -
PEX and Django - unable to import project apps
I'm trying to use PEX as my "virtualenv" packager. I used standard PEX command (installed inside my virtualenv): pex -r requirements.txt -o test_env.pex From what i understand i should now be able to run: ./test_env.pex manage.py runserver outside virtualenv. But it gives me error: ImportError: No module named 'some_module' which is one of my modules in project. I can run: ./test_env.pex and import django and all libs from requirements.txt but i cant import any of my "project" libs (from some_module import * gives me error as above). How can i make "pex" aware of current directory and packages? -
Serializing uploaded file data Django Rest Framework
I am trying to get a file upload system working in Django Rest Framework. The files I want to upload are .gpx files which are custom xml files. I don't want to store the files in the database, instead I want to extract information from them and then input this into my model. I have a function that takes a temp file and then extracts the info and then creates the model elements as needed. What I'm looking to do is perform some checks on the file before it is uploaded and passed to this function. How should I do this? The file upload is currently done as in the documentation (see below), which a generic APIView and a put command. This works perfectly, I just want to know what the best way is to check this file's validity before upload. views.py class FileUploadView(views.APIView): parser_classes = (FileUploadParser, ) def put(self, request, filename, format=None): up_file = request.data['file'] SaveGPXtoModel(up_file, request.user) return Response(status=204) Should the API do these checks or should it assume the file has already been validated? In Django these checks would be handled by the form, should I use a serializer to do these checks? If a serializer is the … -
Passing GET params to a Django View internally
I am trying to call a Django view internally from another view: response = BlogViewSet.as_view({'get':'list'})(request) BlogViewSet is actually a rest framework view. The above code works and I can access response.data but what I actually want to do is pass in some GET params to do some filtering. I tried the following but it didn't work: response = BlogViewSet.as_view({'get':'list'})(request, my_param=something) I realise I could modify request to add GET params but it seems wrong to modify it as it might be used later in the view. -
Django rest framework - cant serialize query set
I try to serialize query set def do(self): reservations = Reservation.objects.all() serializer = ReservationSerializer(data=reservations, many=True) if serializer.is_valid(): encoded_data = json.dumps(serializer.data) r = requests.post('http://httpbin.org/post', headers={'Content-Type': 'application/json'}, data=encoded_data) print(r.text) else: print(serializer.errors) And I always get error of {u'non_field_errors': [u'Expected a list of items but got type "QuerySet".']} I tried to use values() on query set, and then convert to list, but this way I get objects without nested models model class Reservation(models.Model): start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False) end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False) check_in_time = models.TimeField(verbose_name='Время заезда', blank=False) check_out_time = models.TimeField(verbose_name='Время выезда', blank=False) has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True) payed = models.BooleanField(verbose_name='Оплачено', default=False) reserved_days = models.ManyToManyField(Day, blank=False) additional_services = models.ManyToManyField(AdditionalService) guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True) reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True) class AdditionalService(models.Model): payment_date = models.CharField(verbose_name='Дата оплаты', max_length=200, blank=True) payment_type = models.CharField(verbose_name='Форма оплаты', max_length=200, blank=False) service = models.CharField(verbose_name='Услуга', max_length=200, blank=False) quantity = models.IntegerField(blank=False) price = models.FloatField(blank=False) class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length = 200, blank=True) payment_date = models.CharField(max_length=200, blank=True) room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE) class Room(models.Model): name = models.CharField(max_length = 200, null=True) id = models.AutoField(primary_key=True) room_id = models.CharField(max_length = 200, null=False) def __unicode__(self): return self.name serializers class ReservationSerializer(serializers.ModelSerializer): reserved_days = DaySerializer(many=True) additional_services = … -
Django forms input restriction
tr_id = forms.CharField(required=False, max_length=20, widget=forms.TextInput(attrs={ 'class':'filter filter_tr_id', 'placeholder':'TR ID' }) ) I would like to restrict this Django input for only numbers and underscore. I've already got a js function which does the job. how I can add onkeyup feature in the input ? function number_only(id_tr_id) { var regex = /[^0-9\._]/g; id_tr_id.value = id_tr_id.value.replace(regex,""); } is there any other way I can restrict the input for numbers and underscore only ? Thanks -
Django-- Deactivate User account instead of deleting it
I want to deactivate the User account instead of deleting it. I want to do something like user.is_active = False. I have a view to delete User profile and it works but now I need to change it to only deactivate. Here is my view: def delete_profile(request): user = User.objects.filter(id = request.user.profile.user_id) try: user.delete() except: messages.error(request,'Please try again.') return redirect('profile') messages.success(request, 'Profile successfully deleted.') return redirect('index') I tried User.is_active = False , it displays the success message but doesn't do anything. When I check the User in admin panel it will still have User marked as active. Any Idea how I can achieve this? Thanks in advance -
Remove blur from message container
I applied blur for body but i want to remove it for message container. How can i do it ? please i need your help i lost too much time on finding a solution. On close button the message disappears and the blur is removed for body. My only problem is that blur property is applied for message container. Before if success all the body is normal. All the change is after if success. {% if success %} <body id="overlay" style="filter: blur(2px);" > <div id="messageContainer"> <div id='card' class="animated fadeIn"> <div id='upper-side'> <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="checkmark" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" xml:space="preserve"> <path d="M131.583,92.152l-0.026-0.041c-0.713-1.118-2.197-1.447-3.316-0.734l-31.782,20.257l-4.74-12.65 c-0.483-1.29-1.882-1.958-3.124-1.493l-0.045,0.017c-1.242,0.465-1.857,1.888-1.374,3.178l5.763,15.382 c0.131,0.351,0.334,0.65,0.579,0.898c0.028,0.029,0.06,0.052,0.089,0.08c0.08,0.073,0.159,0.147,0.246,0.209 c0.071,0.051,0.147,0.091,0.222,0.133c0.058,0.033,0.115,0.069,0.175,0.097c0.081,0.037,0.165,0.063,0.249,0.091 c0.065,0.022,0.128,0.047,0.195,0.063c0.079,0.019,0.159,0.026,0.239,0.037c0.074,0.01,0.147,0.024,0.221,0.027 c0.097,0.004,0.194-0.006,0.292-0.014c0.055-0.005,0.109-0.003,0.163-0.012c0.323-0.048,0.641-0.16,0.933-0.346l34.305-21.865 C131.967,94.755,132.296,93.271,131.583,92.152z" /> <circle fill="none" stroke="#ffffff" stroke-width="5" stroke-miterlimit="10" cx="109.486" cy="104.353" r="32.53" /> </svg> <h3 id='status'> Success </h3> </div> <div id='lower-side'> <p id='message'> Thank you for your interest in Neotic. </p> <div> <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn ui-icon-delete ui-btn-icon-notext ui-btn-right" onclick="$('#card').hide(); body.style.filter = 'none' ;">X</a> </div> -
Should I prefer one general signal instead of multiple specific ones?
When the user creates a product, multiple actions have to be done in save() method before calling super(Product,self).save(*args,**kwargs). I'm not sure if I should use just one pre_save signal to do all these actions or it is better to create a signal for each of these actions separately. Simple example (I'm going to replace save overrides by signals): class Product(..): def save(...): if not self.pk: if not self.category: self.category = Category.get_default() if not self.brand: self.brand = 'NA' super(Product,self).save(*args,**kwargs) ... SO @receiver(pre_save,sender=Product) def set_attrs(instance,**kwargs): if kwargs['created']: instance.category = Category.get_default() instance.brand = 'NA' OR @receiver(pre_save,sender=Product) def set_category(instance,**kwargs): if kwargs['created']: instance.category = Category.get_default() @receiver(pre_save,sender=Product) def set_brand(instance,**kwargs): if kwargs['created']: instance.brand = 'NA' This is just simple example. In this case, the general set_attrs should be probably enough but there are more complex situations with different actions like creating userprofile for user and then userplan etc. Is there some best practice advice for this? Your opinions? -
CELERYD_CONCURRENCY, --concurrency and autoscale
I have a few questions regarding task routing, concurrency and performance. Here is my use case : I've got one dedicated server to run celery tasks, so I can use all the CPUs to run celery workers on this server. I have a lot of different python tasks, which I route using : CELERY_ROUTES and because the tasks perform really different types of python code, I created 5 different workers. These worker are created when I deploy my project using ansible, here is an example: [program:default_queue-celery] command={{ venv_dir }}/bin/celery worker --app=django_coreapp --loglevel=INFO --concurrency=1 --autoscale=15,10 --queues=default_queue environment = SERVER_TYPE="{{ SERVER_TYPE }}", DB_SCHEMA="{{ DB_SCHEMA }}", DB_USER="{{ DB_USER }}", DB_PASS="{{ DB_PASS }}", DB_HOST="{{ DB_HOST }}" directory={{ git_dir }} user={{ user }} group={{ group }} stdout_logfile={{ log_dir }}/default_queue.log stdout_logfile_maxbytes=50MB stdout_logfile_backups=5 redirect_stderr=true autostart=true autorestart=true startsecs=10 killasgroup=true I have also a CELERY_QUEUES in settings.py to make the bridge between CELERY_ROUTES and my celery programs (Queues) CELERY_DEFAULT_QUEUE = 'default_queue' And if it happens that I don't route a task it will go to my 'default_queue' To give space to all of my queues, I set --concurrency to 1 for default_queue, and more for my most important queue. But I am wondering, does AutoScale have impact on the … -
How to add a form that appear only one time for new users and then back to regular form
I want to create a form with extra fields : this is the models.py for regular form : Boutique : class Boutique(models.Model): name = models.CharField(max_length=250) user = models.ForeignKey(User, default=1) logo = models.FileField(max_length=250) def __str__(self): return self.name form.py : class BoutiqueForm(forms.ModelForm): class Meta: model = Boutique fields = ['name', 'logo'] Views.py : def create_boutique(request): if not request.user.is_authenticated(): return render(request, 'produit/login.html') else: form = BoutiqueForm(request.POST or None, request.FILES or None) if form.is_valid(): boutique = form.save(commit=False) boutique.user = request.user boutique.logo = request.FILES['logo'] file_type = boutique.logo.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'boutique': boutique, 'form': form, 'error_message': 'Image file must be PNG, JPG, or JPEG', } return render(request, 'produit/create_boutique.html', context) boutique.save() return render(request, 'produit/detail.html', {'boutique': boutique}) context = { "form": form, } return render(request, 'produit/create_boutique.html', context) form_template.html : {% for field in form %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2">{{ field.label_tag}}</label> <div class="col-sm-10">{{ field }}</div> </div>{% endfor %} i want to add a table boutique_commerçant that containt 2 extra fields facebook_link and entreprise ... that appear in create_boutique.html only one time for new registred user... -
Serving Static files Django 1.11.3
i'm new to programming(Python 3.6, Django 1.11.3), I've been teaching myself over youtube and the product's documentation. Now I'm following a youtube video by Chris Hawkes, titled Django 1.10 Tutorial. I followed every instruction down to the nail, but for some reason, the database still doesn't find the static files.here's the link to the project structure, setting.py and index.html. https://www.dropbox.com/sh/q6yfxqt7k4wy43l/AACBcgMiOsdnCyGEvBK4zd45a?dl=0 May you kindly assist, I'd appreciate any pointers as to what I should be doing. Thank you -
How to add Slugify to ElasticSearch?
There is a russian word for "pizza" = "пицца" and they are very similar since: "p" equals to "п" "i" equals to "и" "z" equals to "ц" "z" equals to "ц" "a" equals to "а" So when im searching for "пицца" i must get all results with "pizza" as result. How can i achieve that ? -
Create a mixin for class Meta in ModelForm
Django==1.11.3 The code below seems to violate DRY principle. But I fail to create a mixin to generalize the three strings with: exclude; from_date through_date. Could you give me a kick here? class BatchDateInputForm(forms.ModelForm): class Meta: model = BatchDateInput exclude = [] widgets = { 'user': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=get_years()), 'through_date': forms.SelectDateWidget(years=get_years()), } class FrameDateForm(ModelForm): class Meta: model = FrameDate exclude = [] widgets = { 'frame': forms.HiddenInput(), 'from_date': forms.SelectDateWidget(years=get_years()), 'through_date': forms.SelectDateWidget(years=get_years()) } -
Python/Django - No module named
I try to work with class from django views. sync.py import requests class Sync: def do(): r = requests.post('http://192.168.1.7/api/report_x') print(r.response) views.py import sync def index(request): s = Sync() s.do() return HttpResponse("Hello, this is index") When I access index from browser I get global name 'Sync' is not defined What am I doing wrong ? -
Cannot overwrite Django authentication templates in AWS
I have developped a Django application and I have been using the django-authtools module to be able to login using email. It is working great on my laptop but when I tried to deploy it in production in AWS using Beanstalk, it seems Django does not recognize the overwrite of the authentication module and is forcing redirection to the django built-in authentication module. Everything else seems to work fine (from a deployment and application point of view). It results in a 500 error: xxx.xxx.xxx.xxx (-) - - [04/Jul/2017:19:07:54 +1000] "GET /accounts/login/ HTTP/1.1" 500 7807 "http://<removed>.ap-southeast-2.elasticbeanstalk.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" Internal Server Error: /accounts/login/ Traceback (most recent call last): File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 82, in rendered_content template = self.resolve_template(self.template_name) File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/response.py", line 64, in resolve_template return select_template(template, using=self.using) File "/opt/python/run/venv/lib/python3.4/site-packages/django/template/loader.py", line 53, in select_template raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: registration/login.html Again this is working perfectly fine on my laptop, but not on the AWS server. I … -
NGINX - Blog (index page) within site gets redirected through proxy correctly, but all sub-sites do not have the same redirect
NGINX noob here, so please pardon my ignorance; I have a server running a DJANGO site, and WordPress blog in a Docker container within the same server; This is the way I have currently set up my NGINX configuration file: server { listen 80; server_name 123.45.67.89; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/johndoe/djangosite; } location / { include uwsgi_params; uwsgi_pass unix:/home/johndoe/djangosite/djangosite.sock; } location /blog { rewrite ^/blog(.*) /$1 break; proxy_pass "http://127.0.0.1:8001"; } } So using this NGINX configuration, accessing my server 123.45.67.89, successfully brings up my Django site, and I'm able to use it to its full extent; accessing 123.45.67.89/blog, takes me to my WordPress blog page (the blog index); at this point, clicking anything more within the WordPress blog (like a blog post, or the WP Admin site, or anything else related to the WordPress blog), will change the URL to: 123.45.67.89:8001/wp-login.php instead of 123.45.67.89/blog/wp-login.php. How can NGINX be configured to use the blog url path, for everything related to the WordPress sub-site, and not just the WordPress index page? I want the port 8001, that keeps showing up in all WordPress URLs to be instead replaced with "/blog/", like it currently … -
routing urls not correctly django 1.8
Help! I have a simple problem. I made links in my templates, like this: <a href="students">students</a> When i go to alumni.html and i click on the link directing to students.html, it directs to alumni/students but i want to click and see /students. I dont understand why its routing to alumni/students instead. I only changed one aspect of settings.py into: 'DIRS': [os.path.join(BASE_DIR, "templates")], urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^students/$', 'assignments.views.students', name='students'), url(r'^alumni/$', 'assignments.views.alumni', name='alumni'), ] views.py from django.shortcuts import render def students(request): return render(request, "students.html", {}) def alumni(request): return render(request, "alumni.html", {}) What am i doing wrong? -
Is it possible to bind an django-user account to one specific workstation?
My goal is that every user can only log in to my Django web app from a specific workstation. If the user tries to log in from another workstation, the login should be denied. Is it possible to implement such a licensing model in Django, possibly via identifying the hostname of the workstation? I'm using Django 1.10/Python 3.5. -
Group by in django framework
id = (1,2,3,4), parent_user_id=(7,7,4,4) Sql Statment: select `id` from profile WHERE parent_user_id in(4,7) GROUP BY parent_user_id; How to write the above sql statement in Django?