Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting and getting Django session variable
Here I'm trying to set session variable guest_email_id and trying to print them. def guest_register_view(request): form = GuestForm(request.POST or None) next_get = request.GET.get("next") next_post = request.POST.get("next") redirect_path = next_get or next_post or None if form.is_valid(): email = form.cleaned_data.get("email") new_guest_user = GuestEmail.objects.create(email=email) request.session["guest_email_id"] = new_guest_user.id print(new_guest_user.id) print(request.session.get('guest_emial_id')) if is_safe_url(redirect_path, request.get_host()): # print(redirect_path) return redirect(redirect_path) else: return redirect("register") context = { "form" : form } return render(request, "accounts/register.html", context) Url for this view: path('register/guest/', guest_register_view, name="guest_register"), I'm able to create GuestEmail object having only one field(email) and get it's id, but I'm not getting the value of the session variablr I'm trying to set. I get the below output: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 09, 2019 - 10:29:52 Django version 2.2.6, using settings 'ecommerce.settings' Starting development server at http://0:8000/ Quit the server with CONTROL-C. [09/Nov/2019 10:30:02] "GET /register/guest/ HTTP/1.1" 200 2800 21 None [09/Nov/2019 10:30:05] "POST /register/guest/ HTTP/1.1" 302 0 [09/Nov/2019 10:30:05] "GET /register/ HTTP/1.1" 200 3283 Can anyone help me with what am I doing wrong here in the code? -
How to django user defined table with model
I am writing work management tools, The tool is a general domain tool (any industry can use it), so there is no fixed table called "tasks" or "projects". I have a table called "tables" and another table called "table_details". In table, i will have the user-defined tables/entities and in table_details, i will have the structure of those tables. i need a 3rd table for the entities data. But I am not getting how to do it with Django models This is my current models: from django.db import models class Table(models.Model): name = models.CharField(max_length=50) class TableDetails(models.Model): table = models.ForeignKey( Table, on_delete=models.CASCADE ) description = models.TextField(max_length=500) class TableData(models.Model): data_of_table = models.ForeignKey( TableDetails, on_delete=models.CASCADE ) I am not sure if I am in right order, Can anyone help me to achieve this? Thanks -
Print the structure of a Django project
Is there a command line or python function that prints the directory structure of my Django project? I'm brand new to Django and I've seen this in several tutorials but I don't know how to print it: api/ manage.py api/ __init__.py settings.py urls.py wsgi.py music/ migrations/ __init__.py __init__.py admin.py apps.py models.py tests.py views.py venv/ -
Pre-populate the records in related table
I have three tables: ReflectionDate, ReflectionItem, and ReflectionItemDateLink. The relationship between them is as follows: 1) each record in ReflectionDate can be linked to multiple records in ReflectionItem; 2) the correspondence between ReflectionDate and ReflectionItem is stored in ReflectionItemDateLink. #models.py class ReflectionDate(models.Model): date=models.DateField(default=datetime.now, blank=True) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def __str__(self): return str(self.date) class ReflectionItem(models.Model): reflection_item=models.CharField(max_length=200,null=True,blank=True) Yes = "Yes" No = "No" Include_or_not = ( (Yes, "Yes"), (No, "No"), ) include=models.CharField(max_length=9, choices=Include_or_not, default=Yes) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) def __str__(self): return str(self.reflection_item) class ReflectionItemDateLink(models.Model): date=models.ForeignKey(ReflectionDate,on_delete=models.CASCADE) item=models.ForeignKey(ReflectionItem,on_delete=models.CASCADE) remark=models.CharField(max_length=200,null=True,blank=True) create_time = models.DateTimeField(auto_now_add=True) update_time = models.DateTimeField(auto_now=True) In Django admin, I have #admin.py ##about reflection items class ReflectionItemAdmin(admin.ModelAdmin): pass class ReflectionItemInlineFormSet(BaseInlineFormSet): model = ReflectionItemDateLink def __init__(self, *args, **kwargs): super(ReflectionItemInlineFormSet, self).__init__(*args, **kwargs) self.initial=[] ids=ReflectionItem.objects.filter(include='Yes').values_list('pk', flat=True) for item_i in ids: self.initial+=[{'item':ReflectionItem.objects.get(pk=item_i)}] class ReflectionItemInline(admin.TabularInline): model = ReflectionItemDateLink formset = ReflectionItemInlineFormSet print(ReflectionItem.objects.count()) #extra = DeepHour.objects.count() extra = ReflectionItem.objects.filter(include='Yes').count() class ReflectionDateAdmin(admin.ModelAdmin): inlines=[ReflectionItemInline] # pass admin.site.register(ReflectionDate,ReflectionDateAdmin) admin.site.register(ReflectionItem,ReflectionItemAdmin) My objective: when I create a new record in ReflectionDate (using ReflectionDateAdmin), I want all the ReflectionItem records with include=Yes to be prepopulated and automatically shown on the ReflectionDateAdmin page. It has been basically realized using ReflectionItemInline and ReflectionItemInlineFormSet. Something like this (static is not properly shown, but not a problem … -
Fetch complete user record in DJango
Below is the user record present in MySQL Database table - auth_user Please click the image if it is not clear here Below is my code present in View.py file. from django.contrib.auth.models import User from django.http import HttpResponse from django.views import View class loginController(View): def get(self, request): userobj = User.objects.filter(username = 'username') return HttpResponse(request.POST.get('username')); It returns just the username. Is it possible to fetch the full user record? -
Django - Log Warning On Specific Routes
I'm currently renaming an existing API endpoint from /path to /newpath. Ideally I want to keep /path around for some time, while logging a warning for any request that comes in with that route. That way I won't break anything for current unknown clients, but will also be able to see how many requests are coming in. I currently using a router to map requests in my url.py file, e.g. router.register('path', views.PathViewSet, base_name='path') How can I add a LOGGER.warning when a request comes in for /path? -
How to search with partial exact match in Django
Table definition: class Hello(models.Model): name models.CharField(max_length=64, blank=True) 2 records are in db: #1 aaaa-bbbb (cd) #2 aaa-bbbb (ef) The search key word: 'aaa-bbbb' ret = models.Hello.objects.filter(Q(name__icontains='aaa-bbbb')) Expected result is #2, but 2 records are found. How to find #2? -
Django's manag.py is not executing
python version: 3.7.4 django version: 2.2.7 os: windows 10 Trying to execute manage.py in any way, shape, or form is not working from neither vscode's python interface, cmd, nor windows powershell. It doesn't show any errors or anything happening. It was working as recently as one week ago the last time I tried. This is how my windows look: vscode: 'C:\Users\josep\Documents\GitHub\lang_site>py manage.py runserver' 'C:\Users\josep\Documents\GitHub\lang_site>' cmd: 'C:\Users\josep\Documents\GitHub\lang_site>py manage.py runserver' 'C:\Users\josep\Documents\GitHub\lang_site>` I have tried the following from the directory containing manage.py: check my Path environment variable contains C:\Users referencing this post uninstall/reinstall Django via pip restart my machine check my init files referencing this post check if I have changed my manage.py file in any way by mistake go to a previous working branch that I haven't touched in a long time try django-admin runserver --settings=lang_site.settings result is ModuleNotFoundError: No module named 'lang_site' I also double checked to make sure the lang_site folder contains a proper __init__.py I have tried py manage.py + runserver, help, and by itself but none of them are executing Just to doublecheck, there is my manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lang_site.settings') try: from django.core.management import execute_from_command_line … -
Django: running manage.py always aborts
I have an existing Django application that I'm trying to set up locally. After creating a virtual environment and installing all the required dependencies, running manage.py just aborts without any other useful error message. $ python manage.py [1] 39973 abort python manage.py Any subcommands supplied also just aborts and I've been trying to find a way to debug with no luck. Versions used: python 3.6.8 Django 2.0.2 -
Why django trying to create migration table when my purpose is just to read existing oracle database
My purpose is to connect to oracle database and run query in order to populate those results on a web page. But when I try to run python manage.py migrate I am getting below error. I dont want to create any table. I just made changes in settings.py file to connect to oracle database instead of sqlite. Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\oracle\base.py", line 506, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-01031: insufficient privileges The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\migrations\recorder.py", line 55, in ensure_schema editor.create_model(self.Migration) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\base\schema.py", line 312, in create_model self.execute(sql, params or None) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\base\schema.py", line 133, in execute cursor.execute(sql, params) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\rishbans\Anaconda3\envs\DjangoProject\lib\site-packages\django\db\backends\oracle\base.py", line 506, in execute … -
Django query annotation without timezone
I'm trying to write the following query using Django's query objects: all_proposals2 = Proposal.objects.raw( "select *, vote_score/extract('epoch' from age(created)) as display_rank from proposals_proposal") This is what I've come up with: all_proposals = Proposal.objects.annotate( display_rank=F('vote_score') / Extract(Func(F('created'), function='AGE'), 'epoch'), ) But it generates this query: SELECT "proposals_proposal"."id", ... ("proposals_proposal"."vote_score" / EXTRACT('epoch' FROM AGE("proposals_proposal"."created") AT TIME ZONE 'America/Los_Angeles')) AS "display_rank" FROM "proposals_proposal" ORDER BY "proposals_proposal"."created" ASC Which is not a valid query. Postgres gives this error: HINT: No function matches the given name and argument types. You might need to add explicit type casts. But it is very close to correct except it has the extra AT TIME ZONE 'America/Los_Angeles' appended to the AGE() function invokation. How can I change the query so that it doesn't have this timezone specification? -
Template tag for hiding sensitive user information in Django
I'm trying to do this in a template: myacctspecial@gmail.com myaccxxxxxxxxxxxxxxxxxx I want to partially hide emails. Is there a template tag in Django that hides part of a string with x's? -
How to access object url outside of templates?
I have a FileField which users upload Excel files to. I need to get access to the URL of the file to use in a helper function; namely pd.readexcel(url). Currently I am getting the last uploaded object like this: tips_by_employee_report = StoreReports.objects.latest('tips_by_employee_report') I have tried .url and .path but these methods do not work on this class. I have looked all around and in the Django docs but can only find accessing the url in the templates. How do I access the object URL outside of templates? -
How to serialize an array to a string in Django Rest Framework?
In a website built with Django I've got a model which has a CharField: class Person(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() categories = models.CharField(max_length=255) The CharField can contain a list of strings which are comma separated. For example: ADC,HJD,RTP Using Django Rest Framework I created a POST endpoint to which people can post new records. That field is posted in json as an array though. So the json looks like this: { "name": "John", "age": 25, "categories": ["ADC", "HJD", "RTP"] } I wanted to simply join() the array in the Serializer create() method. But it never reaches that point because it gets filtered out by the validator. I guess the validation is done in the view, but I'm unsure where to start digging. Does anybody know how I can make the endpoint accept an array and turn it into a comma separated string in a CharField? -
How can i protect my css and js source code
I finished my django-project and now deployed on the server but now I'm worried about my css and js source code now I want to hide them or change the code like hashing them to make it hard to read but I dont know Is it possible ?? Is it any website for change my code to make it hard to read??? now I disabled the right click but it's not good way I saw some website hide the css code and user can't access to the source code of css and js but the website written by php remember that I've used python/django for my project Do you have a way for this??? -
Django - Cannot find and load wsgi module with gunicorn
So currently im trying to deploy a django project on digital ocean with nginx as a production server, but it seems when trying to follow this guide to use my own and get it deployed project. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 But when getting to the point in where i have to test it with wsgi and gunicorn but it wont find the module so im getting the error here: (VoidPrivate) root@VOID-BACKEND-01:~/Env/VoidPrivate# gunicorn -b 0.0.0.0:8000 Voidbackend.wsgi [2019-11-08 22:10:09 +0000] [13476] [INFO] Starting gunicorn 19.9.0 [2019-11-08 22:10:09 +0000] [13476] [INFO] Listening at: http://0.0.0.0:8000 (13476) [2019-11-08 22:10:09 +0000] [13476] [INFO] Using worker: sync [2019-11-08 22:10:09 +0000] [13479] [INFO] Booting worker with pid: 13479 [2019-11-08 22:10:09 +0000] [13479] [ERROR] Exception in worker process Traceback (most recent call last): File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/root/Env/VoidPrivate/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app __import__(module) ModuleNotFoundError: No module named 'Voidbackend' [2019-11-08 22:10:09 +0000] [13479] [INFO] Worker exiting (pid: 13479) [2019-11-08 22:10:09 +0000] [13476] [INFO] Shutting down: Master [2019-11-08 22:10:09 … -
heroku python buildpack pip install not adding the entry-points.txt file when installing
My runtime is python-3.7.5 I have an Django reusable app with an entry point in setup.py defined as: setup = ( ... entry_points={'my.group': 'foo = bar'}, ) That allows me to use pkg_resources.iter_entry_points(group="my.group", name=None) to get a list of plugins. I didn't know that until I had this bug, but it seems to rely on a entry_points.txt file that gets installed in the egg-info. This entry_points.txt file seems to be missing when I push to heroku. I did a heroku run bash and: ~/.heroku/python/lib/python3.7/site-packages/m_package.egg-info $ ls dependency_links.txt installed-files.txt PKG-INFO SOURCES.txt top_level.txt but when I uninstall it and install it manually, and I recheck: ~/.heroku/python/lib/python3.7/site-packages/my_package.egg-info $ ls dependency_links.txt entry_points.txt installed-files.txt PKG-INFO requires.txt SOURCES.txt top_level.txt Am I missing something that the buildpack does? The only extra thing to add is that I'm using https://github.com/timshadel/heroku-buildpack-github-netrc.git to get Https authentication in git, (my requirements.txt has some packages from private github repos) but I don't think that this should matter at all. -
heroku works but not localhost:800 anymore
I'm working on python crash course chapter 20 learning log, finally I'm able to push the app to heroku, it works just fine, but if I try to run it locally, python manage.py runserver, it says "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''", is it supposed like that? or is because my computer too outdated, windows 7? Does anyone know whats going on, thank you! -
Django Rest Framework serializer update method does not save object
I have overridden the update method for one of my serializers to call a model's method before saving the object. Like so: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = [...] def update(self, instance, validated_data): instance.model_method() instance.save() return instance In my views, I am saving the serializer using serializer.save(), and of course setting it using MyModelSerializer(instance, data=request.data). However, my instance is not being saved. Just removing the update method saves the instance, but does not call the model_method() obviously. How can I fix this issue? Thanks for any help. -
Multilevel join in Django
I was wondering if there is an easy way to get the parent (A) of a model (C) in Django, given that A has a many to many relationship with B, which has a many to many relationship with C? -
function' object has no attribute 'objects
I'm trying to loop through my database based on a tutorial I'm fallowing, however when I enter my 'listings' app page I get Error: AttributeError at /listings/ - 'function' object has no attribute 'objects' I already tried naming the variable something else so it doesn't share the name with the model, but regardless of what I do. I'm still getting the errors So that's my views.py from listings app from django.shortcuts import render from listings.models import listing # Create your views here. def index(request): listings = listing.objects.all() context = { 'patients' : listings } return render(request, 'listings/listings.html') def listing(request): return render(request, 'listings/listing.html') That's my urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name ='listings'), path('<int:listing_id>', views.listing, name ='listing'), Here I'm looping through and imputing the data into the given format {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <div class="card-body"> <div class="listing-heading text-center"> <h4 class="text-primary">Jane Doe</h4> <p> <i class="fas fa-map-marker text-secondary"></i> Bishopstown Co,Cork</p> </div> <hr> <div class="row py-2 text-secondary"> <div class="col-6"> <i class="fas fa-asterisk"> Risk:</i> Low</div> </div> <hr> <div class="row text-secondary pb-2"> <div class="col-6"> <i class="fas fa-clock"></i> 2 days ago</div> </div> <hr> <a href="listing.html" class="btn btn-primary … -
How to return the result based on Queryset in django rest framework?
I am writing a Django Rest API and my use case is like this: Here is my endpoint: http://127.0.0.1:8000/api/v1/totaltime/slug=abc&date=9-10-21 This will return all the query result of the doctor ABC who worked on this particular date. { "doctor_name": "ABC", "slug": "abc", "working_date": "2019-10-21T07:32:24Z", "clinic": "xyx", } I am using Generic ListAPIView for this and my requirement is to count the number of clinics visited by a doctor using the result of a query set and print it. Is there any way to print my own count result instead of queryset result when user types http://127.0.0.1:8000/api/v1/totaltime/slug=abc&date=9-10-21. -
Django | Pure Javascript - No application works with Django
I want to use ajax in pure javascript (or in a library which doesn't use jQuery) but whatever application/type I use, Django doesn't handle the data. (I want to send texts, objects, arrays, etc...) Here's my Javascript code, using the "Ajax" library: function objectToFormData(obj, rootName, ignoreList) { var formData = new FormData(); function appendFormData(data, root) { if (!ignore(root)) { root = root || ''; if (data instanceof File) { formData[root] = data; } else if (Array.isArray(data)) { for (let i = 0; i < data.length; i++) { appendFormData(data[i], root + '[' + i + ']'); } } else if (typeof data === 'object' && data) { for (const key in data) { if (data.hasOwnProperty(key)) { if (root === '') { appendFormData(data[key], key); } else { appendFormData(data[key], root + '.' + key); } } } } else { if (data !== null && typeof data !== 'undefined') { formData[root] = data; } } } } function ignore(root){ return Array.isArray(ignoreList) && ignoreList.some(function(x) { return x === root; }); } appendFormData(obj, rootName); return formData; } class Ajax{ static _default_send(url, data, success, error=null, method="post", headers={}){ if ("csrfmiddlewaretoken" in data){ headers["x-csrftoken"] = data["csrfmiddlewaretoken"]; delete data["csrfmiddlewaretoken"]; } const form_data = objectToFormData(data); headers["content-type"] ="application/form-data"; headers["accept"] = "application/json"; … -
Validation for Jquery added rows in Django formset
Please help! I am trying to add validations in Django is_valid() in a custom ModelFormset(BaseInlineFormSet) implementation. Howver, the self.forms only has cleaned_data if the min_num is set to that count. It seems to ignore the actual number of (TOTAL_FORMS) field and cleaned_data for new rows added via jQuery formset on front-end are not sent back correctly. forms.py: CustomInlineFormSet= forms.inlineformset_factory(MainModel, InlineFormModel, widgets = {}, form=InlineFormModelForm, formset = CustomInlineFormModelFormset, exclude=[], min_num=1, max_num = 8, extra=0, can_delete=True ) # I'm wondering if I need to set initial on the POSTed inlineform, but if so, how to instantiate that correctly???? class CustomInlineFormModelFormset(BaseInlineFormSet): def clean(self): cleaned_data = super(CustomOperatorFormset, self).clean() for form in self.forms: # All docs/examples point to this, but form['cleaned_data'] is blank for 2nd/3rd rows added through the jQuery formset. Only seems to match the min_num !! So the logic below won't work for new forms! if(not form.cleaned_data['name']): form.add_error('name, 'Make required for specific condition only') views.py inline_set = CustomInlineFormSet(request.POST, instance=???, prefix='custom_set') -
How to render a piece of data stored in an external model without refreshing the page?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading …