Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can one model class have a specific relation with another set of model classes django?
This is my models: class company(models.Model): User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) Name = models.CharField(max_length=50,blank=False) class group(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_Name = models.CharField(max_length=32,unique=True,error_messages={'unique':"This Group Name has already been registered"}) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group') class ledger1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Companys') Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) So these are my models I have created for my accounting application... The company model is connected to group and ledger through foreign key... I want to provide different group and ledgers for different companies which the user have Created... Its just like what we do in django for all users,we need to do something like this for users: filter(User=request.user) Similarly,Can I make something like this for my companies? I mean one company will have different set of group and ledger.. Is it possible in django? If it is Can anyone help me out to solve this... Thank you in advance -
Django: What is Difference between model.objects.all() and model.objects.filter().all()
Hi I was about to clearing my Tables in Django.. When i execute: >> model.objects.all().count() >> 0 but >> model.objects.filter().count() >> 50 What exactly is difference between two? -
Keras Squeezenet on Django - input always shape=(?, 227, 227, 3)
I'm trying to create a django web app which incorporates squeezenet (I am using raspberry type 1 hence, inception is not an option). What I am wondering is, whenever I try my predict commands manually using the python interface, I always get the result I wanted. But, when I deploy it on django views.py, I always encounter an error. Here are my codes: from django.shortcuts import render, redirect from django.conf import settings from django.core.files.storage import FileSystemStorage from uploads.core.models import Document from uploads.core.forms import DocumentForm import os, json from glob import glob import tensorflow.python.keras import tensorflow as tf import time from keras_squeezenet import SqueezeNet from tensorflow.python.keras.models import Model from tensorflow.python.keras.layers import Dense, GlobalAveragePooling2D from tensorflow.python.keras import backend as K from keras.applications.imagenet_utils import preprocess_input, decode_predictions from keras.preprocessing import image import numpy as np tf.keras.backend.clear_session() model = SqueezeNet() def home(request): documents = Document.objects.all() return render(request, 'core/home.html', { 'documents': documents }) def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) img = image.load_img('/home/pi/a/simple-file-upload'+uploaded_file_url, target_size=(227, 227)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) result = decode_predictions(preds) return render(request, 'core/simple_upload.html', { 'uploaded_file_url': uploaded_file_url, 'result' : result }) return … -
Don't change timezone to default during serialization
I want to save user's timezone after serialization to make special date range for queryset. Input data: 2018-09-28T09:06:39.099+0300 print(request.query_params) <QueryDict: {'date': ['2018-09-28T09:06:39.099+0300']}> print(serializer.validated_data, '\n\n', serializer.data) OrderedDict([('date', datetime.datetime(2018, 9, 28, 6, 6, 39, 99000, tzinfo=<UTC>))]) {'date': '2018-09-28T06:06:39.099000Z'} So django transforms aware datetime objects to default timezone before serialization. How can I can get only timezone that was with datetime object or datetime object with user's timezone? -
Django model method for saving values
I'm wondering is it a good practice to have methods in Django model just for setting and saving values? For example I have a model: class Team(models.Model): name = models.CharField(max_length=50) def set_name(self, name): self.name = name self.save() I can set name outside of model like this: team.name = name team.save() Or I can use set_name method: team.set_name(name) In my understanding it is better to use set_name method, because it is loosely coupled. For example if I'll change name of the name field I won't need to update all references to this field in my codebase. -
Django : Key (user_id)=(912) is not present in table "auth_user"
I am trying to write a function that populates dummy test data. This is what I am doing for user in gusers: #gusers contain a bunch of users emp = modelEmployer.objects.create(user=user,employer_image="images/populate/unknown.jpeg") This is the model class modelEmployer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) employer_image = models.ImageField(upload_to='images/', default='') Sometimes when I run this code I get the error Exception Type: IntegrityError Exception Value: insert or update on table "Employer_modelemployer" violates foreign key constraint "Employer_modelemployer_user_id_fabafdeb_fk" DETAIL: Key (user_id)=(912) is not present in table "auth_user". Why am I getting this error randomly ? Any suggestions on how I can fix this ? I am not sure what auth_user table is ? -
Django rounds left 3 digits while displaying bigint in mysql
I am using Django to display rows in mysql. The table in mysql has a primary key which it bigint, and one of them is 871195445245063168, 18 digits. But on my page, I see 871195445245063200 displayed, the least 3 digits are rounded. I am wondering where I make it wrong. 1, I define a class with a function named data_query to query mysql. class MyQuery: self.conn = MySQLdb.connect(host = self.DBHOST, user = self.DBUSER, passwd = self.DBPWD,port = self.DBPORT,charset = self.CHARSET,connect_timeout=3) def data_query(self,sql): cursor = self.conn.cursor(MySQLdb.cursors.DictCursor) start = time.time() cursor.execute(sql) end = time.time() sql_time = end - start column_description = cursor.description column_name = [ column[0] for column in column_description ] res = cursor.fetchall() cursor.close() self.conn.close() return res,column_name,sql_time 2, I defined a json encoder as follows class CJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): try: return obj.strftime('%Y-%m-%d %H:%M:%S') except ValueError: return str(obj) elif isinstance(obj, datetime.date): try: return obj.strftime('%Y-%m-%d') except ValueError: return str(obj) elif isinstance(obj,datetime.timedelta): return str(obj) elif isinstance(obj, decimal.Decimal): return float(obj) elif isinstance(obj,ObjectId): return str(obj) else: return json.JSONEncoder.default(self, obj) 3, I get my display like this, with sensitive info replaced. db = FenqileSqlQuery(host, user, pwd, port) sql_statement = 'select * from mytable where Findex=871195445245063168 limit 10' sql_result, table_column_name, sql_time = db.data_query(sql_statement) query_result … -
What is the syntax of django?
I have this code in django is_partner = models.BooleanField( _('is partner'), default=False, help_text=_('Designates whether the user can access to the UI'), ) what the _('is partner') ? -
Bad Request (400) when try to access the domain without 'www.' django
I have django project in production and i point it with domain name let say for example it is 'www.example.com' when i try to access it with 'example.com' without 'www' it is give me : Bad Request (400) but when i try to access it with 'www.example.com' it works great my settings.py :- ALLOWED_HOSTS = ['www.example.com', '.example.com', 'example.com'] SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True CSRF_COOKIE_SECURE = True X_FRAME_OPTIONS = 'DENY' my nginx-config : server { listen 80; server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/project/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I use nginx, gunicorn and the domain provider is namecheap if you need me to show any other code please tell me. thanks -
Django function working in Chrome,Opera and Microsoft Edge but not in FireFox
I have written a delete function,when user click logout button it triggers ajax call which calls delete function and destroys session.I am saving my session in file. But problem is my code is working fine in different browsers otherthan Firefox, in firefox when i clcik logout button it performs the task but terminate the performance abnormally which out redirecting back to the home page. Logout operation doesnt take me back to the localhost:8000,instead of that it stays in localhost:8000/logout. But same code working fine on other browsers and redirecting back to home page successfully! def logout(request): if request.session.has_key: request.session.delete() else: pass return JsonResponse({'logout':True,'redirect_url': reverse('sanjh:home')}) <script> $(document).ready(function(){ $('#logout-anchor').click(function(event){ console.log('hi-you are logged out') $.ajax({ method: 'GET', url: '/logout', success: function(res) { console.log(res); window.location = res.redirect_url; } }) }) }) </script>] -
Django: product model with multiple variations and pricing
Crux of the problem: One product can have multiple variations with different prices. For example: if a Shirt has 2 color choices (black and white) and 2 size choices (Small and Large), there will be 4 product variants, like below: Shirt - Color: White, Size: Large, Price: $12, Shirt - Color: White, Size: Small, Price: $10, Shirt - Color: Black, Size: Large, Price: $14, Shirt - Color: Black, Size: Small, Price: $10 Below is my model: class Product(models.Model): """ This model holds all common fields of a product """ name = models.CharField(max_length=155) class ProductAttribute(models.Model): """ This model holds the attr_type (ex: color) and attribute_name (ex: red) """ product = models.ForeignKey(Product, on_delete=models.CASCADE) attr_type = models.ForeignKey( VariantType, on_delete=models.PROTECT, blank=True, null=True) attr_name = models.CharField(max_length=155, blank=True) class ProductVariant(models.Model): """ This model holds the values for price and combination of attributes """ product = models.ForeignKey(Product, on_delete=models.CASCADE) variant = models.ManyToManyField(ProductAttribute) sku = models.CharField(max_length=155, blank=True) price = models.DecimalField(max_digits=25, decimal_places=2) I want to know 2 things: I have to save the product attributes first (ProductAttribute model) and then create specific m2m relations in the ProductVariant model. How do I do this? Is there a better option for models than what I have created? -
python site package Error while running manage.py
Is there any other way to install all the site packages or the solution for this type of errors? (env) devbase@bounce:~/devbase/queuearoo$ python manage.py Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/home/devbase/env/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/devbase/env/local/lib/python2.7/site-packages/djorm_pgtrgm/__init__.py", line 1, in <module> from django.db import backend ImportError: cannot import name backend -
Django detailview get_queryset and get_object
I am using django detailview. initially, I used the url pattern url(r'^todo/details/(?P<pk>[\d]+)', views.todoDetailView.as_view(), name='detail_todo'), my view is class todoDetailView(DetailView): model = models.todo It worked fine. In second case my url is url(r'^todo/details/(?P<id>[\d]+)', views.todoDetailView.as_view(), name='detail_todo'), this time, I modified my view to class todoDetailView(DetailView): model = models.todo # context_object_name = 'todo_detail' def get_object(self, **kwargs): print(kwargs) return models.todo.objects.get(id=self.kwargs['id']) It worked fine, I moified the second case to class todoDetailView(DetailView): model = models.todo # context_object_name = 'todo_detail' def get_queryset(self): return models.todo.objects.get(id=self.kwargs['id']) then I get an error, Generic detail view todoDetailView must be called with either an object pk or a slug. I know that there is no proper slug or pk provided. So, initially I added get_object() (it worked) but get_queryset() is not working. What is the difference in thier working ?? And also if a user is getting details only based on slug, I read on stackoverflow that this can be used slug_field = 'param_name' slug_url_kwarg = 'param_name' link - Generic detail view ProfileView must be called with either an object pk or a slug Can anyone explain me actual working of get_object() and get_queryset() (also get_slug_field() if possible) Along with the terms slug_field and slug_url_kwarg Thanks in advance -
Change Model's column attribute
I have an already migrated Django model, which was created this way: operations = [ migrations.CreateModel( name='Victim', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=200)), ('instagram', models.CharField(max_length=254)), ('old_password', models.CharField(blank=True, max_length=200)), ('new_password', models.CharField(blank=True, max_length=200)), ], ), ] But now, I want to make email and instagram attribute Blank=True, but password fields make Blank=False. What is the easiest way to do this: delete and recreate the model (data is not important) or is there a possible way to do this? -
Django and Node together on Heroku - Error R14 (Memory quota exceeded)
I'm working on a SPA + SSR (Universal App) using Django as backend and ReactJS as frontend to have better SEO and Page Speed results compared to just an SPA with the same stack and deployed it on Heroku. Since SSR on React would need a Node server, I followed this guide on Heroku for running Django and Node together which did warn that: "This solution comes with its own set of challenges. Web dynos now face greater resource contention than either a Django or node dyno would on its own. All processes on a dyno share memory, CPU, and a single filesystem, so choose your dyno type with care. " For quite a while, I kept getting Error R14 (Memory quota exceeded) and Error R10 (Boot timeout) on my logs: 2018-09-27T07:35:43.272457+00:00 heroku[web.1]: source=web.1 dyno=heroku.110010347.d0013afc-887b-4913-b983-15871a5c4200 sample#memory_total=323.27MB sample#memory_rss=314.05MB sample#memory_cache=9.22MB sample#memory_swap=0.00MB sample#memory_pgpgin=102968pages sample#memory_pgpgout=20212pages sample#memory_quota=512.00MB 2018-09-27T07:36:04.717690+00:00 heroku[web.1]: source=web.1 dyno=heroku.110010347.d0013afc-887b-4913-b983-15871a5c4200 sample#load_avg_1m=3.10 2018-09-27T07:36:04.717851+00:00 heroku[web.1]: source=web.1 dyno=heroku.110010347.d0013afc-887b-4913-b983-15871a5c4200 sample#memory_total=710.81MB sample#memory_rss=488.09MB sample#memory_cache=0.03MB sample#memory_swap=222.70MB sample#memory_pgpgin=231609pages sample#memory_pgpgout=106651pages sample#memory_quota=512.00MB 2018-09-27T07:36:04.718474+00:00 heroku[web.1]: Process running mem=710M(138.8%) I was about to give up but then suddenly got a bit of hope proceeding with this because restarting the dyno suddenly made it work with below results: 2018-09-27T07:40:21.262437+00:00 heroku[web.1]: State changed from starting to up 2018-09-27T07:40:21.164398+00:00 … -
Django media images not showing in bitnami server with Debug = False on production
I have two files like static files and media files. The static files contain my css,js and other static content. The media files contain uploads. This is my configuration: STUDENT_DIR = os.path.dirname(student.__file__) PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(STUDENT_DIR, 'media') i added url.py file urlpatterns = [ ..... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here dev environment everything working fine and production static files are working fine, issue is production(django bitnami server) media images are not showing i tried giving entire media_root path also if i make DEBUG = True media files working fine but i am not sure why media files are not working in DEBUG = False MEDIA_ROOT = "/opt/bitnami/apps/django/django_projects/epitastudent/student/media" Please help me any one. Thanks in advance ... -
Avoid repopulation of django database
I have a population script which must run the first time that the application is started. Only the first time. The application is running as a docker container. The way I am doing this at the moment is, before starting the django application, the container runs the population scripts. This has the consequence that restart the container runs the population scripts again, causing duplicated entries. What strategy could I use to avoid repopulating the database? I have a couple of ideas: mark in the caontainer filesystem. Very easy to implement, but I am not sure if this will survive a container restart? I have anyway discarded this because it will definitely not survive a container rebuild. mark in the database. This seems too complex to implement, but seems the most robust solution: it will only run whenever the DB is not marked, and it will automatically detect whenever the DB has been scratched. mark in a persistent volume. This is my preferred solution. The only minor problem is that scratching the database will not be detected (but I can manage that manually) Do you have any other idea how to achieve this? -
Django template {{ item.get_FOO_display }} using only jinja2 without django
I use Django. I also use standalone Jinja2 to build email body from django models. I have model with choice field and I would like to get its display value from the model instance. In django template, it is easy, for example: {{ form.get_foo_display }}. However, it does not work if is it outside of the django template. My code using jinja2 is: Trip participation:\t{{ item.get_event_trip_display }} where item is model instance and event_trip is choice field (the {{ item.event_trip }} works ok) However the get_event_trip_display is rendered as: Trip participation: <bound method curry.<locals>._curried of <Registration: John Doe>> Known solutions: Use {% if ... %} block to manually select the choice. Append the instance with new attributes in Python code: item.trip_parictipation_display = item.get_trip_participation_display() My question: Is there simpler way hot to call the function directly in jinja2? (I have a lot of fields like that) -
How to set Jquery Value(it may be input value) to template Variable in Django?
{% with "World" as name %} {{name}} {% endwith %} any one tell me, how to assign input value to django template variable -
Update frontend html page with new message from RabbitMQ queue
I've created a producer in my django server app. It creates the exchange and now I need to create a consumer that can update the frontend web page displaying the new message. I can't do it with django because the library pika is blocking and I can't figure a way out to do this in django. I'm wondering if in javascript, is there a way to listen to the queue and update the DOM when there's new message to consume from the queue? -
Django AttributeError and query does not exist error
Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'relation' Exception Value: Signs matching query does not exist. DJANGO throw these two errors how could i resolve this to show the relation between user and these details models.py class Signs(models.Model): relation = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(null=True, blank=True, max_length=1000, help_text="User Department") mobile = models.CharField(null=True, blank=True, max_length=1000, help_text="User Mobile") def __str__(self): return (self.relation.username).title() class Meta: verbose_name_plural = "Registration Information" class Mycheque(models.Model): related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True) to_pay = models.CharField(max_length=250, null=True, blank=True) amount = models.BigIntegerField(default=0, null=True, blank=True) amount_in_words = models.CharField(max_length=10000, null=True, blank=True) vouchar_no = models.BigIntegerField(default=0, null=True, blank=True) dated = models.DateTimeField(auto_now_add=True, null=True, blank=True) cheque_no = models.BigIntegerField(default=0, null=True, blank=True) cheque_date = models.CharField(max_length=10, null=True, blank=True) account_no = models.BigIntegerField(default=0, null=True, blank=True) def save(self): self.dated = datetime.now() super(Mycheque, self).save() def __str__(self): return (self.related.relation.username).title() class Meta: verbose_name_plural = "Single Cheque Of Users" views.py def mycheque(request): if request.method == "POST": userdata = User.objects.get(username = request.user) user_data = Signs.objects.get(relation_id=userdata.id) if userdata.check_password(passwd) == True: to_p = request.POST['topay'] amnt = request.POST['amount1'] amnt_in_words = request.POST['amount_string'] vouch_no = request.POST['voucharno'] d = request.POST['date'] cheq_no = request.POST['chequeno'] cheq_date = request.POST['chequedate'] acc_no = request.POST['accountno'] single = Mycheque(to_pay=to_p, amount=amnt, amount_in_words=amnt_in_words, vouchar_no=vouch_no, dated=d, cheque_no=cheq_no, cheque_date=cheq_date, account_no=acc_no) single.save() messages.success(request, "Your Cheque is created") else: messages.error(request, "Please Try again...") … -
django2.1 send email fail:ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:833)
I want to send email to myself, so I tried it. I had set my email info in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.163.com' EMAIL_PORT = 25 EMAIL_HOST_USER = '*****@163.com' EMAIL_HOST_PASSWORD = '***' then I write down the example from django document from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) then a exception happened ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:833) How to fix it? -
sorting and searching in django using javascript frontend or python backend
There are existing solutions for sorting and searching both in javascript front end and backend using python for django. While using python, there's some delay less then a second but when using javascript, it is almost instant. I only tested with less than 100 roles using both method. Javascript is faster in this case. However, when there are many thousands of data, what would be the preferred method? -
While running the python manage.py getting this type of error
The django.db.backend is deprecated while running the manage.py .the site packages are not supporting home/devbase/env/local/lib/python2.7/site-packages/django/utils/functional.py:55: RemovedInDjango18Warning: Accessing django.db.backend is deprecated. res = instance.__dict__[self.func.__name__] = self.func(instance) Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/devbase/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute django.setup() File "/home/devbase/env/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup apps.populate(settings.INSTALLED_APPS) File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/devbase/env/local/lib/python2.7/site-packages/django/apps/config.py", line 197, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/devbase/devbase/queuearoo/main/models.py", line 7, in <module> from django_earthdistance.expressions import DistanceExpression ImportError: No module named django_earthdistance.expressions -
Problem with success/redirect URL for ModelForm form_valid() function
I am having a bit of difficulty with overriding the form_valid() method of a CreateView. I have a ModelForm where users can register a new patient. The form is handled by a CreateView. I have overridden the form_valid() method of the view as I first need to assing the user to the patient and then assess whether the details of the patient (i.e. data in the form) meet certain criteria. If the criteria are not met, the patient/form is not saved and the user gets an error message. If they are eligible the patient/form is saved and the user gets a success message. This functionality of the form/view is working - in the test code below I have a boolean 'is_eligible' which I will substitute out for the proper criteria later. When is_eligible == True the model saves and I get a success message, when it == False it does not save and I get the error message. My problem is handling the success url and redirect if the patient isn't eligible. I would like it to go back to a 'dashboard' that I have setup, but each time I do I get a DisallowedRedirect at /dashboard/patients/register Unsafe redirect URL …