Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Declare variables and increase that inside Django templates
I want to declare a variables inside Django templates and increase that by one . my code is {% with 0 as my_variable %} {% for address in user.addresses %} {{my_variable=my_variable+1}} {% if my_variable==1 %} // do something {% else %} // do something {% endif %} {% endfor %} {% endwith %} It's giving the error of jinja2.exceptions.TemplateSyntaxError: can't assign to 'const' How to declare the variable and increase it? -
How to solve SQLdecode error when you migrate models in django?
I am new to django, I have created a project and app and I would like to connect my project to the mongodb. when I enter python manage.py migrate commond , I am gettting below mentioned error. I have dropped database and cleared all migrations in the django_migration table and deleted migration files in the created migrations folder. still getting same error. Please help me with this. Thanks in advance Error: raise TypeError("documents must be a non-empty list") TypeError: documents must be a non-empty list The above exception was the direct cause of the following exception: djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "django_migrations" ("app", "name", "applied") VALUES (%(0)s, %(1)s, %(2)s) Version: 1.2.31 Settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'DB_name', 'HOST':'localhost', # 'PORT': 27017, # 'USER':'', # 'PASSWORD':'' }, models.py from django.db import models # Create your models here. class dummy(models.Model): name= models.CharField(max_length=100, blank=True, null= True) -
IntegrityError at /project/new/ NOT NULL constraint failed: home_post.department
When trying to create a new project within my django project I encounter this error IntegrityError at /project/new/ NOT NULL constraint failed: home_post.department I have search far and wide but can't find a solution that works for me. I have done python manage.py makemigrations and python manage.py migrate a few times but with no luck. I can add anymore information if needed such as migrations and urls.py, thanks for any help you can offer. views.py class ProjectCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['road_name', 'asset_name', 'department', 'description', 'comments'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class ProjectUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['road_name', 'asset_name', 'department', 'description', 'comments'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False models.py class Post(models.Model): description = models.TextField() road_name = models.CharField(max_length=150, default='') asset_name = models.CharField(max_length=200, default='') department = models.ManyToManyField( to='Listing', blank=True, null=True ) comments = models.TextField(default='', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Listing(models.Model): title = models.CharField(max_length=250) def get_absolute_url(self): return reverse('project-create') def __str__(self): return "{}".format(self.title) class Departments(models.Model): listing = models.ForeignKey(Listing, on_delete=models.DO_NOTHING) post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) name = models.CharField(max_length=140) def __str__(self): return "{}".format(self.name) class … -
How to not append /home/ When Clicking href Django
If I'm at a web page myapp.com/home I have a nav bar at the top that leads to delete_confirm.html. This is within my home.html page that contains the link <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> User Settings </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{% url 'delete_confirm_view' %)">Delete Account</a> </div> </li> Here is my urls.py urlpatterns = [ path('home/', home_view, name='home'), path('admin/', admin.site.urls, name='admin'), path('delete/', delete_user, name='delete'), url(r'^signup/$', views.signup, name='signup'), path('paste_list/', paste_list_view, name='paste_list'), url(r'^$', home_view), path('<str:custom_uuid>/edit', edit_view, name='edit_paste'), path('<str:custom_uuid>/', detail_view, name='detail'), path('accounts/', include('django.contrib.auth.urls')), path('delete_confirm_view/', delete_confirm_view, name="delete_confirm_view" ) ] And the relevant part of views.py @login_required def delete_confirm_view(request): return render(request, "delete_confirm_view.html", {}) The error I'm getting is: The current path, home/{% url 'delete_confirm_view' %), didn't match any of these. I'm wondering how I can not include the /home portion that is appended to the URL being checked. OR, how I can forward to the required page correctly. -
Django design function to check 500 error for invalid host and block IP
I'm getting bots that intentionally try to look for vulnerabilities on my IP and what I have to do is manually block the IP's. For example with this as the start of the error sent to my email by django Invalid HTTP_HOST header: '68.183.112.215'. You may need to add '68.183.112.215' to ALLOWED_HOSTS. Report at /.well-known/security.txt Invalid HTTP_HOST header: '68.183.112.215'. You may need to add '68.183.112.215' to ALLOWED_HOSTS. Request Method: GET Request URL: https://68.183.112.215/.well-known/security.txt I'd need to know the error type is invalid HTTP_HOST then with the IP listed HTTP_X_REAL_IP = '198.20.70.114' parse this field to get the IP I think this should work def handler500(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') #check if Invalid HTTP_HOST header #if so run script to add ip to blocked ip's #if possible let the normal 500 error to be raised .... #otherwise raise custom error If I can figure out the error type then I can try this out. Getting tired of doing this manually. -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'login
I am trying to add users app which i made separately and then trying to add this to my blog. But the problem is every time i try to add this something is messed up like this error i am getting now. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. so far i have done this blog/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from users.views import login_view, register_view, logout_view # from django.contrib.auth import views as auth_views # from users import views as user_views from posts.views import index,postDetail, categoryDetail, blog, search urlpatterns = [ path('admin/', admin.site.urls), path('', index, name="home"), path('blog/', blog, name="blog"), path('search/', search, name='search'), path('<slug>/', postDetail, name='post-detail'), path('category/<slug>/', categoryDetail, name='category-detail'), path('login/', login_view), path('logout/', logout_view), path('register/', register_view), # path('register/', user_views.register, name='register'), # path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), # path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('tinymce/', include('tinymce.urls')) ] settings.py LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' users/forms.py from django import forms from django.contrib.auth import ( authenticate, get_user_model ) User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username = … -
Python using django framework - You do not have permission to perform this action ERROR
I have my feature on my web app where in an admin account can set verification to a company which is the code of that is below. Now when performing the action i cant seem to figure out what is the reason why it is giving my an error "You do not have permission to perform this action ERROR." - 403 Forbidden . In case you wanted to know the FE i have provided also. Thank you. Hope that helps. html <button ng-click="main.verifyCompany(company,true)" ng-show="company.is_verified" class="btn btn-primary btn-sm"> <i class="fas fa-thumbs-up"></i> Approve </button> FE (angular) me.verifyCompany = function (company, verify) { if (verify) { var message = "Do you really want to activate job posting and other features for this business account?. Doing so will send an email notification." } else { var message = "Deactivate posting for this account?." } confirmSweet.ask(message).then(function (response) { if (response) { var filter = {} filter.id = company.id filter.verify = verify AdminService.verify_company(me, filter).then(function (response) { if (response.status == "200") { console.log("Response", response.status) me.get_companies() } }) } }); } PYTHON CODE class VerifyCompany(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,IsCompany,IsAdmin,) def get(self, request,company_id): data = request.data verify = request.GET["verify"] verify = True if verify == "true" else … -
Static file storage and server hosting - Django
I am new to server side operations and have a personal project that I am building. I am running Python3, Django2 with mysql (which will be changed to postgres for live usage) and currently have my static files stored inside the virtualenv on my local drive. It's also built locally on Ubuntu 16.04 if this changes anything, for example: Maybe git deployment would be easiest? My first question is: I don't expect lot's of traffic (under 1000 a day), and databases are very simple. Only an admin can upload static content, such as posts, images, tags and categories. Essentially a blog format. Where should I store these files? Amazon s3, azure, google, or anything you suggest 2. Second question is: Where should I host my web app, and how will it affect where I store my static files? I'd like to note that I am an entrepreneur doing this on my own so an inexpensive and simple setup is what I am aiming for as I don't have much experience in server side tech, but willing to learn. Thank you in advance for your time and sorry if I left out some required information, I'll update the Q as needed. -
Django many to many database approach
I have an ongoing project called "Recruitment System" and i am using django framework. I am struggling on what approach should i do: You have a table for a List of Applicants in database.(ApplicantTable) Once that applicant is marked as hired, the human resource team wanted to monitor the requirements for all the applicants.(RequirementsMonitoringTable) ApplicantTable has a column named "requirement" and has a manytomany relationship with RequirementMonitoringTable. Example: We have Applicant A in the database - His requirements needed for employment are: 1. NBI Clearance 2. SSS 3. Passport 4. Resume 5. College Diploma So the database outputs like this applicantID | requirementID| remarks| datePromised| 2 1 null null 2 3 null null 2 5 null null 2 2 null null 2 4 null null Is this approach fine? Or is there any other way that would make this better using django. Thanks -
Django Postgres DeserializationError: Problem installing fixture
I am trying to import my developement database fixtures into my production server. The migrations have been made and I tried slimming down the database migration to only two classes. This is the command and error I am receiving: Error (env) root@django-01:/home/projects/server/mysite# python3 local.py loaddata db.json Traceback (most recent call last): File "/home/projects/server/env/lib/python3.5/site-packages/django/core/serializers/json.py", line 68, in Deserializer objects = json.loads(stream_or_string) File "/usr/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/usr/lib/python3.5/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 19 column 1 (char 229) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "local.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/home/projects/server/env/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label for obj in objects: File "/home/projects/server/env/lib/python3.5/site-packages/django/core/serializers/json.py", line 73, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/home/projects/server/mysite/db.json': db.json [ { "model": … -
Calling custom middleware attribute in django template
views.py def location_access_permission(get_email): user_email = get_email allow_access = False try: allow_access = UserApprovedModel.objects.filter(u_mail__exact=user_email).first().add_as_admin except: allow_access = True return allow_access middleware.py from .models import UserApprovedModel from django.utils.deprecation import MiddlewareMixin from .views import location_access_permission class ReferMiddleware(MiddlewareMixin): def process_view(self,request, view_func, view_args, view_kwargs): is_custom_admin = location_access_permission(request.user.email) settings.py 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', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middleware.ReferMiddleware', ] html page where I want to use that is_custom_admin variable like is_authenticated() function {% if user.is_custom_admin %} <li class="nav-item"> <a class="nav-link" href="{% url 'org-locations' %}"> <i class="menu-icon mdi mdi-account-location"></i> <span class="menu-title">Locations</span> </a> </li> {% endif %} Basically, I want to hide 'location' in navbar for some custom users like we hide some attributes with is_authenticated. So, for that I am trying to make my is_custom_admin. -
django - measuring delay in the middleware
I wrote this code for django 1.8 to compute how long it takes to process a request. I intentionally made the view take 4 seconds but the delta time displayed in this code is 8 milliseconds. Any ideas how I can measure it in the middleware? from datetime import datetime class MonitorMiddleware(object): def process_request(self, request): request.start = datetime.now() def process_response(self, request, response): print 'Took: ', round((datetime.now() - request.start).microseconds / 1000000.0, 3) return response -
django url not matching
I am doing a project and I have this problem with a specific url that doesn´t want to get matched with an url regex I made for it. Furthermore, it was working great until today. Here is the html code with the button <button class="btn editar" onclick="location.href='{% url 'ver_caso' caso_id=caso.id %}';">Crear caso</button> And here all the urls I have in the urls.py file urlpatterns = [ # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), #Casos en curso url(r'^casos/en_curso/buscador_inteligente/editar_entidad/(?P<tipo>[A-z úé]+)/(?P<id_ent>\d+)/(?P<id_caso>\d+)/$', views.editar_entidad, name='editar_entidad'), url(r'^casos/en_curso/buscador_inteligente/guardar_resultadoInteligente/(?P<tipo>[A-z úé]+)/(?P<caso_id>\d+)/$', views.guardar_resultadoInteligente, name='guardar_resultadoInteligente'), url(r'^casos/en_curso/buscador_guiado/guardar_resultadoGuiado/(?P<tipo>[A-z úé]+)/(?P<caso_id>\d+)/$', views.guardar_resultadoGuiado, name='guardar_resultadoGuiado'), url(r'^casos/en_curso/buscado_general/guardar_resultadoGeneral/(?P<caso_id>\d+)/(?P<expresion>.+)/$', views.guardar_resultadoGeneral, name='guardar_resultadoGeneral'), url(r'^casos/en_curso/buscador_inteligente/(?P<tipo>[A-z úé]+)/(?P<caso_id>\d+)/$', views.buscador_inteligente, name='buscador_inteligente'), url(r'^casos/en_curso/buscador_guiado/(?P<tipo>[A-z úé]+)/(?P<caso_id>\d+)/$', views.buscador_guiado, name='buscador_guiado'), url(r'casos/en_curso/compartir_casos/(?P<caso_id>\d+)/(?P<tipo>[A-z úé]+)/$', views.compartir_casos, name='compartir_casos'), url(r'^casos/en_curso/administrar_casos/(?P<tipo>[A-z úé]+)/$', views.administrar_casos, name='administrar_casos'), url(r'^casos/en_curso/buscador_general/(?P<caso_id>\d+)/$', views.buscador_general, name='buscador_general'), url(r'^casos/en_curso/agregar_doc/(?P<caso_id>\d+)/$', views.agregar_doc, name='agregar_doc'), url(r'^casos/en_curso/nuevo_caso/$', views.nuevo_caso, name='nuevo_caso'), url(r'^casos/en_curso/ver_caso/(?P<caso_id>\d+)$', views.ver_caso, name='ver_caso'), url(r'^casos/en_curso/$', views.casos, name='casos'), #Resultados url(r'^resultados/eliminar_resultadoCaso/(?P<caso_id>\d+)/(?P<resultado_id>\d+)/(?P<tipo>[A-z úé]+)/$', views.eliminar_resultadoCaso, name='eliminar_resultadoCaso'), url(r'^resultados/eliminar_resultado/(?P<caso_id>\d+)/(?P<resultado_id>\d+)/(?P<tipo>[A-z úé]+)/$', views.eliminar_resultado, name='eliminar_resultado'), url(r'^resultados/crearInforme/(?P<resultado_id>\d+)/(?P<tipo_informe>[A-z úé]+)/$', views.crearInforme, name='crearInforme'), url(r'^resultados/ver_resultado/(?P<resultado_id>\d+)/(?P<tipo>[A-z úé]+)/$', views.ver_resultado, name='ver_resultado'), url(r'^resultados/$', views.resultados, name='resultados'), #Casos finalizados url(r'^casos/documentos_caso/(?P<caso_id>\d+)/(?P<destino>FrontEnd/documentos_[a-z]+\.html)/$', views.documentos_caso, name='documentos_caso'), url(r'^casos/resultados_caso/(?P<caso_id>\d+)/(?P<destino>FrontEnd/resultados_[a-z]+\.html)/$', views.resultados_caso, name='resultados_caso'), url(r'^casos/informes_caso/(?P<caso_id>\d+)/(?P<destino>FrontEnd/informes_[a-z]+\.html)/$', views.informes_caso, name='informes_caso'), url(r'casos/finalizados/compartir_casosFinalizado/(?P<caso_id>\d+)/$', views.compartir_casoFinalizado, name='compartir_casoFinalizado'), url(r'^casos/finalizados/eliminar_finalizado/(?P<caso_id>\d+)/$', views.eliminar_finalizado, name='eliminar_finalizado'), url(r'^casos/finalizados/$', views.casos_finalizados, name='casos_finalizados'), #Documentos url(r'^documentos/mensaje_nuevo/(?P<id_doc>\d+)/(?P<id_caso>\d+)/$', views.mensaje_nuevo, name='mensaje_nuevo'), url(r'^documentos/eliminar_doc/(?P<id_doc>\d+)/(?P<id_caso>\d+)/$', views.eliminar_doc, name='eliminar_doc'), url(r'^documentos/agregar_docDocumentos/(?P<caso_id>\d+)/$', views.agregar_docDocumentos, name='agregar_docDocumentos'), url(r'^documentos/agregar_docCaso/(?P<caso_id>\d+)/$', views.agregar_docCaso, name='agregar_docCaso'), url(r'^documentos/ver_doc/(?P<id_doc>\d+)/$', views.ver_doc, name='ver_doc'), url(r'^documentos/$', views.documentos, name='documentos'), #Notas url(r'^notas/eliminar_nota/(?P<id>\d+)/(?P<tipo>[A-z úé]+)/(?P<id_nota>\d+)/$', views.eliminar_nota, name='eliminar_nota'), url(r'^ver_notas/eliminar_notacaso/(?P<id_caso>\d+)/(?P<id_nota>\d+)/$', views.eliminar_notacaso, name='eliminar_notacaso'), url(r'^notas/(?P<id>\d+)/(?P<tipo>[A-z úé]+)/$', views.notas, name='notas'), url(r'^ver_notas/crear_nota/(?P<id_caso>\d+)/$', … -
Making program, which pings (specific/all) hosts in LAN
I got homework to do program, which pings (using ICMP) specific (or all if possible) adresses in local server, and returns their statuses. I tried to do it in python, tkinter: #!/usr/bin/env python import csv import tkinter import subprocess import os import time def hosts(): start = "T" while start == "T": start = input("Adding to list [Y/N]: ") if start != "T": break typein = input("Typ urzadzenia: " ) namein = input("Nazwa: ") ipin = input("IP: ") status = "on" data = [typein, namein, ipin, status] with open("hostyin.csv","a", newline="") as f: w = csv.writer(f) w.writerow(data) else: lp() ping() def lp(): x = 0 with open("hostyin.csv", 'r') as inf, open("hostyout2.csv", 'w', newline="") as outf: r = csv.reader(inf) w = csv.writer(outf) for row in r: w.writerow((x, row[0], row[1], row[2], row[3])) x +=1 def table(): root = tkinter.Tk() #opens file with open("hostyout2.csv", newline = "") as file: reader = csv.reader(file) r = 0 for col in reader: c = 0 r += 1 for row in col: if row == "off": color = "red" elif row == "on": color = "green" else: color = "white" label = tkinter.Label(root, width = 10, height = 1, \ text = row, bg=color, relief = tkinter.RIDGE) … -
Django queryset to JSON object nested by primary key
I'm trying to parse a queryset into a JSON object, so that each key is the primary key of the model, and each value is a JSON object containing all other fields. myjson = { apple: { color: "r", calories: 10}, banana: { color: "w", calories: 50} } Here is the model and Django view collecting the data (based on this blog post): class Fruit(models.Model): fruit_id = models.CharField(primary_key=True) color = models.CharField(max_length=50) calories = models.IntegerField() def get_FruitsTableDjango(request): fruits_table = Fruit.objects.all().values() fruits_table_list = list(fruits_table ) # important: convert the QuerySet to a list object return JsonResponse(fruits_table_list , safe=False) But on the client's side (via AJAX), this returns an array of objects: mydata = [ 0: { fruit_id: "apple", color: "r", calories: 10}, 1: { fruit_id: "banana", color: "w", calories: 50} ] I found also here how I can rework this array as expected : //Restructure JSON by fruit_id name fruits= {}, mydata.forEach(function (a) { var temp = {}; Object.keys(a).forEach(function (k) { if (k === 'fruit_id') { fruits[a[k]] = temp; //gets fruit_id return; } temp[k] = a[k]; //fill the temp variable with elements }); }); mydata=fruits; //overwrite initial array with nicely-rearranged-by-fruitId object I have basically two questions: Is there a more direct … -
How to get the files uploaded in InMemoryUploadedFile django
I am developing an application in django 2.1 in which I must upload an undetermined number of audios through a modal and then pass the information to the view from which the modal is launched. However, these audios should not be stored in the database until the main view form is filled out. Then I thought about these solutions: First I thought about saving it as a session attribute but the contents of a FileField is not JSON serializable which did not work. Second I thought about the LocalStorage property but if the files exceed the size I will have problems. Third I thought about getting the file path and then create the audio but as I was reading is a bad practice and can only be obtained if the file is created on the disk, that is, if it is in TemporaryUploadedFile but my files should weigh less than one 1MB For which I have the option that all files that are loaded with a size smaller than 2.5MB are stored in InMemoryUploadedFile but I do not know how to obtain them. Does anyone know how this is done? or how else can I save a list of temporary … -
How do I link a CSV file created in a function using Pandas and show it in my django view/html?
I've created a file called util.py that contains this code within a function to convert my pandas dataframe to CSV: crisporDF = pd.DataFrame(res, columns=["Position", "Guide", "Specificity Score", "Predicted Efficiency (Doench '16)", "Predicted Efficiency (Mor.-Mateos)", "Out-of-Frame score", "Off-targets for 0-1-2-3-4 mismatches"]) crisporDF = crisporDF.replace('\n',' ', regex=True) crisporCSV = crisporDF.to_csv('crisporCSV.csv', index=False) crisporDF = crisporDF.to_html(classes=["table-bordered", "table-striped", "table- hover",], index=False, justify="initial") ive called it crisporCSV as you can see and it creates and saves the file, this is within a function and I'm calling the function in my view like: crisporDF = crispor(form.cleaned_data['dnaSeq'], form.cleaned_data['species'], form.cleaned_data['pam']) The function takes some form outputs that a user submits. The function the returns the pandas dataframe as html code as seen above (crisporDF) I've then returned this in the function "return crisporDF" this then outputs the table in my view. return render(request, 'home.html', {'form': form, 'crisporOUT': crisporDF}) this is then called in my html as {{ crisporOUT|safe }} How would I render the csv as a link in my view to download? The file exists but I don't know how I'd go about it, please ask if you need anymore info thanks! -
Django per instance permissions and second order permissions?
Apologies for the title, couldn't think of a better way to word it. I have not written any Code for the following so forgive lack of examples. I am still struggling with the idea conceptually. What I am trying to achieve is a user being able to upload a Document with a DocumentType (e.g. report, documentation, etc...) with a permissions system where the user belongs to a group and the group has permission to upload certain document types only. My issue is that I wish to have seperate models for a Document and DocumentType. DocumentType would be a Foreign Key for Document. How do I give a group permissions to upload a certain document type? e.g a user can create a new Document with Foreign Key DocumentType if the user's group has permission for DocumentType ? -
Django - adding multiple markers to google map using addresses
I looked around on SO for help with this but I can't seem to get this working even after looking at other people's solutions that seem to work. Can anybody tell me what I am doing wrong? Here is my script, I am passing a list of venues that have an address attribute where the data looks like this: "51 Stuart St, Boston, MA". {{clat}} and {{clng}} are the latitude and longitude of the user. <script> var map; var geocoder; function initMap(){ map = new google.maps.Map(document.getElementById('map'),{ center: {lat: {{clat}}, lng: {{clng}}}, zoom:12 }); geocoder = new google.maps.Geocoder(); setMarkers(geocoder, map); } function setMarkers(geocoder, map){ {% for v in venues %} geocoder.geocode({'address': {{v.address}}, function(results, status){ if (status == 'OK'){ var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map }); } else{ alert('Geocode unsuccessful: ' + status); } }) {% endfor %} } google.maps.event.addDomListener(window, 'load', initialize); </script> Also I am calling alert() because I saw other people using this but I am not sure how to actually see this message, can somebody help with this as well? I am using ubuntu and manage.py runserver. -
Django, create the new value of foreign key (drop list) before save
I am new to django and I want to make a simple accounting app, but I am facing the following problem: I have 3 models; accounts, journal, and journalLine, I want every journal number can have multiple lines.For example, journal number 1 can have 4 lines and etc.. So before submitting the from i want the new journal number to be created automatically and the value assigned to the foreign key field (jounralNumber) instead of showing a list (the list only shows only the journal numbers created on the database) models.py from django.db import models from django import forms # Create your models here. # Model For chart of accounts table class accounts(models.Model): accNumber = models.AutoField(primary_key=True,unique=True) accName = models.CharField(max_length=200,unique=True) accNumberMin = models.PositiveIntegerField(default=0,unique=True) accNumberMax = models.PositiveIntegerField(default=0,unique=True) #-- to definde values for choices main or sub-account-start main = 'main' sub = 'sub' main_sub_choices = ((main, 'Main account'),(sub, 'Sub account')) #-- to definde values for choices for main or sub-account-end main_sub = models.CharField(max_length=10,choices=main_sub_choices,default='sub') def __str__(self): ## to show accounts as names not objects in Admen panel return self.accName class journal(models.Model): journalNumber = models.PositiveIntegerField(default='',unique=True) journalDate = models.DateField() journalDesc = models.CharField(max_length=300) def __str__(self): return str(self.journalNumber) class journalLine(models.Model): LineNumber = models.AutoField(primary_key=True) journalNumber = models.ForeignKey(journal,on_delete=models.CASCADE) accNumber = … -
Pls explain how database works with django-rest-auth and get_user_model
I am going to use django-rest-auth for my project and add a connection to another database through the foreign key with the user's email. How can I describe it in my model, because at the moment my models.py file is empty and everything works fine. As I understand it, django-rest-auth uses the standard get_user_model function. Sorry for such a stupid question, thanks -
413 Payload Too Large on Django server
My team has been getting 413 errors whenever we try and upload large files to our Django back-end: 413 Payload too large We can't exactly pin down the maximum acceptable file size - it seems to vacillate in the 1-3MB range. Things we have excluded: It's not a webserver configuration issue, because we're running the Django server locally (without a webserver) We believe it's not an app server configuration issue, because this happens on multiple app servers (./manage.py runserver and daphne -p 8000 topknott.asgi:application) It's not an issue with the field on the Django model, which looks normal: photo = models.ImageField(blank=True) Can anyone spot what we're missing? -
How to save a model when testing without obeying null constraints?
I am writing a unit test for a model method of ModelA which queries for the most recent related ModelB and validates it based on the current time. Ideally for this test I would just like to create one ModelA and a few ModelBs make some assertions and be done. My issue is that both ModelA and ModelB have foreign keys that point to other models which in turn have foreign keys that point to even more models. Is there a way in the scope of my test to ignore the IntegrityError that is thrown by not assigning these other foreign keys? My models.py looks something like this class ModelA(models.Model): modelc = models.ForeignKey('ModelC') ... def method1(self): most_recent_modelb = ModelB.objects.filter(modela = self).latest('created') #some other stuff class ModelB(models.Model): modela = models.ForeignKey('ModelA') modelz = models.ForeignKey('ModelZ') class ModelC(models.Model): modeld = models.ForeignKey('ModelD') -
How to Dynamically Size Crispy Form in Django
I have a form that is appearing as 1 line. I'd like for the size of the window to expand dynamically depending on how much text is entered: Here is the html info from the page it is in: home.html <div class="container"> <div class="jumbotron jumbotron-fluid"> <div class="row"> <div class="col-md-6"> {% if request.user.is_authenticated %} <form action="" method="POST"> {% csrf_token %} {{ form2|crispy }}<br> <input type="submit" name="submit" value="Paste" id="submit" class="btn btn-primary"> </form> {% endif %} </div> -
How to set a custom response structure for Graphene Django?
I am using Graphene Django and trying to set up a custom structure for the response. Currently, response is like the folowing: query { singleEntity(id: "...") { id name } } "data": { "singleEntity" { "id": ..., "name": ... } } However, I want to have a response like this: query { singleEntity(id: "...") { id name } } "singleEntity" { "data": { "id": ..., "name": ... }, "statusCode": 200, "errors": [] } "singleEntity" { "data": null, "statusCode": 404, "errors": [{ "message": "Not found" }] } I know that I can do this manually per query resolver; however, I am looking for a more consistent approach to this. So, if a resolver raises an error, the errors field of resolved field gets filled. If resolvers return data, it just shows the data without errors. I am able to do this in Django Rest Framework as there is a custom error handler in DRF. I am looking for something similar in Graphene. Is this possible to do this with Graphene? Using middleware or some form of a custom resolver?