Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use MariaDB ColumnStore with Django (Django-ORM)?
I have a Django project which uses MariaDB (engine - django.db.backends.mysql). I would like to user MariaDB ColumnStore instead - is it possible? Will I need a different ORM engine? Also, I develop on Windows 10 Pro PC and plan to set up ColumnStore using docker containers provided by MariaDB. This should not be an issue, right? Thank you -
How to apply one specific change to database after 'makemigrations' command?
I added a field to one of my models, but in the 'models' folder I have two other python files which have only View models from which I query views in my database. When I run the makemigrations command, the new migrations file that is created includes also adding these view models to my database as tables (which I don't want to). How can I ignore these changes, and only commit the one addition of a field to an actual table on the database. I think I maybe have to delete the migrations.CreateModel... in the new migrations file and only keep the migrations.addField... , then run the 'migrate' command. I didn't proceed with this because I'm not sure and maybe it will mess up my database in some way. Thanks in advance to anyone who can help. -
A way to access loop index from Django formset loop?
In Django framework templates you can loop through a formset like so: {% for form in formset %} {{ form }} {% endfor %} Is there a way to access the index of the loop? Perhaps something like this: {% for form in formset %} {{ form }} {{ form.index }} {% endfor %} Which should render 0, 1, 2,... prior to each form. -
How does gunicorn deploy django better?
I am using nginx with gunicorn and django. I would like to know Question: What are the benefits using gunicorn compared to just using django's runserver alone -
Pass parameters defined “in the buttons”(template) to CRUD-view
I have a table, where I add in the last column of every row the buttons “delete” and “edit”. I do this with the url + parameters in the href in the template (see below). I wrote a function for every href + parameter and the scripts work. <form method="post"> {% csrf_token %} <input type="hidden" name="projekt_id" value="{{objekt.id}}" /> <a class="btn btn-outline-secondary btn-sm" href="{% url 'check:remove_project' objekt.id %}" role="button">delete</a> <a class="btn btn-outline-secondary btn-sm" href="{% url 'check:edit_project' objekt.id %}" role="button">edit</a> </form> Since i need such tables very often I want to handle the entire functionality (view the data/edit/delete/create) in one single view (I already have this in one template). My idea/wish is to pass the name= and value= from inside the buttons to the view. There I can distinguish for the appropriate functions - by if-statements- between edit/delete/view/create… How can the parameters be passed from the BUTTONS in template to the view? Where is the documentation? I wonder if there is a more elegant way to solve this? (maybe a combination of class based views?) -
Need to protect my directory on ubuntu server so the ubuntu users with access to server cannot see my source code
Hi i am new to ubuntu and security stuff. i have deployed my django project using apache2 and mod-wsgi and angular6 project on aws ec2 instance (ubuntu server). Now i have to deploy the same project in other organisations private inhouse server. So all my source code will live in their server so i need to make sure that they cannot read, copy or access my django source code which will be on their server. Please help me out. Have tried searching on google but i am unable to find anything to help me out achieve this. -
Form Problems - Setting Initial Value
I am trying to set the initial value of a field on a form. The field is not part of the model, but when I try and set it to a value the field is blank. From my research it could be because the form is "bound" which makes some sense to me, but in this case the field is not part of the model. My form: #Form for editing profile class CatForm(forms.ModelForm): pictureid = forms.CharField() class Meta: model = Cat fields = ['name'] def __init__(self, *args, **kwargs): picid = kwargs.pop("pictureid") print(picid) super(CatForm, self).__init__(*args, **kwargs) self.fields['pictureid'] = forms.CharField(initial=picid, required=False) The model: class Cat(models.Model): name = models.CharField(max_length=34,null=False) I was expecting it to set the field to the value of the initial attribute, but it doesn't. I have tried testing it by directly adding a string, but doesn't set. -
I want to create a website where users will be posting to the site, How would I make each post appear in a separate card?
Am creating a website where user will be posting information in the site, but when I post in the site, all post appear in a single card while I want each post to appear in a separate card, How would I do this?? would I have to use Javascript in the front end or python in the back end to accomplish this, and how? Am using python 3.6.8, and django 2.1.8, I have written a code but all post appear in single materialize card views def homepage(request): return render(request=request, template_name="main/home.html", context={"documents":Documents.objects.all} -
How to fix: Domain name not working in digital ocean's droplet. Using Nginx, docker-compose, django
I'm trying to set up a domain name to my digital ocean’s droplet. While the IP address works perfectly, the domain name doesn’t seem to do anything and get “This site can’t be reached”. Checking https://whois.net/ it shows the DNS nameservers are pointing to right direction which are digital ocean’s name servers [NS1.DIGITALOCEAN.COM, NS2.DIGITALOCEAN.COM, NS3.DIGITALOCEAN.COM], and using www.whatsmydns.net it shows the domain name has propagated. Digital Ocean’s DNS records are the following: A--domain.tk--directs to X.X.X.X CNAME--www.domain.tk is an alias of domain.tk NS--domain.tk--directs to ns1.digtalocean.com NS--domain.tk--directs to ns2.digtalocean.com NS--domain.tk--directs to ns3.digtalocean.com I’m using a .tk domain using freenom and have configured the same domain nameservers over there. My NGINX configuration is the following: upstream jaciv_server { server djangoapp:8000; } server { listen 80; server_name domain.tk www.domain.tk; location / { proxy_pass http://jaciv_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /opt/services/djangoapp/static/; } location /media/ { alias /opt/services/djangoapp/media/; } } My docker-compose.yml is the following version: '3' services: djangoapp: build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media domainname: jaciv.tk networks: - nginx_network - database1_network depends_on: - database1 nginx: image: nginx:1.13 ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/djangoapp/static - media_volume:/opt/services/djangoapp/media depends_on: - djangoapp - redis networks: - … -
URL Template Tag works in one instance, but can't find path with kwargs of '{'pk': ''}' in another
I've assigned a navbar link a URL template tag using named paths, and I'm passing the keyword argument of pk to that URL. When I click on the link directly, it passes the kwarg as it should and I get the DetailView that is intended. However, when i attempt to view other DetailView's in my app, I receive the error of: Reverse for 'my_company_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['console/(?P[0-9]+)/mycompany/$']. .html snippet <a class="dropdown-item" href="{% url 'user_console:my_company_detail' pk=request.user.primary_company_pk %}">My Company</a> urls.py urlpatterns = [ path('login/',auth_views.LoginView.as_view(template_name="user_console/login.html"),name='login'), path('change-password/',auth_views.PasswordChangeView.as_view(template_name="user_console/change-password.html"),name='change_password'), path('home/',views.HomepageView.as_view(),name='home'), path('logged-out/',auth_views.LogoutView.as_view(template_name='user_console/logged_out.html'),name='logged_out'), path('requests/',views.RequestListView.as_view(),name='request_list'), path('request//',views.RequestDetailView.as_view(),name='request_detail'), path('consumers/',views.ConsumerListView.as_view(),name='consumer_list'), path('consumer/create/',views.ConsumerCreateView.as_view(),name='consumer_create'), path('consumer//',views.ConsumerDetailView.as_view(),name='consumer_detail'), path('companies/',views.CompanyListView.as_view(),name='company_list'), path('company//',views.CompanyDetailView.as_view(),name='company_detail'), path('company/create/',views.CompanyCreateView.as_view(),name='company_create'), path('request//edit',views.RequestUpdate.as_view(),name='request_update'), path('request/create/',views.RequestCreateView.as_view(),name='request_create'), path('requests/export-all/',views.RequestExport,name='export_all_requests'), path('requests/import/',views.RequestImport,name='import_requests'),path('mycompany//',views.MyCompanyDetail.as_view(),name='my_company_detail'), ] .html that throws error I click on this href: {{request.pk }} and I receive the error: NoReverseMatch at /console/request/201/. Reverse for 'my_company_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['console/(?P[0-9]+)/mycompany/$'] -
Vs code remote container not stopping on breakpoints
I have a setup with both a devcontainer.json and a launch.json with the new Remote Container plugin in vs-code. But I cant get the breakpoints working. I get the app to launch and can browse it, but the breakpoints are not getting hit, am I missing something in my launch.json? { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "0.0.0.0:8000", ], "env": { "PYTHONUNBUFFERED": 1, "ENV": "local", "DJANGO_SITE_ID": 1, "DJANGO_SETTINGS_MODULE": "project.settings.local1", } } ] } -
How to display all the user_permission of user in django template
Here i am trying to display all the user_permissions of some particular user but i am getting nothing though is_superuser=True for this user.How can i do it ?? views.py def profile_user(request,id): user = get_object_or_404(User,id=id) user_permissions = user.user_permissions.all() #user_permissions = Permission.objects.filter(user=user) return render(request,'user_profile.html',{'user':user,'user_permissions':user_permissions}) template <p>User Roles: <b> {% for permission in user_permissions %} {{permission}} {% endfor %} </b></p> -
Change 5th number from list
I have a one function for my calendar def formatweek(self, theweek, events): week = '' for d, weekday in theweek: #return f'<tr style="color:blue";> {week} </tr>' week += self.formatday(d, events) return f'<tr> {week} </tr>' where theweek is a list of pairs: [(1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6)] [(8, 0), (9, 1), (10, 2), (11, 3), (12, 4), (13, 5), (14, 6)] [(15, 0), (16, 1), (17, 2), (18, 3), (19, 4), (20, 5), (21, 6)] [(22, 0), (23, 1), (24, 2), (25, 3), (26, 4), (27, 5), (28, 6)] [(29, 0), (30, 1), (31, 2), (0, 3), (0, 4), (0, 5), (0, 6)] Where the first number(for example(1)) in pairs is day in month (1.januar) and the second is a number for week name (0-Monday, 1-Thuesday etc...) d and weekday become an int in loop. d = days of month (1,2,3,4....)and Weekday = number for days (Mon - 0, Tue - 1 etc...). It returns this return f'<tr> {week} </tr>'for the table. And I would like to make and 5th and 6th number in week (Saturday, Sunday) to return not only above one but also something like this return f'<tr style="color:blue";> {5 (or … -
How to monkeypatch a Python class for an entire Django application?
The main permission checking methods in Django REST Framework, BasePermission's has_permission and has_permission, both return True, effectively making any permission checking allow by default. Since this is counter to a security mindset and OWASP recommendations I would like to fix the implementation locally before reporting a bug. I could fix it for my own classes by subclassing BasePermission but I want to ensure that every subclass of BasePermission used anywhere does deny by default. Can I replace the functionality of these two methods for every subclass in my Django system? To be clear, I am not trying to do this for testing purposes. -
Django objects and openpyxl cells. How to set cell value like a value of django object field?
I have to write a block of code wich generate xlsx report from django dataset( few models). Frame of the report have more difficult structure than usual x rows y columns (some cells was united). It should look like that: So I wrote view function: from cut.models import * from django.http import HttpResponse from openpyxl.workbook import Workbook from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font def get_report(request): rent_test = Renters.objects.all response = HttpResponse( content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ) response['Content-Disposition'] = 'attachment; filename=FORM_1-IL.xlsx'.format() workbook = Workbook() worksheet = workbook.active worksheet.title = 'A_REPORT' worksheet.merge_cells('A2:A5') #... worksheet.merge_cells('M4:M5') worksheet['A2'].value = 'name of forestry' #...etc. columns = [ 'only_one_column' ] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = worksheet.cell(row=row_num, column=col_num) cell.value = column_title workbook.save(response) return response So all it are understandable and simple. But how I can use django fields ? I wish to transfer them to relative cell( value of field instead red font "field value" -
Django: maintain sessions with multiple domains
I have two/multiple domains say, foo.com and bar.com and both have the same backend, which means both domains redirect the coming requests to same "web instance" hosted somewhere else. Current Behaviour If a user login in foo.com, he/she also need to login in bar.com in order to access any end-point/URL such as bar.com/some/url/end-point/. The SESSION_COOKIE_DOMAIN may do something if I've the domains with a common pattern. Unfortunately, I don't. Question How can I maintain user sessions in multiple domains? -
How do I perform an action on publication within Wagtail?
I'd like to perform a function when a Wagtail Page object is published (specifically, I have a utility method that sends out emails notifying subscribers that a new blog page is available). Is there a method I can override (either save or something else) that will let me run this function on publication, or even better, on first publication of the object? -
Any too way to handler IntegrityError in django?
In django the exception IntegrityError could be caused by a lot of reasons. Some times this error means a unique conflict. Some other times this could be caused by some foreign key check. There could be some other reasons for this exception too. Currently we can only know the root cause by convert the exception into text: (1062, "Duplicate entry '79d3dd88917a11e98d42f000ac192cee-not_created' for key 'fs_cluster_id_dir_e8164dce_uniq'") But this is very unfriendly for program to identify. Is there any way for code to identify the root cause of exception? -
Django can only find part of the static file in the same directory?
All the static files were put in the static subdirectory of my project root path, the path looks like below: CMDB ├── assets ├── CMDB ├── domain ├── manage.py ├── static ├── users all the static files in static directory like below: static/ └── adminlet-2.4.10 ├── bower_components ├── dist └── plugins in my base.html template, I load static files like below: <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/bootstrap/dist/css/bootstrap.min.css' %}"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/font-awesome/css/font-awesome.min.css' %}"> <!-- Ionicons --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/Ionicons/css/ionicons.min.css' %}"> <!-- Theme style --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/dist/css/AdminLTE.min.css' %}"> and this parts works find. another several css and js files were include by: <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/bootstrap/dist/css/bootstrap.min.css' %}"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/font-awesome/css/font-awesome.min.css' %}"> <!-- Ionicons --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/bower_components/Ionicons/css/ionicons.min.css' %}"> <!-- Theme style --> <link rel="stylesheet" href="{% static 'adminlet-2.4.10/dist/css/AdminLTE.min.css' %}"> and they can not be found by django server. In explorer, it reports 404 error. the static files part in settings.py below: STATIC_URL = '/static/' STATIC_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Django version is 2.2.2 -
How to programatically add product images in django oscar?
I am currently programatically importing products into my product catalog, however, I am having difficulty uploading images for each product. Here's what my code looks like: # frobshop/custom_utils/product_importer.py from oscar.apps.catalogue.models import Product ... for product in my_product_import_list: ... product_entry = Product() product_entry.title = my_product_title product_entry.product_class = my_product_class product_entry.category = my_category product_entry.primary_image = "product_images/my_product_filename.jpg" product_entry.save() The details such as product title and product class are successfully saved when I check using the development server, however, I am unsure how to set an image for each product. The entire product_images folder was initially located outside of my media directory, but since I wasn't getting any results, I copy pasted the entire folder of my images into the media directory but still with no results. I am assuming that quite a number of steps are being skipped, and maybe there's a convention on how to arrange images in the media directory. However, I am not sure where to find these steps and conventions. Here's the portion of my settings.py file that deals with my installed apps, the media directory, and static files: # frobshop/frobshop/settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.flatpages', 'compressor', 'widget_tweaks', ] + get_core_apps(['custom_apps.shipping', 'custom_apps.payment', 'custom_apps.checkout']) … -
django select_related('created_by').... what is the context variables?
i use select_related, and query log is good how can i use the context variables 'posts' '{{post.username}}' is not work.... [model.py] class Post(models.Model): `subject = models.CharField(default='', max_length=255) content = models.TextField(default='') created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) [view.py] class PostListView(LoginRequiredMixin, ListView): context_object_name = 'posts' def get_queryset(self): queryset = Post.objects.select_related('created_by').order_by('-id') return queryset [template.html] ` `No. `subject `author `date ` ` ` `{% for post in posts %} ` ` {{ forloop.counter }} ` {{ post.subject }} ` {{ post.username }} `{{ post.created_at }} ` `{% endfor %} ` [queryset queries] SELECT Posts.id, Posts.subject, Posts.content, Posts.created_at, Posts.created_by_id, auth_user.id, auth_user.password, auth_user.last_login, auth_user.is_superuser, auth_user.username, auth_user.first_name, auth_user.last_name, auth_user.email, auth_user.is_staff, auth_user.is_active, auth_user.date_joined FROM Posts INNER JOIN auth_user ON (Posts.created_by_id = auth_user.id) ORDER BY Posts.id DESC; -
How to grab web service data from a website and show it in a HTML using Python?
I can't show this data in a table using Python, I just want to show this web service data in a table in an HTML file using Python This is the web service data that I am trying to output into a table for viewing: {"r":0,"msg":null,r":[{"p":"0128982","dd":"D1","dcNo":"1902","vNo":"01208212", "od":"2016-03-01","dd":"2011-01-02","dt":"00:00","nOp":"1","S":"M","status":"S","aL":[{"oDD":"D2","oDD":"2019-06-03","oDD":"01:30","cBy":"XASNH","cO":"2019-06-07","rc":"FCST"},{"olddd":"D3","olddd":"2019-06-04","olddt":"03:30","cBy":"XRCA4","On":"2019-06-07","reasonCode":"WOW"}]}]} I did a request like this in my views.py python page, but I am not sure how I would show this request in an HTML page def index(request): url = """http://example_blah/blah/blah""" r = requests.get(url) data_df = pd.read_json(r.text) data_df return render(request, 'users/index.html', {'r': r}) -
Npm module not found, from npm to yarn
I'm having some problems with changing my frontend that works with Django rest framework (on the same port). The frontend is based on React. So I had my old src React folder and that worked with npm first and I received the new frontend that I need to start with yarn (it works with npm start as well, before implementing in Django folder). So now I just replaced src folders and run npm install, but what I can see that package.json is not updating. In my src/index.js I had a real difference, so in the first src folder (old template) I had only import App from './components/App'; So I changed it to import NextApp from './NextApp'; because that was that main react file... but in the secound, new template I had src/index.js like import React from "react"; import ReactDOM from "react-dom"; import NextApp from './NextApp'; import registerServiceWorker from './registerServiceWorker'; // Add this import: import {AppContainer} from 'react-hot-loader'; // Wrap the rendering in a function: const render = Component => { ReactDOM.render( // Wrap App inside AppContainer <AppContainer> <NextApp/> </AppContainer>, document.getElementById('root') ); }; // Do this once registerServiceWorker(); // Render once render(NextApp); // Webpack Hot Module Replacement API if (module.hot) { … -
How to grab web service data and show it in a table in python?
I can't show this data in a table using Python, I just want to show this web service data in a table This is the web service data that I am trying to output into a table for viewing {"returnCode":0,"message":null,"resultList":[{"poNo":"0000123456","deliveryDock":"D1","dcNo":"DC01","vendorNo":"0001112222", "orderDate":"2019-06-07","deliveryDate":"2019-06-02","deliveryTime":"00:00","noOfPallets":"10.0000","source":"MANUAL","status":"Scheduled","auditList":[{"oldDeliveryDock":"D2","oldDeliveryDate":"2019-06-03","oldDeliveryTime":"01:30","changedBy":"XASNH","changedOn":"2019-06-07","reasonCode":"FCST"},{"oldDeliveryDock":"D3","oldDeliveryDate":"2019-06-04","oldDeliveryTime":"03:30","changedBy":"XRCA4","changedOn":"2019-06-07","reasonCode":"WOW"}]}]} ======================================================================== -
Posting data to database through a "workflow" (Ex: on field changed to 20, create new record)
I'm looking to post new records on a user triggered basis (i.e. workflow). I've spent the last couple of days reasearching the best way to approach this and so far I've come up with the following ideas: (1) Utilize Django signals to check for conditions on a field change, and then post data originating from my Django app. (2) Utilize JS/AJAX on the front-end to post data to the app based upon a user changing certain fields. (3) Utilize a prebuilt workflow app like http://viewflow.io/, again based upon changes triggers by users. Of the three above options, is there a best practice? Are there any other options I'm not considering for how to take this workflow based approach to post new records?