Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JS won't load unless it's in base.html
I have 2 different js files (custom.js & cart.js), but when I put both of them in my base.html they won't work. When it only have custom.js, the index page works fine, but when I add the cart.js the menu won't work. base.html (works without cart.js) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="{% static '/styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static '/plugins/fontawesome-free-5.0.1/css/fontawesome-all.css' %}" rel="stylesheet" type="text/css"> <title>psproject</title> </head> <body> <!-- Top bar --> {% include 'partials/_topbar.html' %} <!-- Main Header --> {% include 'partials/_mainheader.html' %} <!-- Main nav --> {% include 'partials/_mainnav.html' %} {% block content %} {% endblock %} <!-- Recent viewed --> {% include 'partials/_footer.html' %} <!-- footer --> {% include 'partials/_footer.html' %} <!--Index--> <script src="{% static '/js/custom.js' %}"></script> <!-- Cart --> </body> </html> I've tried to put the script on each file, created a {% block js %} after the block content but it did not work. -
How to get absolute file path for Django project on Ubuntu server?
I am having a tough time understanding absolute and relative file paths. I have an app that users upload files to the server using this model: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return '{0}/{1}'.format(instance.user.username, filename) class UploadReports(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) xls = models.FileField(upload_to=user_directory_path) Then this get_employees_names function works and returns a list of employees. But during the run_payroll function it redirects to the 'filename-error' page of my site. def get_employee_names(username): tips_file = '/home/david/django_website/media/'+username+'/Tips_By_Employee_Report.xls' df_employee_names = pd.read_excel( tips_file, sheet_name=0, header=None, skiprows=7) df_employee_names.rename( columns={0: 'Employee'}, inplace=True) df_employee_names['Employee'] = \ df_employee_names['Employee'].str.lower() employee_names = df_employee_names.loc[:, 'Employee'].tolist() return [(name, name) for name in employee_names] # this is where the the code redirects to 'filename-error' when the file exists @login_required def run_payroll(request, man_name): # get current logged in user current_user = str(request.user) # check if file names of uploaded files are correct names = ['/home/david/django_website/media/'+current_user+'/Stylist_Analysis.xls', '/home/david/django_website/media/'+current_user+'/Tips_By_Employee_Report.xls', '/home/david/django_website/media/'+current_user+'/Employee_Hours1.xls', '/home/david/django_website/media/'+current_user+'/Employee_Hours2.xls', '/home/david/django_website/media/'+current_user+'/SC_Client_Retention_Report.xls', '/home/david/django_website/media/'+current_user+'/Employee_Service_Efficiency.xls'] for name in names: if not os.path.isfile(name): return redirect('filename-error') If I do this in the terminal of the server (venv) david@stacks:~$ cd django_website/media/DavidAlford (venv) david@stacks:~/django_website/media/DavidAlford$ ls I get: payroll.xlsx SC_Client_Retention_Report.xls Employee_Hours1.xls Employee_Hours2.xls Stylist_Analysis.xls Employee_Service_Efficiency.xls Tips_By_Employee_Report.xls My settings.py: Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT … -
Django 1.8 raises error "module X has no attribute 'run'" after upgrading to Python 3.5
I have a Django project running under Django 1.8.4 that I'm trying to upgrade to latest version of Django. Since I was still using Python 2.7 on a Debian 8 server, I first upgraded my server to Debian 9 and then I upgraded my Django project's virtual environment to Python 3.5.3 (the default version of Python 3 on Debian 9). After I rebuilt the virtual environment to use Python 3, I ran the command 2to3 -w . in my project's root folder. 2to3 found and fixed 62 problems without any difficulties. I also have 216 unit tests and only two of them failed under Python 3.5. I then went to my Django website and the site appeared to be working except that the forms that contain pull-down elements show "SomeThingobject" instead of the values from the SomeThing table. I ran a few SQL queries directly against the database and confirmed that my SomeThing lookup table is populated. Now I want to run a Django queryset command in the Python shell like the following to see why my pulldowns are showing my column values: queryset=SomeThing.objects.all() However, if I activate my virtual environment and try to run the command ./manage.py shell, I … -
Trouble getting related fields in ForeignKeys to show in Template
I'm working in Django 2.2 trying to build a view for a database that compiles everything for a specific company (locations of all of their stores and notes on the companies) into a single view. I've tried methods in several different answers, but still cannot seem to get data from related foreign keys to show in the template. models.py class Company(models.Model): name = models.CharField(max_length=30, primary_key=True) official_name = models.CharField(max_length=50) corporate_address1 = models.CharField(max_length=50) corporate_address2 = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.ForeignKey('Country', on_delete=models.CASCADE) slug = models.SlugField(max_length=30, unique=True) def __str__(self): return self.name class Stores(models.Model): store_name = models.CharField(max_length=30, primary_key=True) owner = models.ForeignKey('Company', on_delete=models.CASCADE) store_address1 = models.CharField(max_length=50) store_address2 = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.ForeignKey('Country', on_delete=models.CASCADE) type = models.CharField(max_length=30,choices=store_types) slug = models.SlugField(max_length=30, unique=True) def get_absolute_url(self): return reverse("store-detail", kwargs={"slug": self.slug}) class notes(models.Model): title = models.CharField(max_length=120) content = models.TextField() posted = models.DateTimeField(db_index=True, auto_now_add=True) category = models.ForeignKey('Company', on_delete=models.CASCADE) active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("article-detail", kwargs={"id": self.id}) class Country(models.Model): country = models.CharField(max_length=30,choices=countries,primary_key=True) class Meta: ordering = ["-country"] db_table = 'country' def __str__(self): return self.country views.py class CompanyOverView(LoginRequiredMixin, DetailView): model = Company template_name = "company-overview.html" slug_url_kwarg = 'slug' query_pk_and_slug = True pk_url_kwarg = "company.name" template <div align="center"> <p>{{ object.name }}<br>({{ object.official_name }})</p> … -
Show all users related to tenant in one place
I'm working on an application in the saas model (django 2.1). I use the django tenants plugin (https://github.com/tomturner/django-tenants). My problem is to display all tenants in the "public" schema. In such a way as to see how much each tenant has users, to be able to manage them, etc. Is it a good architectural solution to put a foreign key into Tenant in the User model and save this column during the registration process? Is there another way to do it? Below is example, pseudo code: class Tenant(TenantMixin): name = models.CharField(_('Name of company'), max_length=50, unique=True) on_trial = models.BooleanField(default=True) paid_until = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) auto_create_schema = True def __str__(self): return self.name def get_name(self): return self.name class Domain(DomainMixin): pass class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email address'), unique=True) first_name = models.CharField(_('First name'), max_length=60, blank=True) last_name = models.CharField(_('Last name'), max_length=60, blank=True) member_of_company = models.ForeignKey(Tenant, on_delete=models.CASCADE, related_name='users', null=True, blank=True) -
Can not display ' in browser
I am trying to pass some data from django views to django templates where I would like to save this data to javascript variable, but some weird things happen. If I look data in djnago console I see this: [{'id': 1, 'shape': 'image', 'image': "{% static 'display_network/logos/Router.png' %}", 'label': 'Default gateway'}, {'id': 2, 'shape': 'image', 'image': "{% static 'display_network/logos/VM.png' %}", 'label': 'VM2'}, {'id': 3, 'shape': 'image', 'image': "{% static 'display_network/logos/VM.png' %}", 'label': 'VM3'}, {'id': 4, 'shape': 'image', 'image': "{% static 'display_network/logos/VM.png' %}", 'label': 'VM4'}, {'id': 5, 'shape': 'image', 'image': "{% static 'display_network/logos/VM.png' %}", 'label': 'VM5'}] But when I save data to the javascript variable and print then in the console I get weird result: [{&#39;id&#39;: 1, &#39;shape&#39;: &#39;image&#39;, &#39;image&#39;: &quot;{% static &#39;display_network/logos/Router.png&#39; %}&quot;, &#39;label&#39;: &#39;Default gateway&#39;}, {&#39;id&#39;: 2, &#39;shape&#39;: &#39;image&#39;, &#39;image&#39;: &quot;{% static &#39;display_network/logos/VM.png&#39; %}&quot;, &#39;label&#39;: &#39;VM2&#39;}, {&#39;id&#39;: 3, &#39;shape&#39;: &#39;image&#39;, &#39;image&#39;: &quot;{% static &#39;display_network/logos/VM.png&#39; %}&quot;, &#39;label&#39;: &#39;VM3&#39;}, {&#39;id&#39;: 4, &#39;shape&#39;: &#39;image&#39;, &#39;image&#39;: &quot;{% static &#39;display_network/logos/VM.png&#39; %}&quot;, &#39;label&#39;: &#39;VM4&#39;}, {&#39;id&#39;: 5, &#39;shape&#39;: &#39;image&#39;, &#39;image&#39;: &quot;{% static &#39;display_network/logos/VM.png&#39; %}&quot;, &#39;label&#39;: &#39;VM5&#39;}] My 'js' code: var devices = "{{ devices }}"; console.log(devices); All ' are converted to &#39; and I dont know why they are converted. Any idea how can I solve … -
how to set query for models that have complex relations in django
I have models and betwen them exist complex releations.I want to set query for this situation. This is my files: Models.py class Course(models.Model): category = models.ForeignKey(CourseCategory, null=True, blank=True, on_delete=models.SET_NULL) title = models.TextField(max_length=100, blank=True) slug = models.SlugField(null=True, blank=True, unique=True) class CoursePrerequisite(models.Model): this_course = models.ForeignKey(Course, related_name='this_course', on_delete=models.PROTECT) prerequisite_of_course = models.ForeignKey(Course, related_name='prerequisite_of_course', on_delete=models.PROTECT) class Curriculum(models.Model): course = models.ForeignKey(Course, on_delete=models.PROTECT, ) title = models.TextField(max_length=100, blank=True) term = models.ForeignKey(Term, on_delete=models.PROTECT) teacher = models.ForeignKey(User, on_delete=models.PROTECT) slug = models.SlugField(null=True, blank=True, unique=True) is_active = models.BooleanField(default=False) class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.PROTECT) curriculum = models.ForeignKey(Curriculum, on_delete=models.PROTECT) Views.py def single_curriculum(request, slug): curriculum = get_object_or_404(Curriculum, slug=slug) if request.method == 'POST': this_course = curriculum.course_id pre_course = get_object_or_404(CoursePrerequisite,this_course=this_course) if not pre_course: Enrollment.objects.create(student=request.user, curriculum_id=curriculum.id) return redirect('lms:all_enrollment') if pre_course: #This is the place of my question's answer(I think!) if pre_user_course: Enrollment.objects.create(student=request.user, curriculum_id=curriculum.id) return redirect('lms:all_enrollment') if not pre_user_course: #Rise some error for this condition. Brif of my LMS: As seen from my model file, in this system, the courses have a pre-requisite state.Untile preson can't pass pre-requisite of course, can't take the course. Each course is presented for enrollment in model named: 'Curriculum'. Each person can take 'Curriculum' and record of his(or her) Enrollment save in Enrollment model. I wrote view for show 'Curriculum' and each … -
Filter built with Regex cannot target more than one word at a time (Django 2.1.5)
I have a custom filter that highlights the keywords that the user had put into the search bar (like on Google search). However, as of now, it only highlights the last word of the keywords. For example, if the keywords are "American film industry", only "industry" will be highlighted. But I want all three words to be highlighted whenever and wherever they are present on the webpage (even if they aren't next to each other). To treat these words as individual worlds, I have split the keywords: def highlight(value, search_term, autoescape=True): search_term_list = search_term.split() search_term_word = '' for search_term_word in search_term_list: pattern = re.compile(re.escape(search_term_word), re.IGNORECASE) new_value = pattern.sub('<span class="highlight">\g<0></span>', value) return mark_safe(new_value) Any idea why the filter only highlights the last word and how to make the code work? -
Django Rest Framework Request Validation
Is there a way to validate params that are passed with the request without writing boilerplate code? Now I've got something like this: project_id = kwargs['project_id'] try: project_obj = Project.objects.get(id=project_id) except Project.DoesNotExist: return Response( {'message': 'Requested project does not exist'}, status=status.HTTP_404_NOT_FOUND ) except ValueError: return Response( {'message': 'Project id must be a number'}, status=status.HTTP_400_BAD_REQUEST ) I've read about Serializers' Validation but I'm not sure it's the right thing. Without handling these exceptions, Django just returns 500, it's not the behavior I actually want. -
docker-compose build command freezing
after 'sudo docker-compose up' command the terminal is freezing in 'Building wheels for collected packages ... ' Building wheels for collected packages: cryptography, freeze, ipaddress, psutil, pycrypto, pygobject, pykerberos, pyxdg, PyYAML, scandir, SecretStorage, Twisted, pycairo, pycparser Building wheel for cryptography (setup.py): started i've tried : pip install --upgrade pip pip install --upgrade setup tools commands in Dockerfile this is my Dockerfile : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /todo_service && cd /todo_service/ && mkdir requirements COPY /requirements.txt /todo_service/requirements RUN pip install --upgrade pip RUN pip install -r /todo_service/requirements/requirements.txt COPY . /todo_service WORKDIR /todo_service i want to know the reason of this, if it's connection or dns issues ...? -
Django - When using mysql.connector.django gives TypeError: not all arguments converted during string formatting
When using Django with mysql-connector-python and the Admin views, and trying to list data from one of the tables, the page fails with TypeError: not all arguments converted during string formatting. Has anyone seen this before? Any ideas to fix this? Same code works on a Postgres backend. The Django Rest Framework APIs also work and return data for the same table. Versions: django==2.0.13 djangorestframework==3.8.2 mysql-connector-python==8.0.5 Stacktrace: Traceback (most recent call last): File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response response = response.render() File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/ddtrace/contrib/django/templates.py", line 33, in traced_render return Template._datadog_original_render(self, context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated return self.render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 155, in render return compiled_parent._render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 943, in render bit = node.render_annotated(context) File "/Users/xbox/IdeaProjects/venv/lib/python3.6/site-packages/django/template/base.py", line 910, in render_annotated … -
Does Django makes query on prefetching a field and accessing it through "values()" or "values_list()"?
models.py: class DemoA(models.Model): M = < M2M-Field to DemoB> class DemoB(models.Model): title = < CharField > Queryset with prefetch: qs = DemoA.objects.all().prefetch_related('M') Prefetch works good when used with .all() as stated in the docs. Eg: # This is the expected use case and will not make any additional query for row in qs: print(row.M.all()) 1) Now what if I try to access it using .values() or .values_list() methods ? Will it make additional query(s) ? Eg: print(qs.values('M')) # OR print(qs.values_list('M')) 2) Additional: What if I access the property of M in a similar way? Will it make any additional query? Eg: print(qs.values('M__title')) -
Google authentication to create User model in django
I want to verify user from google and save user details to my basic User model. By following official tutorial https://developers.google.com/api-client-library/python/auth/web-app I made an application which verifies the user but problem is I need to create a user first then it authenticate it from google.I want user to first verify via google then my code should create User by details fetched from google. Here is my views.py: FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='profile email',#enter your required scope redirect_uri='http://127.0.0.1:8000/home', prompt='consent') def gmail_authenticate(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() #credential of the user if credential is None or credential.invalid: #credential is not present or invalid #so, generating credential FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: #if credential is present and valid http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v2', http=http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status}) def auth_return(request): get_state = bytes(request.GET.get('state'), 'utf8') if not xsrfutil.validate_token(settings.SECRET_KEY, get_state, request.user): return HttpResponseBadRequest() #storing credential to DB credential = FLOW.step2_exchange(request.GET.get('code')) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) print("access_token: %s" % credential.access_token) return HttpResponseRedirect("/") The DjangoORMStorage class needs user instance but I dont want to create User until the user the verified my google. … -
ValueError: dictionary update sequence element #0 has length 1736; 2 is required
I have set up a Jupyter Notebook that connect my Postgresql database, call the datas within a table and apply a Machine Learning model from an API to these datas which are product descriptions, but I keep getting a ValueError: dictionary update sequence element #0 has length 1736; 2 is required which I'm very unfamiliar with.. My Notebook is set up in 3 cells but I put them together below for clarity: from watson_developer_cloud import NaturalLanguageClassifierV1 import pandas as pd import psycopg2 import json conn_string = 'host={} port={} dbname={} user={} password={}'.format('119.203.10.242', 5432, 'mydb', 'locq', 'Mypass***') conn_cbedce9523454e8e9fd3fb55d4c1a52e = psycopg2.connect(conn_string) data_df_1 = pd.read_sql('SELECT description from public."search_product"', con=conn_cbedce9523454e8e9fd3fb55d4c1a52e) natural_language_classifier = NaturalLanguageClassifierV1( iam_apikey='F76ugy8hv1s3sr87buhb7564vb7************', url='https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/7818d2s519-nlc-1311') classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', [{data_df_1.to_json()}]).get_result() print(json.dumps(classes, indent=2)) And this is the full error output: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-108-293ce740be95> in <module>() 1 import json 2 ----> 3 classes = natural_language_classifier.classify_collection('7818d2s519-nlc-1311', [{data_df_1.to_json()}]).get_result() 4 5 print(json.dumps(classes, indent=2)) /opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in classify_collection(self, classifier_id, collection, **kwargs) 152 if collection is None: 153 raise ValueError('collection must be provided') --> 154 collection = [self._convert_model(x, ClassifyInput) for x in collection] 155 156 headers = {} /opt/conda/envs/DSX-Python35/lib/python3.5/site-packages/watson_developer_cloud/natural_language_classifier_v1.py in <listcomp>(.0) 152 if collection is None: 153 raise ValueError('collection must be provided') --> 154 collection = [self._convert_model(x, ClassifyInput) for … -
Regroups a list of products by order with regroup template tag
I'm having problems using {% regroup %} Django template tag. A brief summary: I succeed listing all my orders with their products ordered in the same template. So all seems to works fine doing the following: Create the order Create products ordered Assing those products to the order Display the daily orders with their products in the same template (filtered by date also) in dailyorders.html Here my codes and only I'll show the code which allows me to display the orders and modify one if I want (where I have the problem) models: class Productsordered (models.Model): item = models.ForeignKey(Itemlist, on_delete=models.CASCADE) order = models.ForeignKey(Orders, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quant} - {self.item.nombre_producto}" class Orders(models.Model): date = models.DateField(default=date.today) client_name = models.CharField(max_length=30) (just name, not client id) def __str__(self): return self.client_name class Itemlist(models.Model): id = models.SlugField(primary_key = True, max_length =30) name_item = models.CharField(max_length=30) price = models.IntegerField() Just daily orders and modify order views: def show_daily_orders(request,**kwargs): daily_products_ordered = Productsordered.objects.filter(order__date__day=date.today().day, order__date__month=date.today().month, order__date__year=date.today().year) return render(request,'dailyorders.html',{'daily_products_ordered':daily_products_ordered}) def add_products_ordered (request,pk_order,pk_item): products_ordered=Productsordered.objects.filter(order=pk_order) get_order=Orders.objects.get(id=pk_pedido) list= Itemlist.objects.all() #ask if the product is already there, if not create one try: product = products_ordered.get(item=pk_item) product.quantity += 1 product.save() except: newproduct = Itemlist.objects.get(id=pk_item) newproduct = Productsordered.objects.create(item=newproduct, order=get_order) product.save() return render(request,'modify.html',{'list':list,'products_ordered':products_ordered,'order':order}) dailyorders.html would … -
How can I sort list of objects based on a button
I'm a newbie to Django, and I want to add a sort of a button for sorting elements according to date, descending and ascending order. The idea is to add a button or carousel in the template page. and based on the click decide the sorting if ascending or descending order. I cant figure out how to link the button to the backend. I know that the queryset: post.objects.order_by('date') the button is created as: <div class="form-group"> <label class="font-weight-light text-warning text-info " for="exampleFormControlSelect1" >Sort by date</label> <select class="form-control" id="sort"> <option id="NtF">New to old</option> <option id = "FtN">old to new</option> </select> -
App Engine stackdriver logging to Global log instead of service log
I'm trying to set up logging for a django app hosted as an App Engine service on GAE. I have set up the logging succesfully, except that the logging is showing up in the global log for that entire project instead of the log for that service. I would like for the logs to show up only in the specific service logs this is my django logging config: from google.cloud import logging as google_cloud_logging log_client = google_cloud_logging.Client() log_client.setup_logging() LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'stackdriver_logging': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': log_client }, }, 'loggers': { '': { 'handlers': ['stackdriver_logging'], 'level': 'INFO', } }, } And I am able to succesfully log to the Global project log by calling like this: def fetch_orders(request): logger.error('test error') logger.critical('test critical') logger.warning('test warning') logger.info('test info') return redirect('dashboard') I'm wanting to figure out if I can configure the logger to always use the log for the service that it's running in. -
Python Django "unknown colum user.password" when creatsuperuser
I am trying to build a Django application on top of an existing mysql datatabase. The curernt user table uses 'pwd' for password field. And I have following as custom User model. When run manage.py createsupseruser I get error saying "django.db.utils.OperationalError: (1054, "Unknown column 'user.password' in 'field list'"). How can I make Django to use 'pwd' instead? class UserModel(AbstractBaseUser): """ user model - reflect of user table """ # fields userid = models.IntegerField(primary_key=True) username = models.CharField(max_length=60, unique=True) pwd = models.CharField(max_length=128) email = models.EmailField(max_length=60, unique=True) realname = models.CharField(max_length=100) lastsigntime = models.DateTimeField(null=True, blank=True) lastlogouttime = models.DateTimeField(null=True, blank=True) # requirements USERNAME_FIELD = 'username' PASSWORD_FIELD = 'pwd' objects = UserManager() class Meta: db_table = "user" def set_password(self, raw_password): self.pwd = raw_password -
Best Practice for using Environment Variables with Django and Python?
Working on separating out sensitive credentials from settings.py in Django applications. In reading - I've decided I'm going to try a .env file to hold all my credentials and keys - and references those environmental variables in my settings.py file. Everyone suggests using os.environ to set and get my variables - is that the best method for it? If I just made a private_settings.py (which would be git-ignored of course) file and imported that into my settings, wouldn't that be the same thing? I could then call things like my_db_password variable and get it in the same fashion, right? Is there a benefit to one way versus the other? What is the 'best practice' way of handling sensitive data like that? Do I need to use another library to handle .env variables? -
query choices with forms.ModelChoiceField that doesn't show object1
I am building a web site in Django that has two apps and models -- maxes and workouts. I want the maxes form to be able to query the workouts model in order to get Lifts. I can get it to work by adding in def str(self): return '%s' % (self.lift) workouts/models.py from django.db import models from utils.models import (CreationModificationDateMixin) # Create your models here. class wplans(CreationModificationDateMixin): wplan = models.CharField(max_length=50) wnumber = models.IntegerField(default=0) lift = models.CharField(max_length=30) weight = models.IntegerField(default=0) sets = models.IntegerField(default=0) reps = models.IntegerField(default=0) def __str__(self): return '%s' % (self.lift) ```python maxes/forms.py ```python class maxesModelForm(forms.ModelForm): lift = forms.ModelChoiceField( label=("Lift"), queryset=wplans.objects.all(), required=True ) It works but I want to be able to add in the wplan field into a form, but it still show lift name now the wplan. If I take out the def __str__ it shows wplanobject(1) -
"Query set has no attribute <field>" but I'm not doing any field lookup
In Django I'm using filter to return a Queryset so I can update it in my serializer. The problem is I get getting this error: 'QuerySet' object has no attribute 'vin'. I understand the error occurs when you try to lookup a field on a Queryset, in which case you would use get() instead of filter(), but I'm not doing a field lookup. And my database does get updated as intended, but I receive the error regardless. The docs use it the same way: # Update all the headlines with pub_date in 2007. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same'). But I'm not sure why it's acting as if I'm still trying to do a field lookup on the queryset serializers.py class ShoppingListSerializer(serializers.ModelSerializer): class Meta: model = ShoppingList fields = ('vin', 'img_url', 'year', 'make', 'model', 'grade', 'colour', 'MMR', 'run_date', 'timestamp', 'lane', "trim", "mileage", 'human_valuation', 'run_no', 'adesa_id', 'engine', 'transmission', 'wheel_drive', 'interior_color', 'seller_announcements', 'auction_location', 'extra', 'check') def create(self, validated_data): # look up the supplied vin, rundate and check fields before POSTing # if the instance exists then just update vin = validated_data["vin"] run_date = validated_data["run_date"] check = validated_data["check"] lookup = ShoppingList.objects.filter(vin=vin, run_date=run_date, check=check) # if lookup exists then update that instance instead if lookup: print("Updating … -
ImportError: cannot import name 'DjangoFilterBackend'
After upgrading to Django REST framework 3.7 I got following error File "/home/jpg/Projects/django2x/sample/views.py", line 24, in <module> from rest_framework.filters import DjangoFilterBackend ImportError: cannot import name 'DjangoFilterBackend' and here is my view from rest_framework.filters import DjangoFilterBackend from rest_framework import viewsets class FooViewSet(viewsets.ModelViewSet): queryset = Foo.objects.all() serializer_class = Foo_Serializer filter_backends = (DjangoFilterBackend,) filter_fields = ('foo_bar', 'bar_foo') -
How to fix "FileNotFoundError" after deployment?
I am getting a FileNotFoundError: [Errno 2] No such file or directory: 'media/DavidAlford/Tips_By_Employee_Report.xls' after uploading file to production server. Made sure the permissions are correct on the project-level directory, the media directory, and the media sub-directories yes Checked that the Apache server is communicating with the database yes The folder DavidAlford is a dynamically created directory which is created when the user uploads files. Traceback: Traceback: File "/home/david/django_website/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/david/django_website/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/david/django_website/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/david/django_website/venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/david/django_website/payroll/views.py" in get_manager_name 47. current_user_username=request.user.username) File "/home/david/django_website/payroll/forms.py" in __init__ 19. self.fields['manager'].choices = get_employee_names(username) File "/home/david/django_website/payroll/payroll.py" in get_employee_names 12. tips_file, sheet_name=0, header=None, skiprows=7) File "/home/david/django_website/venv/lib/python3.7/site-packages/pandas/util/_decorators.py" in wrapper 188. return func(*args, **kwargs) File "/home/david/django_website/venv/lib/python3.7/site-packages/pandas/util/_decorators.py" in wrapper 188. return func(*args, **kwargs) File "/home/david/django_website/venv/lib/python3.7/site-packages/pandas/io/excel.py" in read_excel 350. io = ExcelFile(io, engine=engine) File "/home/david/django_website/venv/lib/python3.7/site-packages/pandas/io/excel.py" in __init__ 653. self._reader = self._engines[engine](self._io) File "/home/david/django_website/venv/lib/python3.7/site-packages/pandas/io/excel.py" in __init__ 424. self.book = xlrd.open_workbook(filepath_or_buffer) File "/home/david/django_website/venv/lib/python3.7/site-packages/xlrd/__init__.py" in open_workbook 111. with open(filename, "rb") as f: Exception Type: FileNotFoundError at /select-manager-run-payroll/ Exception Value: [Errno 2] No such file or directory: '/media/DavidAlford/Tips_By_Employee_Report.xls' Class in forms where code is getting stuck: class … -
Get Django admin.ModelAdmin to display join of two tables
I have a Django app with the following models.py from django.db import models class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) delivered = models.BooleanField(default=False) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) And in my admin.py, I have this from django.contrib import admin @admin.register(Order) class OrderAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'email', 'paid', 'delivered'] list_filter = ['paid', 'delivered'] This only shows the Order table. I would like to join the Order with the OrderItem table and display it in the Django admin. I am not sure this is relevant but for one Order, there could be many OrderItem(s). -
Creaet and output txt file
I have a scenario where a user uploads some data, Django does some processing in pandas and returns a potentially large txt file. I've got this working but I'm unsure about the scalability of the approach and want to know if there's a better way. Adapted the Outputting to CSV section of the Django doc I have the following: class MyClass(LoginRequiredMixin,FormView): template_name = 'myapp/mytemplate.html' form_class = MyForm success_url = '/' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): if request.method == 'POST': form = MyForm(request.POST, request.FILES) #print("filename",files[0].name) if form.is_valid() : filename = "my-file.txt" content = 'any string generated by django' response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response else: print("i am invalid") return self.form_invalid(form) In practice I will need to output a text file of perhaps 1000 lines, built by looping over numerous dataframes, should I just build an extremely long text string (content), or is there a better way? In pure python I am more used to creating txt file output using: f = open( 'some_file.txt', 'w+') f.write("text") f.write("text") f.close() Which seems more intuitive.