Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
join and aggregate using django orm
I have two tables user and purchase purchase table has columns user purchase_total and user table has columns userid and username In here i want to do inner join to find the total purchase for each user I need to how do I do the inner join between user and purchase and aggregate to find the total purchase for each given user. using django ORM Query below is the query i have that would do this type of join: select user.* sum(purchase_total) AS total purchase from user inner join purchase on purchase.id = user.id How do I create a django orm query using this. -
Effect of translate google translate
I work on a number convector, the essence of the problem is that there are two fields, one for input and the other for reading only. I would like to make the server process real time, but for now I only thought of a button. Tell me what options there are. I use Django 2.2 -
How to get list of all objects of logged in user's here in django?
I tried getting the list of objects from the current logged users. There something missing in the codes. I wrote a class-based view as well as function-based views. Class-based views give an error like 1 positional argument but two were given. And in function-based view it giving only first item instead looping through it. I want to show the pass investments inventory record of each investor. Thank you! views.py (Function-Based Views) def InvestmentListView(request): investors = Investment.objects.all(id=request.user.id) args = {'investors':investors} return render(request, 'investors/myinvest.html', args) This only retrieving an only first item. views.py (class-Based viewa) class InvestmentListView(ListView): model = Investment template_name = 'investors/myinvest.html' context_object_name = 'total_invested_by_user' def get_queryset(self): return Investment.objects.filter(investor=self.request.user.id) This CBV gives an error like 1 positional argument, but 2 were given. myinvest.html <div class="container"> {% if user.is_authenticated %} <h2>Investor Name: {{ request.user }}</h2> <table> <tr> <th>Amount Invested</th> <th>Date</th> <th>Rate Of Interest</th> <th>Return</th> <th>Profit</th> </tr> <tr> {% for invest in investors %} <th>{{ invest.amount }}</th> <th>{{ invest.timestamp }}</th> <th>{{ invest.rate }}</th> <th>None</th> <th>None</th> {% endfor %} </tr> </table> {% endif %} Here, models.py class Investor(models.Model): name = models.CharField(max_length=99) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Investment(models.Model): amount = models.FloatField(blank=False) rate = models.FloatField(blank=False) timestamp = models.DateField(default=datetime.now) investor = models.ForeignKey(Investor, on_delete=models.CASCADE) … -
Django:In this situation, how can I migrate? migrate is not working
First, the existing model is in '0001_initial.py'. After adding the 'models' I added, and when I did 'makemigrations', It's going into '0002_xxx.py'. I succeeded in Migrate, and there was no problem with the database. And then when these 'models' were added, I wanted to put the initial data into the database. so I made fixture folder for putting in initial data after make migrations. I put the json file in it. However, when I changed the name of 'model' and did 'makemigrations' again, I had an error finding the table. So I went directly to sqlite and erased all the tables on the new models. Then I did makemigrations. After that, python3 manage.py migrate sbimage When I do 'migrate' here like this, django.db.utils.OperationalError: table "sbimage_camerathreshold" already exists There's an error like this. python3 manage.py migrate sbimage --fake This has made both 0001, 0002 'FAKED'. It's my 0002 file was created after 'makemigrations'. from django.db import migrations, models def load_my_initial_data(apps, schema_editor): call_command("loaddata", "addition.json") class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.CreateModel( name='AuthNumberT', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_t', models.CharField(max_length=64)), ], ), migrations.CreateModel( name='Claimant', fields=[ … -
How to do INNER JOIN to another queryset/query
I have a problem with Django ORM. I have a model Weather: class Weather(models.Model): city = models.ForeignKey(City, verbose_name='Город', on_delete=models.CASCADE) temperature = models.FloatField('Температура') source = models.CharField('Источник', max_length=100) date = models.DateTimeField('Дата и время') I want to get actual weather from every source for every city. I created sql query for that but I don't understand how to do it with Django ORM. Query: SELECT * FROM api_weather t1 INNER JOIN ( SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source ) t2 ON t1.city_id = t2.city_id AND t1.source = t2.source AND t1.date = t2.latest_date I realized how to do SELECT MAX(date) AS latest_date, city_id, source FROM api_weather WHERE date<='2019-07-04 15:50' GROUP BY city_id, source with Django ORM, it's Weather.objects.filter(date__lte=datetime.datetime.now()).values('city_id', 'source').annotate(latest_date=Max('date')) but I don't understand how to do INNER JOIN from model Weather to this query. -
pip install mysqlclient installation error in django
when I'm trying to install mysqlclient i faced this problem.How can i fix this error C:\Users\santhoshe.e\loginpro>pip install mysqlclient==1.3.12 Collecting mysqlclient==1.3.12 Downloading https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz (89kB) |████████████████████████████████| 92kB 590kB/s Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Complete output from command 'c:\users\santhoshe.e\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-record-fqec09fa\install-record.txt' --single-version-externally-managed --compile: ERROR: running install running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command "'c:\users\santhoshe.e\appdata\local\programs\python\python37-32\python.exe' -u -c 'import setuptools, tokenize;file='"'"'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-record-fqec09fa\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\SANTHO~1.E\AppData\Local\Temp\pip-install-v3kt5jg5\mysqlclient\ -
Django 2.2:App registry error in django.Tried every solution available but none of the methods worked available on the internet.
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. checked all INSTALLED_APPS in settings.py registered models,apps.py. Earlier this error was not coming when i was working with core and users applications under the same project. settings.py """ Django settings for jam project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'bj))qqcyggizpqmxp9zru$pb%m@bt0--_z%$@z6!xz^$ij3#^@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition #All applications are working INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'core.apps.CoreConfig', 'users.apps.UsersConfig', 'crispy_forms', ] 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', ] ROOT_URLCONF = 'jam.urls' 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.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'jam.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } … -
Django Custom Management Script: Deleting all migrations and database in one single command
I am trying to write a management script for django polling app.. the command should delete all the migrations and pycache, and dbfile so that i can start out again later new with new migrations.... my file is management/commands/removemigrations.py below: from django.core.management.base import BaseCommand, CommandError from polls.models import Question as Poll class Command(BaseCommand): help = 'Delete migrations, pycache, dbfile, and all unwanted file' def add_arguments(self, parser): def handle(self, *args, **options): I am very new in django, can anyone help me to craft this script? I am very new.. Thanks -
Limiting choice to Foreign key
I have a model which had a self relationship Foreign key and a Foreign key, I want to use limit_choices_to = self.parent = parent. But its not working, i tried different things but cant get any to work class State(models.Model): workflow = models.ForeignKey(Workflow, on_delete=models.CASCADE, null=True, blank=True) level = models.IntegerField() name = models.CharField(max_length=100) next_level = models.ForeignKey('flow.State', on_delete=models.CASCADE, related_name='get_next_level', blank=True, null=True, limit_choices_to=(Q(workflow_id=workflow))) return_level = models.ForeignKey('flow.State', on_delete=models.CASCADE, related_name='get_return_level', blank=True, null=True) approver = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) -
How change the password of another user
I'm constructing site by Django. I'm setting some authentications in this site, like Site Manager, Group Manager and Normal User. When System Manager or Group Manager logged in, they could change the password of Normal Users as a part of system management. In django, PasswordChangeForm or SetPasswordForm provide some user password change form. I think these forms are for changing password of users themselves. Yes, I need that too. But I also need the form of changing th password of another users like django admin site. How can I construct the form ? I read the code of django's admin site. I found AdminPasswordChangeForm, can I use this class ? forms.py class MyAdminPasswordChangeForm(AdminPasswordChangeForm): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(user, *args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' views.py class PasswordChange(PasswordChangeView): form_class = MyAdminPasswordChangeForm success_url = reverse_lazy('password_change_done') template_name = 'accounts/password_change/password_admin_change.html' def get(self, request, *args, **kwargs): if 'user_id' in self.request.session: user = User.objects.get(id=self.request.session['user_id']) form_class = self.get_form_class() form = form_class(user=user) return self.render_to_response(self.get_context_data()) def get_form_class(self): return self.form_class -
Uploading video from admin panel [django]
I have a problem in uploading video from admin panel - when i loop video like src='{{uploading.video.url}}' it gives nothing and I have another problem that when I make a form in HTML file and make user upload the video file or any another file [not image] and save it in my database and when I loop it gives me no else enter image description here -
Filter across three tables using django ORM
I have 3 django models, where the second has a foreign key to the first, and the third has a foreign key to the first. Like this: NewRegistration Model class NewRegistration(models.Model): registration_date = models.DateField() ward_no = models.ForeignKey(system_settings.models.Wardno) latitude = models.DecimalField(decimal_places=16, max_digits=30) longitude = models.DecimalField(decimal_places=16, max_digits=30) is_forwarded = models.BooleanField(default=False)` Landowner Model class Landowner(models.Model): lo_address_roadname_en = models.TextField(max_length=100, null=True, blank=True) reg = models.ForeignKey(NewRegistration) Application model class Application(models.Model): building_storey = models.IntegerField(blank=True, null=True, default=0) reg = models.ForeignKey(NewRegistration) I want to count the data of application table on the basis of no_of_storey having certain lo_address_roadname_en from Landowner model and certain ward_no from NewRegistration Model and having certain registration_date from NewRegistration Model I have tried like this. building_storey = Application.objects.filter(reg__ward_no=ward_no).filter(reg__registration_date__gte=start_date,reg__registration_date__lte=end_date).values('building_storey').annotate(Count('building_storey')) context['building_storey'] = building_storey How can i filter from three tables? Please help me. -
nginx serving from html instead of gunicorn
I have a nginx / gunicorn / django app I've set up following https://medium.com/@_christopher/deploying-my-django-app-to-a-real-server-part-ii-f0c277c338f4 It works when I go to the main IP from the browser (I got Django tried these URL patterns, in this order: admin/...) but when I go to /admin I got a 404. Nginx logs are as follows: 2019/07/05 00:30:28 [error] 13600#13600: *1 open() "/usr/share/nginx/html/admin" failed (2: No such file or directory), client: 186.190.207.228, server: 127.0.0.1, request: "GET /admin HTTP/1.1", host: "128.199.62.118" So it is trying to serve files from html/ instead of serving gunicorn, why? Nginx config: server { listen 80; server_name 127.0.0.1; location = /favicon.ico {access_log off;log_not_found off;} location = /static/ { root /home/juan/site; } location = /media/ { root /home/juan/site; } location = / { include proxy_params; proxy_pass http://unix:/home/juan/site/site.sock; } } -
How to order a list of objects containing longitude and latitude by distance? [duplicate]
This question already has an answer here: Haversine Formula in Python (Bearing and Distance between two GPS points) 10 answers I have a list of objects that contain the following properties: latitude, longitude. Given an origin location, how can I sort this list based on their distance to this given origin location? -
Django: pycharm: unversioned files
When I did 'makemigrations' on 'django', the generated file became 'unversioned files'. I don't know why. How can I turn into versioned files these unversioned one? -
Response returns code=415, message=Unsupported Media Type in Android-Rest API
I am trying to implement a user login in Android using Kotlin. In the backend runs Django. The API is created in RestFramework. The API works fine when tested in a browser. But when the same endpoint is tested using Android it returns 415 status code as follows. Response{protocol=http/1.1, code=415, message=Unsupported Media Type, url=http://endpoint/login/} The following is the post function fun post(){ val loginCredentials = UserModel("sampleuser","password") val gson = GsonBuilder().create() val payload=gson.toJson(loginCredentials) val okHttpClient = OkHttpClient() val requestBody = payload.toRequestBody() val request = Request.Builder() .method("POST", requestBody) .url("http://endpoint/login/") .build() request.headers("Content-Type:'application/json'") okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("Responed tO Post",e.message) } override fun onResponse(call: Call, response: Response) { val body = response?.body?.string() val user = gson.fromJson(body,UserModel::class.java) Log.e("res body user",user.username.toString()) } }) -
Why IndexError at / list index out of range in Django
I don't know why happens that with this code, I'm a Python Begginer, the original code is in https://github.com/yo-alan/horarios IndexError at / list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.22 Exception Type: IndexError Exception Value: list index out of range Exception Location: /Users/oscarfrancisco/PycharmProjects/ProyectosGithub/horarios-master/calendario/views.py in index, line 76 Python Executable: /Users/oscarfrancisco/PycharmProjects/ProyectosGithub/bin/python Python Version: 2.7.10 Python Path: ['/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/horarios-master', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python27.zip', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-darwin', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-mac', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-tk', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-old', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/oscarfrancisco/PycharmProjects/ProyectosGithub/lib/python2.7/site-packages'] Server time: Jue, 4 Jul 2019 20:02:39 -0300 def index(request): if not request.user.is_authenticated(): return render(request, 'calendario/index.html') if str(list(request.user.groups.all())[0]) == 'Profesionales': persona = request.user.usuario.persona especialidades = Especialidad.objects.filter(estado='ON', profesional=persona)\ .order_by('nombre') espacios = Espacio.objects.filter(~Q(estado=Espacio.OFF)) calendarios = Calendario.objects.all() context = { "espacios": espacios, "especialidades": especialidades, "calendarios": calendarios} else: institucion = request.user.usuario.instituciones.all()[0] especialidades = Especialidad.objects.filter(estado='ON', institucion=institucion)\ .order_by('nombre') espacios = Espacio.objects.filter(~Q(estado=Espacio.OFF), institucion=institucion) calendarios = Calendario.objects.all() for calendario in calendarios[:]: if institucion != calendario.espacio.institucion: calendarios.remove(calendario) profesionales = Profesional.objects.filter(estado="ON") for profesional in profesionales[:]: usuario = Usuario.objects.get(persona=profesional) if institucion not in usuario.instituciones.all(): profesionales.remove(profesional) context = { "espacios": espacios, "especialidades": especialidades, "profesionales": profesionales, "calendarios": calendarios} #~ try: #~ usuario = Usuario.objects.get(user=request.user) #~ except: #~ usuario = request.user return render(request, 'calendario/home.html', context) -
Trying to create a detail view with a list in the view with a sublist for each item. And I can create a item for every item on the same view
I am trying to finish this feature of my Django project. I have already created a list view and I am able to click on a topic on the list view and go into its detailed view. Once I am on that topic's detailed view there are a list of items that are associated with this topic. At the top of the page I have a form that when submitted will create an item and put it at the end of the item's list on the same detail view. For each item there are a list of subitems. For each subitem I am trying to create a submit button for it. So when I do click the submit button that subitem will be appended to the end of the list it was created under. Everything looks good but when I try to create a subitem it doesn't create the subitem for the right item. I hope this made since, can anyone point me in the right direction please?? I have created a list in a detailed view For each item in the list I have created a sublist For every item on any list I am trying to create a … -
Django Querysets - Objects including entire set in ManyToMany
I have a model, Respondent, related to another model Questionnaire via a ManyToMany field named finished. I have a set of four Questionnaire objects and would like to retrieve all Respondent objects that have a finished relationship with all four. I would also like to retrieve the inverse: Any Respondent object which doesn't have a finished relationship with all four selected Questionnaire objects. I've been looking through the docs, and haven't found something that works for me. I am able to get all of the Respondent objects that match at least one of the Questionnaire objects with Respondent.objects.filter(finished__in=questionnaire_queryset) but that's as far as I've gotten. -
How to generate extra files with the command `python manage.py startapp xxx`?
There is some way for the "python manage.py createapp xxx" command to generate some extra files like, e.g. xxx.urls, statics.dir, template.dir, etc. I would like to be able to avoid the work of having to generate the files and directories that I might need later. files as for example; app.urls, statics.dir, etc -
How to capture inputs in html and send to python
Im trying to set a web page that only shows inputs that collect: A EXCEL PATH SHEET RANGE and then a python script uses the variables to open the excel and take a screenshot of the Sheet:Area i have already the python script but to transfer from cmd to web i dont have any idea Im already try django and flask both i dont understand their use This is my html <form name = "search" action="." method="POST"> <label>Ruta:</label> <input type="text" name="path"> <label>Hoja:</label> <input type="text" name="sheet"> <label>Rango:</label> <input type="text" name="range"> <p></p> <label>Ruta de Guardado:</label> <input type="text" name="path2"> <label>Alto:</label> <input type="number" name="height"> <label>Ancho:</label> <input type="number" name="wid"> <p></p> </form> In the app.py (flask) project app.route('/', methods=['POST']) def getValue(): path = request.form['path'] sheet = request.form['sheet'] range = request.form['range'] path2 = request.form['path2'] he = request.form['height'] wd = request.form['wid'] excel2img.export_img(path,"test8.png", sheet, range) My python script (works with cmd) enter code here import excel2img from PIL import Image import os path = input('Introduce la ruta del archivo: ') sheet = input("Introduce el nombre del hoja: ") range = input("Introduce el rango: ") save = input("Introduce ruta de guardado") he = int(input("Introduce alto de la imagen: ")) wd = int(input("Introduce el ancho de la imagen: ")) path = … -
Why my django project servers static files from two URLS?
My django app serves my static files from '/static/' and from '/'. I have one folder called "static" where i put my favicon, but django load it two times in two differents urls Example: 127.0.0.1/favicon.ico (max-age = 60) 127.0.0.1/static/favicon.ico (miss max-age header) Note: My project have two "files" folder, one where I load manifest.json, robots.txt, etc, files that I want to have at '/'. I call that folder "templates" and render the files inside using templateview in urls (code below). In the other folder called "static" I have my javascript and my favicon. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'colorfield', 's3direct', 'apps.contact', 'apps.info', 'apps.products', 'apps.scheleudes', 'apps.messages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # compress js and css 'django.middleware.gzip.GZipMiddleware', # compress html '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', 'django.middleware.locale.LocaleMiddleware' # Internationalization for the admin site ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'views/dist/prod/templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'views/dist/prod/static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' urls.py urlpatterns = [ # routes path('', TemplateView.as_view(template_name='index.html')), path('productos/', TemplateView.as_view(template_name='index.html')), path('api/', include('apps.contact.urls')), path('api/', include('apps.info.urls')), path('api/', include('apps.products.urls')), path('api/', … -
Display form for a Custom User
I am build a custom user in Django by following this tutorial: https://wsvincent.com/django-custom-user-model-tutorial/ I manage to create it and add new fields such as: phone, location, firstname etc. However, when I click signup, these new fields do not appear. I do know know how to: 1) Make the added fields appear 2) Modify the html/css with bootstrap of that specific html signup page because I cannot find it I tried to add these fields in admin.py in list_display = ['email', 'username'] but doe snot work In admin.py I have: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username'] # HERE I TRIED TO ADD THE FIELDS SUCH AS 'location' BUT IT DOES NOT WORK admin.site.register(CustomUser, CustomUserAdmin) In forms.py I have: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name', 'organization', 'location', 'postcode', 'phone') In my models.py I have: `from django.contrib.auth.models import AbstractUser from django.db import … -
How to add a SQLServer Full Text Search in Django QuerySet?
In Django, one can use full text search natively when using Postgres. However, when using it with SQL Server (and django-pyodbc-azure) there is no simple way to do it (as far I know). To do a full text search in SQL Server you use the CONTAINS(column, word) function as described in the docs, but Django ORM contains do: LIKE '% text %'. I did find two alternative methods to bypass this problem. One is using RAW SQL the other is using django extra. Snippet using django raw SQL: sql = "SELECT id FROM table WHERE CONTAINS(text_field, 'term')" table = Table.objects.raw(sql) Using django extra: where = "CONTAINS(text_field, 'term')" table = Table.objects.extra(where=[where]) There is two problems with it: Raw queries are harder to mantain. Django docs. recommend against using the extra method. So I want to know if there a better way to do this, using "pure" django ORM if possible. -
Django REST framework. APITestCase. How test views which response for download data to csv
I have views like: class StudentAPIPerformanceReport( generics.RetrieveAPIView, ): def get(self, request, *args, **kwargs): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' writer = csv.writer(response) for student in Student.objects.filter(pk=self.kwargs['pk']): assigned_courses = CourseParticipant.objects.filter(student=student) completed_courses = assigned_courses.filter(completed=True) headings = ( "student full Name", "number of assigned courses to student", "number of completed courses by student" ) rows = ( student.full_name, assigned_courses.count(), completed_courses.count() ) writer.writerow(headings) writer.writerow(rows) return response Urls: path( 'student/report/<int:pk>/', StudentAPIPerformanceReport.as_view(), name='student_performance' ) And test for it view: class StudentAPIPerformanceReportTestCase(APITestCase): def setUp(self): self.student_obj = Student.objects.create( first_name='test', last_name='student', email='test_student@gmail.com', ) self.course_obj = Course.objects.create( name='test', ) student_obj = CourseParticipant.objects.create( course_id=self.course_obj.pk, student_id=self.student_obj.pk, ) def test_student_unassigned_from_course(self): data_id = self.student_obj.pk rud_url = api_reverse('student:student_performance', kwargs={'pk': data_id}) get_response = self.client.get(rud_url, data_id) self.assertEqual(get_response.status_code, status.HTTP_200_OK) But i have Traceback: Error Traceback (most recent call last): File "/home/project/test_task/student/tests.py", line 120, in test_student_unassigned_from_course get_response = self.client.get(rud_url, data_id) File "/home/project/test_task/venv/lib/python3.7/site-packages/rest_framework/test.py", line 292, in get response = super(APIClient, self).get(path, data=data, **extra) File "/home/project/test_task/venv/lib/python3.7/site-packages/rest_framework/test.py", line 199, in get 'QUERY_STRING': urlencode(data or {}, doseq=True), File "/home/project/test_task/venv/lib/python3.7/site-packages/django/utils/http.py", line 93, in urlencode for key, value in query: TypeError: 'int' object is not iterable Api which i wont to test just make some csv file in format: test student,1,0 How i can test it? I will be grateful for the help