Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CMS plugin, group options in editor
I am working on a custom plugin for Django CMS, and I have a bunch of options for the editor to use. I would like to group these options together to make it easier for the editor to see what options relate to each other. Example of options that should be grouped How can I make changes to the editor to achieve this? -
Django Rest Framework OAuth2 separate Users by Application
I have 2 application and i want to authorize 2 types of account separated by application.I wrote custom middleware for checking accounts and creating token for them.In the below codes im extracting http authorization values and checking permission by manual.It works there is no problem.But can i improve this method.Is there any another best way for this ? import base64 from django.utils.deprecation import MiddlewareMixin from oauth2_provider.models import Application from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.http import HttpResponse class MyAuthMiddleware(MiddlewareMixin): def process_request(self, request): if request.path == '/o/token/': decoded_header = base64.b64decode(request.META.get( 'HTTP_AUTHORIZATION', '').split(' ')[1]) client_id = decoded_header.decode('utf-8').split(':')[0] username = request.POST.get('username', '') user = get_object_or_404(User, username=username) app = get_object_or_404(Application, client_id=client_id) if app.name == 'PcSlicer' and not user.is_staff: return HttpResponse('unauthorized', status=404) return None -
Python - Django Share files between two authenticated users
I'm working on a project using Python(3.7) and Django(2.5) in which I'm building an application something like a freelancing site, but I'm stuck at one point while implementing the delivery submission part. A user will create a service to sell and then a buyer will order his service, after that the seller has to be done the agreed job and need to submit the work to the buyer as a delivery. The delivery will be in the form of a file, can be a text file, image file, audio, video or a code file, the problem is that I don't know how I can implement this thing in Django, so a user can send a file to another user in a private manner, so only both of these users will be able to access that file. Here's what I have so far, for order between buyer and seller: class Order(models.Model): status_choices = ( ('Active', 'Active'), ('Completed', 'Completed'), ('Late', 'Late'), ('Short', 'Short'), ('Canceled', 'Canceled'), ('Submitted', 'Submitted') ) gig = models.ForeignKey('Gig', on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='selling') buyer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='buying') created_at = models.DateTimeField(auto_now=timezone.now()) charge_id = models.CharField(max_length=234) days = models.IntegerField(blank=False) status = models.CharField(max_length=255, choices=status_choices) def __str__(self): return f'{self.buyer} order from {self.seller}' … -
How can I connect to Django development server on Codenvy?
I'm currently testing Django on Codenvy but I have difficulties to find out how to connect to the build-in development server of Django. I added a server in the Workspace configuration with port 8000 and http protocole. I added the following in the run command of Codenvy's project : Commande line : cd ${current.project.path} && python manage.py runserver Preview : http://${server.port.8000} The run prompt provide me a url : http://nodexx.codenvy.io:xxxxx Going to this URL print a message : ERR_CONNECTION_REFUSED I'm very new to all of this. Do you know what is missing ? -
how to fix the error AttributeError: 'Country' object has no attribute 'City_set' . in django
i have 3 dependent dropdownlists country city road. where country is pre-populated from the database and based on the selection of the first the second will display the related cities. the problem is that once the user select from the first dropdownlist the system display the below error : all_cities = selected_country.City_set.all() AttributeError: 'Country' object has no attribute 'City_set' i do not know how to fix this error. models.py class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class City(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country,on_delete=models.CASCADE) def __str__(self): # return'id : {0} MouhafazatID :{1} Name :{2}'.format(self.id,self.MouhafazatID,self.name) return str(self.name) class Road(models.Model): Vil = models.CharField(max_length=100) city= models.ForeignKey(City,on_delete = models.SET_NULL, null=True) country= models.ForeignKey(Country,on_delete = models.SET_NULL,null=True) def __str__(self): return str(self.Vil) home2.html <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> $(document).ready(function(){ $('select#selectcountries').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var country_name = optionSelected.text(); data = {'cnt' : country_name }; alert(country_name); $.ajax({ type:"GET", url:'/getdetails', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectcities option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectcities").append('<option>'+ result[i].name +'</option>'); }; }, }); }); }); </script> </head> <body> <select name="selectcountries" id="selectcountries"> {% for item in countries %} <option val="{{ item.name }}"> {{ item.name }} </option> {% endfor %} </select> … -
How to POST run time data in views using form in django
I write data in particular div section using ajax, Now i want to POST this data in views.py but it returns None. when i write manully like "abc. It returns value. jquery also works fine for that. html code html_code = "<input type='checkbox' id='filesid' name = 'filesname' value='"+i+"'>"+i+"<br>" $('#runtime-div').html(html_code); views.py filename = request.POST.get('filesname') print(filename) -
Display table without refreshing the page on form submit
I am working on a django application which displays a csv file as a table in the web application on file upload. This works properly but the problem is the page reloads when the form is submitted. For this purpose I tried using ajax to load the data without page refresh. But the code does not seem to work. This is my code so far html <form action="{% url 'csv_upload' %}" method="POST" enctype="multipart/form-data" class="mt-2 mb-2 csv_upload_form"> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile"/> <label for="file" class="btn btn-outline-dark btn-lg btn-block select">Choose .csv file</label> <input class='btn btn-warning btn-lg btn-block upload_csv_button' type="submit" value="Upload file" disabled/> </form> javascript $(document).on('submit', '.csv_upload_form', function(event) { event.preventDefault(); csvUploadAjax(); }); function csvUploadAjax() { let $form = $(".csv_upload_form"); let form_data = new FormData($form[0]); console.log(form_data) $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: form_data, dataType: 'json', processData: false, contentType: false, success: function (data) { fillImageDescriptionText(data); }, error: function (xhr) { // console.log("Something went wrong: " + xhr.responseText); } }); } function displayTable(data) { console.log(data) $(".scroll_it").val(data); } In the above code, the error part of the code runs every-time. I am not sure what I am doing wrong. I am new to ajax and dont completely understand the code. Please help me Thank … -
Django, What is the best practice to add a column to a table when 99% of the column is default value?
I'd like to add a column to a table like class User(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=255) birthday = models.DateField(null=True, blank=True) and now I want to add is_admin = models.BooleanField(default=False) but there are only 3 administrators so 99% of the column value is False I think just for 3 rows adding a column is a waste of resources. Is there another best way to handle this kind of problem? -
Django Get value of form field in Update View
I am using class based views and want to get the current value of a given field ward in my UpdateView's get_context_data method. I've tried using the get method but it isn't working. Here's my method: def get_context_data(self, **kwargs): context = super(ApplicationUpdateView, self).get_context_data(**kwargs) context['money_per_ward'] = int(getattr(Allocation.objects.first(), 'amount_allocated') / 30) context['ward'] = self.request.POST.get('ward') # <-- This prints "None" return context Is there a way I can access the current value of this field? -
(Django) How can we store radio button values into database
How can we store radio button values into database. Each time we enter in the models.py it gets as select field. -
What is difference Between select_related and prefetch_related in Django ORM with Simple Example
I go through various websites for difference between select_related and prefetch_related. but I haven't find good Examples to understand properly. Please Explain with Table data also. -
i am making a fees function in fees views.py dynamically
i am trying to make a fees function very dynamically in fees views.py and i am trying to select the values on the basis of "gr_no" actually there is another model name (gr_register) , gr_register have the primary key name "gr_no". models.py (gr_register) class gr_register(models.Model): Gender_Choices = ( ('M', 'Male'), ('FM', 'Female'), ) Status_Choices = ( ('P', 'Present'), ('FM', 'Left'), ) gr_no = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) date_birth = models.DateField(null=True) classes_A = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_A", default=1, verbose_name="Class of Admission") sections_A = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_A", default=1, verbose_name="Section of Admission") gender = models.CharField(max_length=10, choices=Gender_Choices) classes_C = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_C", verbose_name="Current Class") sections_C = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_C", verbose_name="Current Section") address = models.CharField(max_length=100, null=True, verbose_name="Home Address") area_code = models.ForeignKey(Area, on_delete=models.CASCADE, verbose_name="Area") status = models.CharField(max_length=10, choices=Status_Choices, default='P') class Meta: ordering = ('-gr_no',) def __str__(self): return self.first_name models.py (fees) class fee(models.Model): BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) Gr_num = models.ForeignKey(gr_register, on_delete=models.CASCADE, default=231) fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE, default=1) fee_dues = models. BigIntegerField(default=1000) paid_source = models.ForeignKey(fees_source, on_delete=models.CASCADE, default=1) class_name = models.ForeignKey(Classes, on_delete=models.CASCADE, default=1) paid = models.BooleanField(choices=BOOL_CHOICES, default=1) guradian_code = models.ForeignKey(gardian , on_delete=models.CASCADE, default=1) due_date = models.DateField(default=timezone.now) paid_date = models.DateField(default=timezone.now) def __str__(self): return str(self.paid) views.py (fees) def addfees(request): form = feeForm(request.POST or None) if request.method == … -
How to run a command in Docker using custom arguments?
How to run a command in Docker using custom arguments? I'm trying to run a command that causes django to rotate using an environment variable through an argument in the act of creating the server. Thank you very much for your attention. I need to run the command in this format to work. # VAR=enviroment_name python manage.py migrate --database=01_sistema docker docker exec 24e2b5c60a79 VAR=enviroment_name python manage.py migrate --database=01_sistema Error OCI runtime exec failed: exec failed: container_linux.go:344: starting container process caused "exec: \"VAR=enviroment_name\": executable file not found in $PATH": unknown -
Use django-mptt to query the database for all root categories that have at least one subcategory and at least one product
I have a Category model and I use django-mptt to have subcategories (and sub-subcategories, etc.). I also have products, which are assigned to categories. I want to query the database for all root categories that have at least one subcategory and at least one product. For example, consider this data structure: Category: Dairy (0 subcategories, 1 product) Product: Milk Category: Fruit (1 subcategory, 0 products) Subcategory: Red (0 subcategories, 0 products) Category: Vegetables (1 subcategory, 0 products) Subcategory: Green (0 subcategories, 1 product) Product: Cucumber Category: Junk Food (1 subcategory, 1 product) Product: Doritos Subcategory: Chocolate (0 subcategories, 1 product) Product: Snickers In this case, I would want the query to return just the "Junk Food" category since it's the only one that matches all three criteria (root category, has at least one subcategory, has at least one product). I looked through the django-mptt documentation, but didn't see a way to do this. Maybe I overlooked it. Any suggestions? -
How to use vue libraries in django templates
In my project I am using django templates and include vue as script: <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> Now I want to use some vue libraries that can be installed with npm. Question is, how to use these libraries in my project? Please, give some examples. -
What is the best project structure for Django with Github and documentation? How to automate deployment process?
I have few questions regarding to Django project structure and deployment as below: What is the best project structure for Django project for writing scalable and modular code? Where to put Github docs and relevant files? How should the deployment be automated. If there are many Amazon EC2 instances (i.e 10 parallel servers ) where Django is running on each ? Where to put management commands or script? i.e in app directory -
How to solve "could not connect to server: Connection refused (0x0000274D/10061)" in Django and PostgreSQL
Getting this error I forget PostgreSQL Server Password I am getting this whenever to try to start the server. -
How to pass value as string in ForeignKey and not integer?
IMPORT PHOTO I tried to import my model in admin to csv file and the output of the foreignkeys are integers. How can i convert that into string? I had this similar problem before where i wanted to extend django user model to add "department" to users. It was a foreignkey to department model. When i tried to make a user_pass_test mixin to my view it doesnt work because the value is not string but an object. an instance of my department model. user_passes_test mixins -
Python can't find table, that exit in postgreSQL DB
I'm new to database programming, apologies if I ask something simply. I here my error: DB is connected successfully Failed to execute database program relation "cgi_limit" does not exist LINE 1: SELECT * FROM CGI_limit ^ connection of DB had close succefully now I check twice on naming and case of of the word but Farm=# SELECT * FROM pg_tables; schemaname | tablename | tableowner | tablespace | hasindexes | hasrules | hastriggers | rowsecurity public | django_session | FAT | | t | f | f | f public | auth_permission | FAT | | t | f | t | f public | auth_user_user_permissions | FAT | | t | f | t | f public | auth_user | FAT | | t | f | t | f public | django_admin_log | FAT | | t | f | t | f public | CGI_ambient | FAT | | t | f | f | f public | CGI_tank_system | FAT | | t | f | f | f public | CGI_limit | FAT | | t | f | f | f -
How do I know what page am i in? django paginator
I have a code for a paginator to display links but I'm trying to make add a special class for the current page I am in. code: {% for i in movies.paginator.page_range %} {% if movies.number == i %} <li class="pagination-item current-page"> <a href="#">{{ i }}</a> </li> {% else %} <li class="pagination-item"> <a href="#">{{ i }}</a> </li> {% endif %} {% endfor %} everything works but the if movies.number == i part. I'm sure I saw it somewhere and it worked on his case, but i just cant seem to make it work at mine! error: Invalid block tag on line 205: 'else', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
Celery: Updating name of task to match registered task
I changed the name of the directory my celery tasks are in which (judging from the error below) has caused some problems with my future scheduled tasks. KeyError: 'utils.tasks.foo' [2019-02-21 06:25:09,103: ERROR/MainProcess] Received unregistered task of type 'utils.tasks.foo'. The message has been ignored and discarded. This task is now registered under services.tasks.foo. I know I have more tasks scheduled and can view the task ids in my Redis broker, however when I look at the scheduled tasks using app.control.inspect().scheduled() only the tasks that have been scheduled since I made the directory change to services.tasks.foo are returned. Given that Celery isn't recognizing my old tasks, how can I update the task names to match the path that my tasks are now registered under? -
Is win-psycopg the best PostgresSQL adapter for Python to use on a Windows Machine?
I'm developing a Django web app on a Windows 10 x64 development machine using Python 3.7.2. I would like to use PostgreSQL instead of the default sqlite database as I am planning to host this app on Heroku. From what I've researched I need to use a PostgresSQL adapter for Python and the most popular one is Psycopg. From what I can tell on the psycopg website, since I'm on a Windows machine, I need to use the win-psycopg port, but it looks like win-psycopg only supports up to Python 3.5 and it hasn't been updated since July 2016. I'm hesitant to go back to an older version of Python and use a port of an adapter that may not be actively updated anymore. I am curious as to how other developers have setup Python and PostgreSQL on Windows. Is there another adapter that would be better for Windows than Psycopg? My other thought is to use MySQL instead, but that would mean I wouldn't be able to use Heroku. -
How can i record a stream with a dahua cam?
I am using Django. The problem is that i need to start and stop a recording with a Dahua cam from a function in Django and later save that recording in a model, Dahua has an API to get and set its configuration, but not to directly start and stop a recording. To show the stream in HTML5 we use the following code. <div class="h-50 border border-right-0 border-left-0"> <div id="vxg_media_player1" class="vxgplayer h-100 w-100" url="rtsp://username:password@192.168.1.108/cam/realmonitor? channel=1&subtype=1" aspect-ratio latency="3000000" autostart controls avsync debug></div> </div> A JS Framework exists ( WEB RTC ), but it only works with a video tag. -
Django "relation does not exist" error with custom user class and Postgresql schemas
I am getting an django.db.utils.ProgrammingError: relation "user" does not exist error when running createsuperuser on a Django project with a Postgresql database. I wrote the following database router to indicate that the table user (which is based on a custom extension of the AbstractUser class) is in the schema users. Even so, Django cannot find it. from myapp.models import Class1, Class2, Class3 from users.models import User from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType from django.contrib.sessions.models import Session # Include here classes (i.e. tables) that belongs to the "myapp" schema ROUTED_MODELS_MYAPP = [Class1, Class2, Class3] # Include here classes (i.e. tables) that belongs to the "users" schema ROUTED_MODELS_USERS = [User, LogEntry, ContentType, Session] #classes for custom user model, and django tables `django_admin_log`, `django_content_type`, `django_session` tables # classes for the following table names still missing from list: `auth_group`, `auth_group_permissions`, `auth_permission`. class MyDBRouter(object): """ A router to place DB queries into correct schema depending on considered tables. Sources: https://stackoverflow.com/a/51007441/3976696 https://www.amvtek.com/blog/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/ """ def db_for_read(self, model, **hints): if model in ROUTED_MODELS_MYAPP: return 'myapp' elif model in ROUTED_MODELS_USERS: return 'users' return None def db_for_write(self, model, **hints): if model in ROUTED_MODELS_MYAPP: return 'myapp' elif model in ROUTED_MODELS_USERS: return 'users' return None The router works for other … -
Custom validation on Django model field is only returning False
I'm trying to implement a custom model validator, but it always return false. models.py name = models.CharField(validators=[validate_name], max_length=100, default='', unique=True) validators.py def validate_name(name): print(name.isalpha()) # "Abraham" prints False print("Abraham".isalpha()) # Prints True if name.isalpha() is False: raise ValidationError( 'Name can only contain letters A-Z. Not numbers.', ) return name I expect this code to return True when the name is a string like "Abraham" and False when it contains numbers, etc. It's only returning False. It has something to do with the way I'm passing model variable I guess, but I have no idea what.