Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I implement choice field in django model?
I want to develop a pigeon app in django and my pigeon model has status field. For this I must define another model called Status where to store my statuses. My model class PigeonStatus(models.Model): STATUSES = [ ('Activ', 'Activ'), ('Lost', 'Lost'), ('Dead', 'Dead'), ('For Sale', 'For Sale') ] status = models.CharField(max_length=15, choices=STATUSES, unique=True) in_loft = models.BooleanField('In loft?') def __str__(self): return self.status class Pigeon(models.Model): pigeon_id = models.AutoField(primary_key=True) year = models.CharField(max_length=4, null=False, blank=False) band = models.CharField(max_length=25, null=False, blank=False, unique=True) ... status = models.ForeignKey(PigeonStatus, on_delete=models.CASCADE, null=False, blank=False) My question is how can I set boolean value for every status? I want to query like this: Pigeon.status.in_loft = true. From choices, Activ and For Sale must have in_loft=True and Lost, Dead must have in_loft=False. Does anyone can answer this? Is there another way(better one maybe) to set pigeon status and refer to it later? Thanks! -
Why do I get QuerySet object has no attribute user
I am working on a website using Django, where users can send friend request to another user and I came up with an error on my code. Queryset object has no attribute user. def home(request): p = Profile.objects.exclude(user=request.user) u = p.user sent_request = FriendRequest.objects.filter(from_user=p.user) button_status = 'none' if p not in request.user.profile.friends.all() button_status = 'not_friend' if len(FriendRequest.objects.filter(from_uset=request.user).filter(to_user=p.user)) == 1: button_status='add_request' if len(FriendRequest.objects.filter(from_user=p.user).filter(to_user=request.user)) == 1: button_status='accept_request' -
Setting up CI/CD on Gitlab for django project
This is the first time I've tried adding CI/CD for a Django project on gitlab. I want to set up automatic testing and deploying to the server in the development branch if it is successful. With tests almost everything worked out, dependencies are installed and started python manage.py test but the problem with the testing database. The traceback error is a bit lower and here I don't quite understand how the interaction with the database happens during the tests. Creating test database for alias 'default'... ..... MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main ... super(Connection, self).__init__(*args, **kwargs2) django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") In the settings of django settings.py, a connector to the database is obtained through such variables in a .env file. .env SECRET_KEY=ja-t8ihm#h68rtytii5vw67*o8=o)=tmojpov)9)^$h%9#16v& DEBUG=True DB_NAME=db_name DB_USER=username DB_PASSWORD=dbpass DB_HOST=127.0.0.1 And with the deployment of the project, everything is not clear yet. I'd appreciate your help setting it up. gitlab-ci.yml stages: - test - deploy test: stage: test script: - apt update -qy - … -
How to unit test django application using jena-fuseki?
My django application uses sparql with jena-fuseki RDF-database. How should I run my unit tests as thete's hardly any information in availble for creatig in-memory jena database for a django unittesting ? So far I've been just running a local fuseki-server, but that's not the way unit testing should be done, right ? -
How can i change the currency symbol in the modal of Stripe API , using DJANGO
Can't change the highlighted dollar symbol -
How to correctly separate models into multiple files in Django?
I have one app and one model's file at this point but at the same time I have two databases and the third is upcoming soon. My databases have a few same models and I want to separate them in different files. I saw a few answers here but they are 8 years old. Can someone show it step by step how to do it? I'm using the latest versions of Python and Django as well. -
Multi-tenancy on Django 3.0 with MariaDB and separate databases
We are building a new system on Django 3.0 that requires multi-tenancy with separate databases, and we also intend to use Maria DB. I have already gone through a well-known multi-tenancy solution django-tenant-schemas that offers multi-tenancy with single PostgreSQL database and multiple schemas - so that doesn't solve our problem (Django 3.0 + Maria DB & multiple databases). From what I have understood, it is non-trivial to make changes in Django ORM to change the DB, so I am looking for some other solution. How can I have multi-tenancy with DJango 3.0 if we want to use multiple database with Maria DB? -
two foreign keys in one django model
i'm working on a project the scenario : teacher model then is the teacher has not a profile the institute which working at will upload the courses does this is write way i have tried in the course model? class Course(models.Model): course_name = models.CharField(max_length=20) student = models.ManyToMany(Student) institute_name = models.ForeignKey(Institute,on_delete=models.CASCADE , null=True,blank=True) teacher_name = models.ForeignKey(Teacher ,on_delete=models.CASCADE,blank=True,null=True) tags = models.ManyToManyField(Category,on_delete=models.CASCADE) time = models.DateTimeField(auto_now=True) update = models.DateTimeField(auto_now_add=True) then define if user loggedin in user.is_institute so querying on institute if loggedin in user.teacher then will work on teacher model ! does this structure fork fine ? i know generic foreign keys from django.contrib.contenttypes.models import ContentType but i've hear this will not work with API django:2.2 -
Unable to delete django background tasks
We use django-background-tasks in our application and I have had no issue with deleting tasks from the admin page when running the app in my system. But when I tried to delete some tasks from the production version (hosted with gcp), I keep getting internal server (500) errors. What could be the reason for this? Alternately, is it advisable/safe to directly delete the tasks from the background_task table in the database? -
django distinct in template by filter
I need to display unique values in template. I know distinct will work in query. But table in one row Many to Many field I don't know how to implement for that. If any possibilities are there to use it in template class DoctorFeedback(models.Model): visited_for = models.CharField(max_length=200) tag = models.ManyToManyField(Tags) class Tags(models.Model): tag_title = models.CharField(max_length=50) -
Can I connect my model to an external app?
I've installed a new app thorough pip (it's called django-sitetree). I want to know if I can connect my models (like Category model) to this app with Foreignkey our something else? -
How can I check whether a person is included in a model to make a Job/Post
I have created a School System-like system, that creates a job and sends them to employees/users. I'm almost done making this system however I can't seem to know what do to check if the user is included in the manager model that I created to create a job.. Also, how can a user just see all their job that was assigned to them. All I know is to use objects.allbut that might only seem to show all of the jobs that was posted, I just want the user to see the job included to them. Here is my model.py: from django.db import models from profiles.models import User # Create your models here. class Points (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png',upload_to='profile_pics') def __str__(self): return f'{self.user.username}Profile' class Manager (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Member (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Job (models.Model): manager = models.OneToOneField(Manager, on_delete=models.CASCADE) member = models.OneToOneField(Member, on_delete=models.CASCADE) title = models.CharField(max_length=30, blank=False, null=False) description = models.TextField() datePosted = models.DateTimeField (auto_now = True) … -
How to add unique_together constraint to a Django table with prior data
I am trying to implement a unique_together constraint on one of the models in my Django project. The decision to have a unique constraint was taken after test data was already created in the table. Now while running migrations, I came across the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: movt_frt.frt_group_id, movt_frt.rec_loc_id, movt_frt.dis_loc_id I have tried creating similar unique constraints on table that previously held no data and migrations happened successfully. My question is: Am I right in concluding that the Migration is failing because the table already has data residing in it? Is there a way to do some changes to the migration file on the lines as discussed here and attempt migration again, to run successfully? I am using Django ver. 2.0.6 -
cant use django with mysql db
i have been search for answers on line on how to install mysqlclient but no answer was useful, please does this means i cant work with Django_mysql, because i have downloaded mysql_connector downloaded windows build tools just mention it and still having this error: Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\ecel\envs\mydjango\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\ECEL\AppData\Local\Temp\pip-wheel-o49c3slt' cwd: C:\Users\ECEL\AppData\Local\Temp\pip-install-rkn3bzqg\mysqlclient\ Complete output (24 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb -
Is it OK that change autofield data type in mysql regardless of django field definition?
Is it OK that I change data type in mysql differently from django? For example, I want to change Django model 'int' data type of ID autofield to 'tinyint' by mysql command. Is there not issue for future programming? the reason that I want to change data type is the model has only 24 row and data is no longer likely to be added to the model. so, Is it ok to change 'int' data type to 'tinyint'? -
ImportError: No module named wmicodes.makes
I am trying to setup my project in django and the folder structure seems to be fine. However upon running the command python manage.py runserver I get a ImportError: No module named wmicodes.makes. So i went into the traceback and found out a few files which led me to it. here are the files. myfolder/myfolder/somename/models/base.py #other imports from wmicodes.makes import InternalMake # i get the error on this particular line #other imports '''The rest of the code''' here's another file myfolder/myfolder/somename/models/init.py from .base import * #other imports and here's the traceback: Traceback (most recent call last): File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/mayureshkadam/Desktop/myfolder/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, 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/mayureshkadam/Desktop/myfolder/myfolder/somename/models/__init__.py", line 1, in <module> from .base import * File "/home/mayureshkadam/Desktop/myfolder/myfolder/somename/models/base.py", line 20, in <module> from wmicodes.makes import InternalMake ImportError: No module named wmicodes.makes I tried finding the error however failed. any pointers would be of help. thanks! -
Django - Is there a better way to send bulk Twilio text messages?
I'm currently using the following views.py function sendsmss to allow a user to do a bulk sms message to their list of subscribers, after the user has completed an html form with the sms they want to send to their subscribers: def sendsmss(request): if request.method == "POST": subscribers = Subscriber.objects.all() sms = request.POST['sms'] mytwilionum = "+13421234567" ACCOUNT_SID = TWILIO_ACCOUNT_SID AUTH_TOKEN = TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) for subscriber in subscribers: subscriber_num = subscriber.phone_number client.messages.create( to= subscriber_num, from_=mytwilionum, body=sms ) return redirect('homepage') This function works, but I have only tested the bulk send with 3 subscribers. If there were 100s or 1000s of subscribers how long would this take .. if it takes long then would user be waiting for task to complete before redirect to homepage happens? Is there a better way to do this in Django? -
How to populate table after button click in django template?
I want to insert the values in the input field from the dictionary using DTL. Here's the snippet of code that on load page, making invisible this code tag in the table (may be because of if condition turns False) but just after data submission from dictionary, showing inserted value in the same tag. How can I make it work and remains all the td tags visible on the page load as well? Also since my data.items having 6 keys, so its iterating 6 times, I just want to get single time. I know I'm not very clear but sorry I can't post the whole code since is too big and confidential. Please Help it out, I'm totally new in django. Thanks. .... ... .. {% for key, value in data.items %} {% for key2,value2 in value.items %} <tr class="info"> <td>1</td> <td>Cholesterol -HDL</td> <td> {% if value2.test_name == "Cholesterol -HDL" %} <div class="form-group"> <input type="text" class="form-control" name="cholesterol_hdl_result" value="{{ value2.results }}"> </div> </td> <td><div class="form-group"> <input type="text" class="form-control" name="cholesterol_hdl_uom" value="{{ value2.units }}"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="40.00" name="cholesterol_hdl_lr"> </div></td> <td><div class="form-group"> <input type="text" class="form-control" value="60.00" name="cholesterol_hdl_hr"> </div></td> {% endif %} </tr> {% endfor %} {% endfor %} .. ... … -
Auto suggestion?
I am working on chat bot(Front end: Angular,Back end: Django). I am thinking to add a feature in my chat bot i.e Auto suggestion like when the user comes to the chat bot and when user starts typing What then I need to get all the auto questions which starts with What which I have prepared the question(for ex: similar to google search).I am doing chat bot in manual process(rule- based process) i.e when the user asks the relevant questions then only I would get the output. So can you suggest me how should I do, I don't have any basic knowledge on auto suggestion or auto completion. And say me the approach. like where do I need to keep the questions(in front end or back end).If front end then what is the approach and in back end then what will be the approach.. Please suggest me the approach which would be better. -
Django Host name for an ip address
i have an ip address say x.x.x.x:8080 ,how can i mask this ip address and run as labview.net:8080 so that ip address cannot be exposed to the users.Can any one please explain the steps to be followed? -
Multiple databases routers Django
Dummy Task: Multi DB Router Requirements: 1) Databases: PostgreSQL DB and My SQL DB. 2) Django 1.10 with Python. 3) The multi-setting for local and production environments. 4) Proper Readme file with setup instructions. Description: - Project has 2 roles Admin and User - PostgreSQL has 2 database: database1, database2 - My SQL has 3 database: database3, database4, database5 You need to create a Django application where admin can add users and assign multiple databases (database1, database2, database3, database4, database5 ) to a user and when the user is created, he should get Email for login and password(or any other way to handle this flow). When the user performs login, he can see the database list, which admin assigned to him. Then a user can create a Product by selecting the database from the List. The product should be saved under the selected database. There should be one page where the user can see all product list with the database name. Admin has one page, where he can see all users and their product details. (CRUD operation should follow by default.) -
Django Fernet Fields : InvalidToken at / No exception message supplied
I am running a website using Django . The error i am getting is below: raise InvalidToken cryptography.fernet.InvalidToken`in fernet.py When i login to the ip: 127.0.0.1:8000, i am getting like this :`InvalidToken at / No exception message supplied What am i missing?` -
Combine the results while querying in Django
I am struggling to querying in Django as expected.I have multiple models that are Profile, Education, Address and Social Media. Education, Address and Social Media and related with Profile by foreign key and OnoToOne relation. I want the query results that list of profiles and each profile should contain relevant educations (as list), addresses (as list) and social media (as dictionary). This is my models.py from django.db import models class ORMProfile(models.Model): profile_photo = models.URLField(blank=True, null=True) cover_photo = models.URLField(blank=True, null=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) bio = models.TextField(blank=True, null=True) gender = models.CharField(max_length=120, blank=True, null=True) dob = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMEducation(models.Model): profile = models.ForeignKey(ORMProfile, on_delete=True) school_name = models.CharField(max_length=255, blank=True, null=True) school_type = models.CharField(max_length=255, blank=True, null=True) qualification = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMSocialMedia(models.Model): profile = models.OneToOneField(ORMProfile, on_delete=True) linked_in = models.URLField(blank=True, null=True) facebook = models.URLField(blank=True, null=True) twitter = models.URLField(blank=True, null=True) instagram = models.URLField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class ORMAddress(models.Model): profile = models.ForeignKey(ORMProfile, on_delete=True) street = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, … -
Django: 'QuerySet' object has no attribute 'serialize'
models.py class UpdateQuerySet(models.QuerySet): def serialize(self): qs = self return serialize('json', qs, fields=('user', 'content', 'image')) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Tools_booked(models.Model): auto_increment_id = models.AutoField(primary_key=True) user=models.ForeignKey(Profile, on_delete=models.CASCADE) component = models.CharField(max_length=30, blank=True) booked = models.DateTimeField(auto_now_add=True,blank=True) objects = UpdateManager() def __str__(self): return self.component def serialize(self): return serialize("json", [self], fields=['auto_increment_id','user','component','booked']) in views.py from django.core.serializers import serialize class SerializedDetialView(View): def get(self, request, *args, **kwargs): obj = Tools_booked.objects.get(auto_increment_id=1) json_data = obj.serialize() return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): qs = Tools_booked.objects.all() json_data = qs.serialize() return HttpResponse(json_data, content_type='application/json') I have seen the similar question, it is solved with a new class view. But why this code is not working. The error it showing for SerializedListView and SerializedDetialView urls is 'QuerySet' object has no attribute 'serialize' and 'Tools_booked' object has no attribute 'serialize' Why this error exist and how can we solve this error without creating a new class. -
Django pages accessible through passphrases
(Reposted as my first post was worded incorrectly) Hi, I have a Django website up which currently supports login authentication and posts, however, I want to make a second-layer of authentication. I want to know if there is a way that seperate from user authentication, I could have passcode protected pages. For example, a post could be generated on a hidden page, the only way this page is accessible is if a logged in user enters a passcode into a form. So the user would log in, go to /passform and be greeted by a text input field, once they enter a code which correlates to a post ( for example post1 has a secret passcode of "abc123" ) if the code matches a post it would re-direct them to said page, and, if the code does not correlate it would just error out. Is there a way to do this within Django or should I be using queries for this? ( for this example I'm also assuming my create post has a function to enter a passphrase in the same way you would enter a title ect so it would be stored in the same database. ) Many thanks …