Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
a view with 2 treeviews and drag and drop from one to another
I want to create a form with 2 treeviews (each treeview is based on a table of my database with recursive data). And I want to be able to create a drag and drop form one treeview to the other in odrer to link data between the data tables. I tried django-treenode but i can t understand to use it for doing my view. -
Constrain Django model by field value
Consider the following Django model: class Account(models.Model): ACCOUNT_CHOICES = [ ('m', 'Main',), ('s','Secondary') ] user = models.ForeignKey(User) level = models.CharField(max_length=1, choices=ACCOUNT_CHOICES) How can I enforce a database constraint of a maximum of one 'Main' account per user, while still allowing any number of 'Secondary' accounts per user? In a sense, I want unique_together for user and level, but only when the value of level is m. I know that I can manually check on saving, but I would prefer the database to check automatically and raise an IntegrityError when appropriate. -
creating custom profiles for selected user types
1.I have multiple type of users in my project. i have created a single signup page. in the signup page i have option to select the type of user.based on the selection a related profile should be created and the type of user should be logged into their particular profile page..for example..if the type of user selected is student then after signup a student_profile should be created and student should be logged into that.. similar for professional and other user types.I have used django auth user model to create signup.. 2. I have many custom profile forms for each user types and no idea how to integrate it..model is below: what Please don't suggest me this link cz i don't wanna go with this approach since they use a signup for each user type but i have only one signup for every user type.. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html user registration in forms.py: class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat password', widget=forms.PasswordInput) class Meta: model = User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] def clean_email(self): email = self.cleaned_data.get('email') username = self.cleaned_data.get('username') if email and User.objects.filter(email=email).exclude(username=username).exists(): raise forms.ValidationError(u'Email addresses … -
Add individual users to Project in Django
I am building a basic project management app using Django, where a Project can have any number of users. How can I create a form to add users one at a time? The default behavior of Django provides multi-select fields for many to many relationships. class Project(models.Model): project_number = models.IntegerField() name = models.CharField(max_length=100) design_manager = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='project_design_manager', null=True, blank=True) permit = models.CharField(max_length=100, blank=True, default='') is_active = models.BooleanField(default=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='project_users') I want a dynamic field that allows you to add one user at a time. -
Create Extended User Object with Django Rest Auth
I'm using django-rest-auth with django-rest-framework. I have the default API endpoints already generated. They appear like so: api-endpoints: { login: { create(password, [username], [email]) } logout: { list() create() } registration: { verify-email: { create(key) } create(username, password1, password2, [email]) } user: { read() update(username, [first_name], [last_name]) partial_update([username], [first_name], [last_name]) } } Now, I want to use a custom model called UserProfile, which extends the default user via a OneToOneField as shown below: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) custom_field1 = models.CharField(...) custom_field2... ... The docs state I should create a custom registration serializer. I did some searching around and figured I could try this code as that custom serializer (with cf as an abbreviation for custom_field for this example): class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): user_dict = super().get_cleaned_data() user_dict["c1"] = self.validated_data.get("cf1", '') user_dict["cf2"] = self.validated_data.get("cf2", '') return user_dict However, this does not create an Account object, when a user registers. My two questions are thus: How can I create an Account object on registration? (Is this the appropriate design decision anyway?) (Possibly related to 1) How can I properly create a custom registration serializer? -
probleme de creation des evenements
importation des bibliothques from django.db import models from django.contrib import admin from django.utils.translation import ugettext_lazy as _ code de la classe calendrier class Calendar(models.Model): name = models.CharField(_('name'), max_length=50) slug = models.SlugField(_('slug'), unique=True) def __unicode__(self): return u'%s' % self.name class Meta: verbose_name = _('calendar') ordering = ['name'] creer un evenement class Event(models.Model): title = models.CharField(_('title'), max_length=100) start = models.DateTimeField(_('start')) end = models.DateTimeField(_('start')) calendar = models.ForeignKey("Calendar", on_delete=models.CASCADE) def __unicode__(self): return u'%s' % self.title class Meta: verbose_name = _('event') ordering = ['start', 'end'] creer un calendier class CalendarAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} admin.site.register(Calendar, CalendarAdmin) class EventAdmin(admin.ModelAdmin): list_display = ('title', 'start', 'end') search_fields = ['title'] date_hierarchy = 'start' svp aidez moi suis vraiment bloqué car les views et les templete meme la ne marchent pas -
trying to access a ManyToManyField from db query but returning None
Im tring to access a ManyToManyFireld property after model query but get back None. This is what the model looks like. class Role(models.Model): ROLES = Choices('user', 'staff', 'admin') user = AutoOneToOneField( 'account.User', related_name='_role', primary_key=True, on_delete=models.CASCADE ) role = models.CharField(max_length=10, choices=ROLES, default=ROLES.user) locations = models.ManyToManyField('location.Location', related_name='_role', blank=True) def __str__(self): return '<Role: user={0} ({1})>'.format(self.user_id, self.role) When i call locations on the Role lookup i get back location.Location.None and this is what the query lookup looks like. user_role = Role.objects.get(pk='123249882323') role_locations = user_role.locations print(role_locations) => location.Location.None I want role_locations to return all the locations associated with the Role -
Generating a page dynamically in Django
I'm tyring to generate a page dynamically in Django but i can't find a way to do this. In my DB, i have a table containing some items, this table is "dynamic"; so i will keep adding and removing items from this table. Now, this is what i would like to do: For each of these times, there should be generated a page containing some data about those items. I created a standard view and a standard template like this: views.py def home(request): return render(request, "main/home.html") home.html {% extends "main/header.html" %} {% block content %} { Here should be data about the X item } {% endblock %} I would like to create something like this: When a page is opened, the user is redirected to a page looking like this: site.com/home/item1 or site.com/home/item2, so instead of the line { Here should be data about the X item }, there should be data about the corresponding item. Can someone give me some help? -
Looking for format for KeywordsField.save_form_data
I have a Mezzanine Project and am trying to update the keywords on a blog entry. I am having difficulty getting the format write to call KeywordsField.save_form_data this invokes a js that will update the keywords on a blog post. See below: class PubForm(forms.ModelForm): class Meta: model = BlogPost fields = ['keywords'] def UpdatePub(request, slug): blog_post = BlogPost.objects.get(id=slug) if request.method == 'POST': form = PubForm(request.POST) if form.is_valid(): publish_date = datetime.datetime.now() blog_post.status = CONTENT_STATUS_PUBLISHED publish_date=publish_date tags=form.cleaned_data['keywords'] blog_post.save() KeywordsField.save_form_data(user,blog_post,tags) return HttpResponseRedirect('/write/') else: form = PubForm(instance=blog_post) return render(request, 'blog_my_pub.html', {'form' : form}) It complains that the field user has no attribute 'name'. I have seen this called with (self,instance,data) as the three parameters. I have no idea what self is. Thanks for any input. -
Django Form not recognising model Attribute
Django doesn't seem to recognise the model object in my custom user form. This is the error: -
Incorrect type. Expected pk value, received str
I am trying to use APIVIew to UPDATE and PATCH. Here are my models: class Moment(models.Model): name = models.CharField(max_length=200, blank=False) start = models.CharField(max_length=50,null=True, blank=True) end = models.CharField(max_length=50, null=True, blank=True) outcomes = models.TextField(blank=True) actionPlan = models.TextField(blank=True) forumLead = models.ForeignKey("ForumLead", related_name='forumlead', on_delete= models.CASCADE) platform = models.ForeignKey("Platform", related_name='platform', on_delete= models.CASCADE) kam = models.ForeignKey("KAM", related_name='kam', on_delete= models.CASCADE) typeOfMoment = models.ForeignKey("TypeOfMoment", related_name='typeofmoment', on_delete= models.CASCADE) bigEvent = models.ForeignKey("BigEvent", related_name='bigevent', on_delete= models.CASCADE) campaign = models.ForeignKey("Campaign", related_name='campaign', on_delete= models.CASCADE) def __str__(self): return "{}".format(self.name) class ForumLead(models.Model): name = ... class Platform(models.Model): name = ... class TypeOfMoment(models.Model): name = ... class BigEvent(models.Model): name = ... class Campaign(models.Model): name = ... class KAM(models.Model): name = ... My Serializer: class MomentSerializer(serializers.ModelSerializer): """Serializer for the Moment Objects""" class Meta: model = Moment fields = '__all__' But I am having a Incorrect type. Expected pk value, received str error I have tried to follow the example here a link, but sincerely I am not understanding how to apply it to my case. Any help will be welcomed. -
Passing the error value to the JS code in template. Django
I have purchased one of the Bootstrap templates. I am trying to pass a value from a view or forms.py to my template <div class="input-group"> <textarea class="form-control" rows="4" name="text" placeholder="Hi there, I would like to ..." aria-label="Hi there, I would like to ..." required data-msg="Please enter a reason." data-error-class="u-has-error" data-success-class="u-has-success"></textarea> </div> Exactly this value data-msg="Please enter a reason." How can I do this? pass the value to the JS code or is it possible? how to change the content of the message which will be displayed by the JS code. Any help will be appreciated. -
Angular + Django Api application deployment using Nginx
I have a web application developed using Angular6 + Django rest framework and hosted in aws. Angular application is deployed to my webserver which is public (ip:3.xx.xx.xx) and Django Api is deployed to my appserver which is private(ip:10.xx.xx.xx) I'm using nginx to reverse proxy to the appserver from web server. From the angular application i'm forming the endpoints to call the api functions. Angular Url: http://3.xx.xx.xx:8083/signup Api endpoint :http://10.xx.xx.xx:8081/api/customer/company_registration/ But I'm getting below error when i try to access the api from browser. POST http://10.xx.xx.xx:8081/api/customer/company_registration/ net::ERR_CONNECTION_TIMED_OUT ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: "Http failure response for (unknown url): 0 Unknown Error" name: "HttpErrorResponse" ok: false status: 0 statusText: "Unknown Error" url: null __proto__: HttpResponseBase This is nginx config i tried: server { listen 8083; server_name 3.xx.xx.xx; client_max_body_size 20m; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { root /usr/share/nginx/html/; index index.html; } } server { listen 8081; server_name 10.xx.xx.xx; client_max_body_size 20m; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Handles proxying to Django API location /api/ { #rewrite ^/api(.*) $1 break; add_header 'Access-Control-Allow-Origin' "$http_origin" always; … -
Django-Filer Canonical URLS not working properly (Page not Found)
I am using Django-Filer in my admin on a Django web project which is hosted in PythonAnywhere. I have gone through the installation instructions but I am having trouble accessing the canonical urls the Filer makes for each file. It seems I am being directed to an extended url that Filer.urls is not recognizing (the non-canonical part starts at /filer-public/; this is a directory that is being created and storing my files on the separate PythonAnywhere file directory). Is there an error in my urls syntax? An error in my views.canonical? I am unsure of why plugging in the exact canonical url redirects me to this extended version of the url. Python: 3.7 Django: 2.2 Canonical URL: /filer/sharing/1560887480/39/ ERROR / DEBUGGING SCREEN Page not found (404) Request Method: GET Request URL: http://www.mywebsite.com/filer/sharing/1560887480/39/filer_public/36/ea/36ea58a8-f59c-41ad-9d1f-00a976603eb1/big1.jpg Using the URLconf defined in mywebsitesite.urls, Django tried these URL patterns, in this order: admin/ ^filer/ sharing/(?P<uploaded_at>[0-9]+)/(?P<file_id>[0-9]+)/$ [name='canonical'] The current path, filer/sharing/1560887480/39/filer_public/36/ea/36ea58a8-f59c-41ad-9d1f-00a976603eb1/big1.jpg, didn't match any of these. APP URLS: /mywebsite/.virtualenvs/env/lib/python3.7/site-packages/filer/urls.py # -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import url from . import settings as filer_settings from . import views urlpatterns = [ url( filer_settings.FILER_CANONICAL_URL + r'(?P<uploaded_at>[0-9]+)/(?P<file_id>[0-9]+)/$', # flake8: noqa views.canonical, name='canonical' ), ] APP …