Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write python-django queires and import them?
Data : { "Fruit": "Pomegranate", "District": "Nasik", "Taluka": "Nasik", "Revenue circle": "Nasik", "Sum Insured": 28000, "Area": 1200, "Farmer": 183 } { "Fruit": "Pomegranate", "District": "Jalna", "Taluka": "Jalna", "Revenue circle": "Jalna", "Sum Insured": 28000, "Area": 120, "Farmer": 13 } { "Fruit": "Guava", "District": "Pune", "Taluka": "Haveli", "Revenue circle": "Uralikanchan", "Sum Insured": 50000, "Area": 10, "Farmer": 100 } { "Fruit": "Guava", "District": "Nasik", "Taluka": "Girnare", "Revenue circle": "Girnare", "Sum Insured": 50000, "Area": 75, "Farmer": 90 } { "Fruit": "Banana", "District": "Nanded", "Taluka": "Nandurbar", "Revenue circle": "NandedBK", "Sum Insured": 5000, "Area": 2260, "Farmer": 342 } { "Fruit": "Banana", "District": "Jalgaon", "Taluka": "Bhadgaon", "Revenue circle": "Bhadgaon", "Sum Insured": 5000, "Area": 220, "Farmer": 265 } I want to write all types of combination queries, if someone wants information only for Fruit which is Guava then the output will be exact data for Guava only. also if someone wants information only for Fruit which is Banana & Guava then the output will be exact data for Banana and Guava. If fruit is equal to Banana output will be data for Banana If fruit is equal to Guava output will be data for Guava If fruit is equal to Banana and Guava output will be data for โฆ -
Setting up a Django Project on CodeAnywhere
I am trying to create a running Django project on CodeAnywhere, but i just cant seem to get it running. i am starting in a very basic manner, with the below code import webbrowser webbrowser.open('www.bbc.co.uk') is it even possible to get this to open a new tab in a webbrowser, and will it be on my local machine or within codeanywhere? Many thanks -
Login method in mongo auth backend without mongoengine
I am writing custom auth backend for mongodb, but without using mongoengine, with using PyMoDM. I implemented authenticate and get_user methods in the backend, and authentication goes right. Here is pymodm user model: from pymodm import MongoModel, fields class User(MongoModel): email = fields.CharField(required=True, primary_key=True) username = fields.CharField(required=True) password = fields.CharField(required=True) I tried to define AUTH_USER_MODEL to be my mongo model, but it raises: LookupError: App 'authorization' doesn't have a 'user' model. Ok, I tried to proceed without AUTH_USER_MODEL. When I want to login user, I get an error: AttributeError: 'User' object has no attribute '_meta' I looked into source code and error happens here. As I understand that _meta attribute is a model's self. When I tried to implement the model's property _meta: class User(MongoModel): ... @property def _meta(self): return self then it fails: AttributeError: 'str' object has no attribute 'value_to_string'. I understand why it happens, because every django field has value_to_string method, but pymodm fields don't. Finally, question: Is there a way to overcome it? Please, do not say that I need to use mongoengine. The questions is - how to do it with pymodm? -
Django: Is it possible to detect changed field in pre_save signal?
If I changed field value of ModelA, then is it possible to detect change of this field in pre_save signal? I think that instance.clean() or instance.clean_field() doesn't work inside pre_save signal. I know it can in Django form or Model level, but want to know it can in signal level. -
Staticfiles in Django not working
I just tried to implement a new way of working with my staticfiles (css, img, ...) and it seems that my staticfiles are not loading anymore. My folder: โโโ src โ โโโ ICtemplate โ โโโ archive.zip โ โโโ db.sqlite3 โ โโโ joins โ โโโ manage.py โ โโโ matches โ โโโ member โ โโโ newsletter โ โโโ organization โ โโโ questions โ โโโ requirements.txt โ โโโ static โ โโโ static-storage โ โโโ templates โโโ static-serve โ โโโ address โ โโโ admin โ โโโ css โ โโโ facebook โ โโโ js โ โโโ markitup โ โโโ static โโโ webfaction โโโ httpd.conf My urls.py: urlpatterns = [ ### My Apps ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: 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.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', ], }, }, ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static-storage"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static-serve") and the way it is implemented in the template: {% extends "base.html" %} {% load static %} ... <img src="{% static 'img/icbanner.png' %}" or {% load static %} <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/navbar-static-top.css' %}" rel="stylesheet"> โฆ -
Django: Initial value for a ModelSerializer field
Im writing a Django app using django==1.10 and djangorestframework==3.4.6 Please consider the following code: I have two models: class BaselineModel(models.Model): subject = models.ForeignKey('custom_auth.User', blank=True) weight = models.SmallIntegerField(null=True, blank=True) class DosageModel(models.Model): subject = models.ForeignKey('custom_auth.User', blank=True) udca = models.SmallIntegerField(null=True, blank=True) weight = models.SmallIntegerField(null=True, blank=True) and a serializer: class DosageSerializer(serializers.ModelSerializer): class Meta: exclude = ("subject",) model = DosageModel Question: How can I set the initial value for DosageModel.weight to BaselineModel.weight? -
How to update password in django?
I want to edit my user data from template, bellow are my codes. def guru_edit(request, id): Guru = get_object_or_404(DataGuru, GuruUser_FK_id=id) GuruUser = get_object_or_404(User, id=id) if request.method == 'POST': form_guru = dataguruform(request.POST, instance=Guru) form_user = userform(request.POST, instance=GuruUser) if form_guru.is_valid() and form_user.is_valid(): form_guru.save() form_user.save() return redirect('index_guru') else: form_guru = dataguruform(instance=Guru) form_user = userform(instance=GuruUser) return render(request, 'guru/guru_tambah.html', {'form_user': form_user,'form_guru':form_guru}) But when i was save from template, the password is not encrypted like it used to be, but just plaintext. How to make it encripted? -
xml authenticate version response via python django
I have zero knowledge on XML since I really use JSON but I have a project that includes XML transactions so I have no choice Basically, a request will sent to my API and then I will have to respond via XML like this <?xml version="1.0" encoding="UTF-8"?> <authenticateversion="2.0"> <vendor_member_id>Unique_ID</vendor_member_id> <status_code>0</status_code> <message>OK</message> </authenticate> Need help please, I don't know how to achieve this.. -
How can I find reporters who wrote at least one articles using django orm?
below are models: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline class Meta: ordering = ('headline',) How can I find reporters who wrote at least one articles using django orm ? -
WorkerLostError: Could not start worker processes
I am trying to integrate celery to my app. i want to delay a task which sends an activation email when a user signs up. But when i try to start my worker process python manage.py celeryd --loglevel=info i get this error the whole error is /Users/ravinkohli/env_email/lib/python2.7/site-packages/django/core/management/base.py:265: RemovedInDjango110Warning: OptionParser usage for Django management commands is deprecated, use ArgumentParser instead RemovedInDjango110Warning) /Users/ravinkohli/env_email/lib/python2.7/site-packages/celery/apps/worker.py:182: CDeprecationWarning: Starting from version 3.2 Celery will refuse to accept pickle by default. The pickle serializer is a security concern as it may give attackers the ability to execute any command. It's important to secure your broker from unauthorized access when using pickle, so we think that enabling pickle should require a deliberate action and not be the default choice. If you depend on pickle then you should set a setting to disable this warning and to be sure that everything will continue working when you upgrade to Celery 3.2:: CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] You must only enable the serializers that you will actually use. warnings.warn(CDeprecationWarning(W_PICKLE_DEPRECATED)) [2016-12-21 12:01:32,225: WARNING/MainProcess] /Users/ravinkohli/env_email/lib/python2.7/site-packages/celery/apps/worker.py:182: CDeprecationWarning: Starting from version 3.2 Celery will refuse to accept pickle by default. The pickle serializer is a security concern as it may give attackers the ability โฆ -
Django 1.10 KeyError at /admin/
I have a Django app that was written in Django 1.7, that I am porting to a Docker app. I'm using Django 1.10 in the container. When I browse to the /admin/ URI, I get the following exception: KeyError at /admin/ u'user' Request Method: GET Request URL: http://10.3.101.206:9000/admin/ Django Version: 1.10 Exception Type: KeyError Exception Value: u'user' Exception Location: /usr/local/lib/python2.7/site-packages/django/template/context.py in __getitem__, line 75 Python Executable: /usr/local/bin/python Python Version: 2.7.12 Python Path: ['/var/www/django/labmgr', '/usr/local/lib/python27.zip', '/usr/local/lib/python2.7', '/usr/local/lib/python2.7/plat-linux2', '/usr/local/lib/python2.7/lib-tk', '/usr/local/lib/python2.7/lib-old', '/usr/local/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages'] Server time: Tue, 20 Dec 2016 21:43:21 -0800 Error during template rendering In template /usr/local/lib/python2.7/site-packages/django/contrib/admin/templates/admin/index.html, error at line 58 user 48 {% endif %} 49 </div> 50 {% endblock %} 51 52 {% block sidebar %} 53 <div id="content-related"> 54 <div class="module" id="recent-actions-module"> 55 <h2>{% trans 'Recent actions' %}</h2> 56 <h3>{% trans 'My actions' %}</h3> 57 {% load log %} 58 {% get_admin_log 10 as admin_log for_user user %} 59 {% if not admin_log %} 60 <p>{% trans 'None available' %}</p> 61 {% else %} 62 <ul class="actionlist"> 63 {% for entry in admin_log %} 64 <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}"> 65 {% if entry.is_deletion or not entry.get_admin_url โฆ -
Keep alive OpenShift gear by Pinging
Scenario is, I have a less traffic gear in OpenShift(V2). Due to it's less traffic, gear become idle state. I know that BRONZE plan is there, but I am not interested to upgrade my plan. So I want the gear alive without using RESTART option provided by command-line tools or web-console. I already used HTTP GET method (by browser) ,but it didn't made the gear alive . Later I found a online tool, Is It Down Right Now and I CHECKed (name of the button on that particular website) my URL. Hence my gear became alive after 2,3 CHECK procedure. Then my question is, how can I keep alive a OpenShift gear by pinging or sending some request to my URL that is project_name-hostname.rhcloud.com using Python/Django. Or simply how can I create a exact/similar tool like Is It Down Right Now using Python/Django ? -
django press Enter and it show ^M
I want to change my models in django when I execute python manage.py makemigrations ,it asks a question: Did you rename the demoapp.Myblog model to Blog? [y/N] y^M^M^M that I input y and press Enter,but it adds ^M to the line I've looked around and apparently but I've got no choices can anybody tell me how to fix it? -
Whitenoise and/or static files causing Server Error (500)
I am able to deploy my app (via Django) to Heroku when DEBUG = True but when DEBUG = False I get a Server Error. I think it has to do with how I've set up my static files. When I comment out "STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'" I don't get an error message but the site is completely unformatted. Here's the relevant settings.py code: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ... ] ALLOWED_HOSTS = ['*'] PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT= os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) I've added my static folder in all sorts of locations (same folder as settings.py, in the root folder, etc) to no avail. Any ideas? -
django admin model field not update
I use Django Admin to add data, but the today field won't update to current time, always show django started time. model.py: class Post(models.Model): today = datetime.now().strftime("%Y%m%d") date = models.CharField(max_length=8,default=datetime.now()) title = models.CharField(max_length=100) content = models.TextField(blank=True) image link of screenshot to show my page -
Errno 111: Connection refused- Haystack ElasticSearch setup
I've followed the setup guide from Haystack documentation, when I try to build the indexes using python manage.py rebuild_index, I get error message saying connection refused. My Haystack settings in settings.py: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'items', 'TIMEOUT' : 60, }, } The error I'm receiving: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/haystack/management/commands/rebuild_index.py", line 37, in handle call_command('update_index', **options) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/init.py", line 130, in call_command return command.execute(*args, **defaults) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 214, in handle self.update_backend(label, using) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 257, in update_backend commit=self.commit, max_retries=self.max_retries) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/haystack/management/commands/update_index.py", line 84, in do_update backend.update(index, current_qs, commit=commit) File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/haystack/backends/elasticsearch_backend.py", line 190, in update bulk(self.conn, prepped_docs, index=self.index_name, doc_type='modelresult') File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/elasticsearch/helpers/init.py", line 188, in bulk for ok, item in streaming_bulk(client, actions, **kwargs): File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/elasticsearch/helpers/init.py", line 160, in streaming_bulk for result in _process_bulk_chunk(client, bulk_actions, raise_on_exception, raise_on_error, **kwargs): File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/elasticsearch/helpers/init.py", line 89, in _process_bulk_chunk raise e File "/home/hawka/.virtualenvs/django17/lib/python3.5/site-packages/elasticsearch/helpers/init.py", line 85, in _process_bulk_chunk resp = client.bulk('\n'.join(bulk_actions) โฆ -
Need suggestion in making drag and drop django basic crud application
i have already made a basic crud application in django. but this time i want to do in a different way. i have 4 columns , first one is the list of student and each student is draggable. next i have 3 more columns as shown in the image. what i want is when drag a student and drop in whatever the column that event should occur. like when i drop the student in the delete column, student will be deleted and so on. and all the events should happen without refreshing the page. i need a suggestion what approach i use in this. -
django specifc stack trace when running migrations in django.
here are the database tables I have made from __future__ import unicode_literals from django.db import models class Venue(models.Model): name = models.CharField(max_length=100) address = models.ForeignKey('Address', blank=True, related_name='venue', on_delete=models.CASCADE) phone = models.BigIntegerField(blank=True) class Address(models.Model): street1 = models.CharField(max_length=100) street2 = models.CharField(max_length =100) city = models.CharField(max_length = 100) state = models.CharField(max_length = 2, blank =True) zipcode = models.PositiveSmallIntegerField() country = models.CharField(max_length = 100, blank = True) and here is the stacktrace it seems to be django specifc. Anyone see this before? Apply all migrations: admin, auth, contenttypes, sessions, venue Running migrations: Applying venue.0002_auto_20161220_2343...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards field, File "/home/rickus/211hospitality/com.suitsandtables/venv/local/lib/python2.7/site-packages/django/db/backends/postgresql/schema.py", line 21, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) โฆ -
Apps are not loaded yet
File "C:\project\ENV\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't not loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't not loaded yet. when i try to execute the command for the purpose of making my folder for HIP customization arches-app create my_hip_app --app arches_hip in the activated virtual environment it throws above error. can anyone suggest me what should i do to deal with the above error. -
How do you get a field related by OneToOneField and ManyToManyField in Django?
How do you get a field related by OneToOneField and ManyToManyField in Django? For example, class A(models.Model): myfield = models.CharField() as = models.ManyToManyField('self') class B(models.Model): a = models.OneToOneField(A) If I want to get a 'myfield' and all associated 'as' using class B, given a 'myfield' equal to a string like 'example', how is it done? -
Can't launch Celery worker within a Django project
Recently, I started using Celery 4.0.2 with Django 1.9.10 to run some periodic tasks. Basically, I run into two problems even though I followed the steps mentioned in the official documentation: Celery app is not discovering the tasks that are included in every app directory When I manually add the tasks to the Celery App and try to run the worker, I get this error: RuntimeError: Model class core.models.Modl doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS This is how I create the Celery App: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from .scraper import scraper_example os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conf') app = Celery('celery_power', broker=settings.CELERY_BROCKER_URL, backend=settings.CELERY_RESULT_BACKEND, include=['apps.core.tasks']) # app.autodiscover_tasks() in case I don't include the tasks module, # never worked by the way For my tasks.py that I created in the core app directory, I simply import a few models and used them to insert some data, something like this: from .models import Modl from celery import shared_task @shared_task def deal_with_modl(): m = Modl(name="model") m.save() -
<Django : object>, <Django : object> is not JSON serializable
I have a list of fonts that I want to submit throught a multiple checkbox select, and I want to show all the selected checkboxes on another page. When I submit my form I'm getting this error : [<Font: Space Mono>, <Font: Fruktur>] is not JSON serializable How can I submit my form without having this issue ? views.py def step1(request): initial={'fn': request.session.get('fn', None), 'checkbox': request.session.get('checkbox', (False,))} #cookies form = PersonForm(request.POST or None, initial=initial) if request.method == 'POST': if form.is_valid(): request.session['fn'] = form.cleaned_data['fn'] request.session['checkbox'] = form.cleaned_data['checkbox'] #probably this line is wrong, how can I serialize it ? return HttpResponseRedirect(reverse('step2')) return render(request, 'step1.html', {'form': form}) forms.py class CustomChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe('%s' % (obj.font_name)) class PersonForm(forms.ModelForm): checkbox = CustomChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Font.objects.all()) class Meta: model = Person fields = ['fn', 'checkbox'] Any suggestion ? -
After extending User profile to include a Profile model, Django throws UNIQUE Constraint Failed error
I extended the User model to include a profile with the following code: class Profile(models.Model): PTO_TIER_CHOICES = ( (200.0, 'Boss 5-10 Years'), (160.0, 'Boss 2-5 Years'), (120.0, 'Boss 0-2 Years'), (160.0, 'Peon 5-10 Years'), (120.0, 'Peon 2-5 Years'), (90.0, 'Peon 0-2 Years'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) pto_tier = models.FloatField(choices=PTO_TIER_CHOICES, default=90.0) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I also created a LeaveHistory model with a foreign key to the User model with the following code: class LeaveHistory(models.Model): LEAVE_CHOICES = ( (True, 'PTO'), #is chargeable? (False, 'Jury Duty'), #is chargeable? (False, 'Voting'), #is chargeable? (False, 'Military Leave'), #is chargeable? (False, 'Bereavement'), #is chargeable? (True, 'Emergency'), #is chargeable? ) user = models.ForeignKey(User, on_delete=models.CASCADE) leave_start_date = models.DateTimeField(auto_now=False, auto_now_add=False) leave_end_date = models.DateTimeField(auto_now=False, auto_now_add=False) leave_type = models.BooleanField(choices=LEAVE_CHOICES) def __str__(self): return self.user.username The problem that I am having is that whenever I try to create more than one LeaveHistories with the same username I get the following error: Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/leavehistory/add/ Django Version: 1.10.3 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'accounts'] Installed 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'] Traceback: โฆ -
Django: Update multiple objects attributes
Is there a more efficient way of do this maybe with F expressions? Some how to reducing hitting the DB? # 1st way hits DB twice per object def something(): pks = [4, 2, 1, 3, 0] for i in range(len(a)): mymodel.objects.get(pk=a[i]).update(attr=i) # 2nd way hits DB once per obj and once for the queryset def something(): pks = [4, 2, 1, 3, 0] order = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(steps)]) query = TestStep.objects.filter(pk__in=steps).order_by(order) for i in range(len(query)): query[i].order = i query[i].save() -
getting the last object in REST API
I'm working on django web base chatbot application. i want to generate the gender of the user base on the name. this is the java script : function post(name){ var user_info ={ user_name : name}; $.ajax({ type: "POST", url: "http://127.0.0.1:8000/chat/user_api/", data: user_info, }); } function find_gender(){ var user_info = $.parseJSON($.ajax({ type: "GET", url: "http://127.0.0.1:8000/chat/user_api/", dataType: "json", async: false}).responseText); var last = user_info[user_info.length - 1] return last; } function gender_script(uname){ post(uname); $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/chatbot/run_python_gender/', }); var ggender = find_gender(); return ggender; } $('.btn-xl').click(function(){ if(document.getElementById('radio01').checked == false && document.getElementById('radio02').checked == false ){ alert("--ุงุฑุฌูุง ุงูุงุฎุชูุงุฑ--"); } else{ var name = $('.message-input').val(); var gender = gender_script(name); if(gender.user_gender=="M" && document.getElementById('radio01').checked){ window.open('http://127.0.0.1:8000/male_chatbot'); $('.message-input').val(null); document.getElementById('radio01').checked=false;} So far it's going well but the problem is in var gender it doesn't hold the gender of the current user, it hold the gender of the name before that.So if male enters then a female come after him, the var gender = M and it should be F. The same problem in another python script, it takes the second to last item of the lest