Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have wordpress site and django application on the same domain or integrate them
I have a wordpress site "example.com" and is live I have created an application in Django Now i want to integrate Django with wordpress. Like example.com/djangoapp should starts the django application and I can come back to the wordpress again. So is it possible or what is the recommended way to do this. -
Django: How to sort a table presented in the front end by one particular column
I have a data model like this: class Task(models.Model): task_id = models.IntegerField(null=True) uptime = models.DateTimeField(auto_now=True) The template is: <table cellpadding="0" cellspacing="0" border="0" class="display dataTable" id="list"> <thead> <tr> <th>Id</th> <th>Uptime</th> </tr> </thead> <tbody> {% for task in tasks|dictsortreversed:"uptime" %} <tr> <td>{{task.id}}</td> <td>{{task.uptime}}</td> </tr> {% endfor %} </tbody> And I wish the table presented in the front end to be sorted by the uptime. I have tried dictsort. But it didn't work. Now, if I click on the title of Uptime, it seems that the table treated data in this column as string and sorted the rows in alphabetical order Question is: How to sort this table by the time in the Uptime field -
Django tests for Views
Below is part of my code in views.py @login_required @model_object_required(Unit) @unit_permissions_required(lambda uu: uu.create) def audit_log(request) -> HttpResponse: """ Audit Log - Events recorded in the unit. People with create permission can view this. """ log = AuditLog.objects.filter(unit=request.unit).order_by('-date', '-id') log_count = log.count() context = { "unit": request.unit, "audit_log": log, "audit_log_count": log_count, } return render(request, 'decentmark/audit_log.html', context) Can anyone help me how to write tests for views in Django. -
How to modify settings.py to use cloud datastore in Django 2.1 and Python 3
I want to use google cloud datastore in my Django project. I am lost. I have two scenarios. 1) Running google cloud datastore with production database 2) Running google cloud datastore emulator I have to use different databases for different apps. Like I am using mysql for the following apps. My settings.py looks like: if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/connectionnanme', 'NAME': 'db name', 'USER': 'user', 'PASSWORD': 'pass', } } else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3307', 'NAME': 'db name', 'USER': 'user', 'PASSWORD': 'pass', } } Now I do not know how to configure my settings.py file in order to query my datastore in both cases. Plus any other thing I need to configure it? Kindly share your knowledge or any helpful articles. Thanks. -
In Django Can i call a view function of App1 from url.py of App2?
App1: url.py, view.py App2: url.py view.py Can i call a view function of App1 from url.py of App2 ? -
Session Id changes in Django POST response
While doing a POST request we've noticed that the user and data were changed. in the dev tools we saw the the session_id that came back from the server was different from the request. What can cause such a behavior? we are using Django 1.6 -
Opening Specific Webpages after a certain time interval in Django
I cannot find out a way through which I can link webpage in django that can open automatically after a specific tie interval.. Using the javascript function of "window.location" is of no use when the site server is remotely opened as when this script gets called Django Server returns an error of URL not found. So can anyone help me how to add URLPattern in my urls.py file so that this error can be resolved?? -
Circular Imports Motivation
I have a problem understanding why Django doesn't allow circular imports. Is there any way around it without using apps.get_model and then hardcoding the label and name of the model? Supposing I have 2 models A and B where A has a FK to B and B has some properties based on A. model A from main import B field = models.ForeignKey(B, default=None) model B # from main import A // this does not work @property def last_used(self): A = apps.get_model(app_label='main', model_name= 'A') The only way to go around it is the code above, if i try to import A and use A.objects.filter I get ImportError: cannot import nameerror. My problem is when I refactor the code, it becomes a hassle to look for all those hardcoded model names. Is this a bad design and I should completely change the logic behind my models? -
import error when organizing django models in sperate files
Following the django docu I wanted to seperate my models into different files model1.py and model2.py. I also imported both of them in the __init__.py. But because they have a relationship, I need to import each of them in the other file. Now I get an error for from .model1 import Model1 that says ImportError: cannot import name 'Model1' is there a problem because I want to import within model2.py a class from model1.py that itself is importing from model2.py? You might say, separating each model in a different file is normally not done in django. But I think it would be much better arranged when you have one file for one model. -
Django first app from . import views issue
I'm learning Django by using the Writing your first Django app documentation from the site. Everything will run fine until I add the polls section and I believe the issue is from the line: "from . import views" As the image below shows the '.' seems to have a value although it doesn't in the documentation. polls code I'm using Python 3.7 and Django 2.1.2, could an updated version of either affect this? Here is error I get from trying to run the server: Error output Any help would be greatly appreciated! -
What is the concrete purpose of reverting migrations in Django, and is it safe to work without?
In our Django project, we already generally implement the reverse_func in order to be able to roll-back migrations. class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(forwards_func, reverse_func), ] We do it because of some team member did it with previous projects, without really questioning the need for that. However with the time, it seems that we never use the rollback mechanism. Our DB is a volume of a Docker container. When we switch on a different branch, we generally replace the volume with a precedent dev version, so that we reapply only the latest migrations. My question is therefore: Did we mistunderstood the purpose of the reverse_func ? - What is the purpose for it in dev ? - What is the purpose for it in prod ? And is it safe to work without them ? -
django 2 not able to load env variables from the .env file to setting.py file
I tried to load environment variables from a file named .env to settings.py file here i created the .env file and settings file same folder. this is my .env file DEBUG=on SECRET_KEY=ksmdfw3324@#jefm DATABASE_URL=psql://urser:un-githubbedpassword@127.0.0.1:8458/database SQLITE_URL=sqlite:///my-local-sqlite.db CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213 REDIS_URL=rediscache://127.0.0.1:6379/1? client_class=django_redis.client.DefaultClient&password=ungithubbed-secret MYSQL_DATABASE = student MYSQL_USERNAME = root SECRET_KEY=secret-key this is my setting.py file import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # Accessing variables. dbname = os.getenv('MYSQL_DATABASE') secret_key = os.getenv('SECRET_KEY') # Using variables. print(dabname) print(secret_key) i installed pip install -U python-dotenv Issue is i am not able to get environment variable inside settings file while trying python manage.py runserver i am getting this error C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\dotenv\main.py:65: UserWarning: File doesn't exist warnings.warn("File doesn't exist {}".format(self.dotenv_path)) Traceback (most recent call last): File "manage.py", line 28, in <module> execute_from_command_line(sys.argv) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36- 32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File … -
Django 2.1 annotate count of child and grand child
I want to count how many child and grandchild each record has. These are my table structures bellow: Records: id | name 1 | record 1 Posts: id | record | title 1 | record 1 | title 1 2 | record 1 | title 2 Attachments: id | post | name 1 | post 1 | name 1 2 | post 1 | name 2 3 | post 2 | name 3 so by this example record 1 should have children: 2 grandchildren: 3 total_links: 5 Here's my current code in my view.py: records = Record.ojects.all().annotate(total_links=Count('post__id')) -
how to give different name for database other than PostgreSQL in Jenkins + Docker
In server while deploying any project I want to give different database name in settings.py on django structure.Where I have to change database name?? My docker-compose.yml file as following.. version: '3' services: db: image: postgres web: build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db my database configuration is like this in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Where I have to change database name?? -
django: how to manage settings.py file and also safe gaurd information on git
I am not worried of environments like local, production etc. But i want to see that settings.py is safe when i commit it using git I found one common solution of local_settings.py and later import it in the settings.py But then we cant have all settings.py at one place. what is the recommended way. -
session_id doesn't granted on online, but locally he works.
I'm facing the same problem as in link below. I can't see solution for this problem. Python/Django and sessions problems Locally I can set 2 cookies ( CSRF token and session_id ) But online Session_id is never set. I can't find what the problem is... Maybe anyone knows what the problem is. The site works online, there is a homepage, CSRF token is set and I tried to log in, It never works, it returned to wrong page, but same web app on local server (192.0.1.1) he works fine. Maybe PERPO have solution for this problem, It looks a similar problem? maybe there is a problem with the web server? Thanks for answering my question -
Django - latest object for each object in queryset
class Order(models.Model): # ..fields user = models.ForeignKey(User, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) I want to fetch all users, and for each user to add its latest order - e.g the Order of the user where date_added is maximum. A user can have many orders. This is what I've tried: users = User.objects.all().annotate(last_order=Max('order__date_added')) But this only gives me the date of the last order, and I want the Order object itself. -
Django: Admin list_filter getting too long
The change_list view of my model looks like this: The list_filter at the right side is getting too long and unusable. Is there a way to get a more useable way to filter the change_list view of Django? -
How to get decoded url to download a file on Django?
URL='http://localhost:8765/app/download/?file=/path/to/download/my%3Afolder/file_signed_django.xml' I'd like to know how to deal with this URL, i'm trying to download this file (Signed by Django), the problem is when it changes ':' to '%3A', don't know how to get rid of it, i'm using Django 1.9.13 Thank you so much -
django viewset extends mixins.UpdateModelMixin but postman updates model by patch method returns ' detail: Method PATCH not allowed'
viewset code class UserTitleViewset(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = UserTitleMod.objects.all() serializer_class = UserTitleSerializer def update(self, request, *args, **kwargs): return "ok" def perform_update(self, serializer): return "ok" settings.py CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ] I have tried many times but it's still not working. Thank you for your reply. -
how to create validator for lowercase user in Django 2.0?
my site is up and running. However, silly me I didnt put in a validator to check if users and username can only be in lower-case (I only realised that DJANGO allowed capitalized Users and usernames). Although, I have put up a warning but users usually ignore that still write upper case letters or alteast capitalized letters in their signup forms. I then encounter the problem of slugs not working, thereafter I have to manually change their usernames. I do not want to change the behavior of slugs and instead can I please ask for help from someone in changing my views? I have tried .lower() .format() as well and it didnt work. I am very weak on validators. forms.py from django.contrib.auth.models import User from django import forms from captcha.fields import CaptchaField class SignUpForm(forms.ModelForm): captcha = CaptchaField() password = forms.CharField(max_length= 15, widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.views import generic from django.views.generic import View from home.forms import SignUpForm class SignUpFormView(View): form_class = SignUpForm template_name = 'home/signup.html' #if there is no sign up yet def get(self,request): form = self.form_class(None) return … -
Django how to render a queryset within a list to html
I am trying to pass multiple querysets that I can use in rendering HT context['date']=today_date context['doctor_list']=doctor_list context['appointment_list']= all_data_doctor context['slots'] = slots return(context) I am able to parse all context components (date, doctor_list and slots) except appointment_list because it is a list with a queryset within it. Here is an example ['', '', '', '', <QuerySet [{'first_name': 'Emily', 'last_name': 'Johns'}]>, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] Here is what I am doing but does not seem to work. <tbody> {% for appt in appointment_list %} <tr> {% if appt %} <td>{{ appt.first_name }} {{ appt.last_name }}</td> {% else %} <td> Empty </td> {% endif %} </tr> {% endfor %} </tbody> What could be the problem? And also, is this a good way to do it? Thanks -
Creating excell file with Django workbook and worksheet
I am trying to create excell report with django workbook and workseet as below. def print_assistant_notes(request): if request.method == 'GET': notes = AssistantNotes.objects.filter(notedate=datetime.today().date()).order_by("time") workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "assistant_notes.xlsx")) worksheet = workbook.active title_cell = worksheet["A%d" % (1,)] title_cell.value = "Assistant Notes [ "+str(datetime.today().date())+" ] " row = 3 for note in notes: time_cell = worksheet["A%d" % (row,)] category_cell = worksheet["B%d" % (row,)] note_cell = worksheet["C%d" % (row,)] time_cell.value = note.time category_cell.value = note.categories note_cell.value = note.dailynote row = row + 1 tmp_file = tempfile.NamedTemporaryFile() workbook.save(tmp_file.name) response = HttpResponse(smart_str(tmp_file.read()), content_type='application/vnd.ms-excel') response["Content-Disposition"] = 'attachment; filename="assistant_notes.xlsx"' return response When i print report i get excell report as below in red color data. But i want it to be formatted as blue colored format. Because notes colum does not fit in print area as i mentioned it with blue arrow. So i can say that my codes are generating report as the red part. But i want it to fit in the printable area in blue part. So i want to be able to set cell sizes. And text will fit in that cell size left to right. Up to down cell size will be dynamic as text size may change. -
How to send html mail with mailchimp using python
I am trying send promotional mails to the users using mailchimp for my django application.I have created campaign and list.Now I want to add html template to the campaign through api.I can do this by the send_mail function in Django. But I want to send as promotional email via mailchimp Is there any way to do it ? -
How to exclude a string from capturing url pattern "named groups" Django
I am trying to make urls pattern to catch all urls from root. my main urls.py is: path('', (include('myapp.urls', namespace='app1') I am using two url patterns in app1.urls: re_path(r'^(?P<url_var1>[-\w./]+)/$', DetailView1.as_view(), name='DetailView1'), re_path(r'^(?P<url_var2>[-\w./]+)/$', DetailView2.as_view(), name='DetailView2'), My views.py file is as: class DetailView1(View): template_name = 'detail.html' def get(self, request, url_var1): obj1 = model1.objects.get(my_url=url_var1) return render(request, self.template_name, {'obj1':obj1}) class DetailView2(View): template_name = 'detail.html' def get(self, request, url_var2): obj2 = model2.objects.get(my_url=url_var2) return render(request, self.template_name, {'obj2':obj2}) when i request url "/first-post/my-first-post/", It checks out the url which is in my "model1" under ther header "my_url" and return the page. But when I request url "/second-post/my-second-post/", It checks out the url in "model1" and throws an error, as the url is in "model2" under header "my_url". I know that the urlpattern follows a squence check, and stops at the pattern which matches the first urlpattern(DetailView1), thats why It is giving me this error. I want to know is there a way I can override this behavior of urlpattern. I have also tried reverse, when url is not found in DetailView1: try: obj1 = model1.objects.get(my_url=url_var1) except: return reverse('app1:DetailView2') But Its still giving me an error. If any of you got any other suggestions for catching urlpattern from …