Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
disable the selected option once the form is submitted in django
As the title says, I want to achieve for example this. I'll click on the 'submit' button after the dates are selected from the dropdown. The form submits and redirects back to the same page again but this time not showing up or disable those dates which were selected previously already. The selected date is being saved into the database via forms but how would I disable the already entered data in the template. here's the code so far. form.py class PublishForm(forms.ModelForm): class Meta: model = Publish fields = ['dates'] model.py dates = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class Publish(models.Model): dates = models.CharField(max_length=255, choices = dates) def __str__(self): return self.dates view.py def add(request): if request.method == 'POST': form = PublishForm(request.POST) if form.is_valid(): form.save() return redirect('mainapp:add') else: form = PublishForm() context = { 'form' : form } return render(request, 'mainapp/add.html', context) add.html <form class="site-form" action="" method="post"> {% csrf_token %} {{form}} <button type="submit">create</button> </form> Also, after a long research I've come to a solution which can be done via multi-step form. But I have no idea how its done. Kindly need your suggestion on this. How would I approach … -
display data in tables in django
Need help with displaying data in gridview . I m new to all this. I m able to read and display the data on a page from mongodb but need to display in a table. Can someone advise where should i tweak the tables and what should i be putting in ? In order to make data display in gridview? 20 million $ question for me now is where should i be adjusting the following snippet in my code to give me gridview <table> <tr> <th>Field 1</th> <th>Field N</th> </tr> {% for item in query_results %} <tr> <td>{{ item.field1 }}</td> ... <td>{{ item.fieldN }}</td> </tr> {% endfor %} </table> My model.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100,primary_key=True) desc = models.CharField(max_length=100) urls = models.CharField(max_length=100) #image = models.FilePathField(path="/img") class Meta: db_table = "spiderCollection1" additional tables.py import django_tables2 as tables from .models import Project import itertools class ProjectTable(tables.Table): class Meta: model = Project template_name = "django_tables2/bootstrap.html" title = tables.Column("title") desc = tables.Column("desc") urls = tables.Column("urls") following is views.py from django_tables2 import SingleTableView from django.shortcuts import render from projects.models import Project from projects.tables import ProjectTable # Create your views here. class ProjectListView(SingleTableView): model = Project table_class … -
overriding django template raises TemplateSyntaxError
I'm trying to reset the password_reset_email.html template in my django app by adding this file in templates/registration/password_reset_email.html: {% load i18n %}{% autoescape off %} {% blocktranslate %}You're receiving this email because you requested a password reset for your user account.{% endblocktranslate %} {% translate "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% translate 'Your username, in case you’ve forgotten:' %} {{ user.get_username }} {% translate "Thanks for using our app!" %} {% blocktranslate %}The team{% endblocktranslate %} {% endautoescape %} However it raises a TemplateSyntaxError: 'blocktranslate', expected 'endautoescape'. Did you forget to register or load this tag? What am I doing wrong? -
Custom fields not coming during user creation in Django
I have created a custom user creation form: class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField( label='Password Confirmation', widget=forms.PasswordInput) first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') class Meta: model = User fields = ['email', 'first_name', 'last_name'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user Here is my model: class User(AbstractUser): """ Our own User model. Made by overriding Django's own AbstractUser model. We need to define this as the main user model in settings.py with variable AUTH_USER_MODEL *IMPORTANT* """ is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField( max_length=255, unique=True, verbose_name="email address" ) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email Here is the admin.py class UserAdmin(BaseUserAdmin): add_form = UserCreationForm list_display = ('email', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_admin',)}) ) search_fields = ('email',) ordering = ('email',) admin.site.register(User, UserAdmin) Note the first_name and last_name. These two fields aren't coming in the form. What am I doing wrong due to which these fields … -
Nothing returned when editing profile page
Trying to edit a profile using a form I have that should allow a user to edit her first name, last name and email. Problem is when I try editing the form nothing happens. Still trying to learn Django so could be something I am missing/not getting right. Here is my form; <form id="edit-mentor-profile" class="form-horizontal" method="post" > {% csrf_token %} <div class="form-group"> <label for="photo" class="col-sm-2 control-label">Avatar</label> <div class="col-md-6"> <div class="media v-middle"> <div class="media-left"> <div class="icon-block width-100 bg-grey-100"> <i class="fa fa-photo text-light"></i> </div> </div> <div class="media-body"> <a href="#" class="btn btn-white btn-sm paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated> Add Image<i class="fa fa-upl"></i></a> </div> </div> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-md-2 control-label">Full Name</label> <div class="col-md-8"> <div class="row"> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control" id="edit-mentor-profile-first_name" placeholder= {{ user.first_name }}> <label for="edit-mentor-profile-first_name"></label> </div> </div> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control" id="edit-mentor-profile-last_name" placeholder={{ user.last_name }}> <label for="edit-mentor-profile-last_name"></label> </div> </div> </div> </div> </div> <div class="form-group"> <label for="email" class="col-md-2 control-label">Email</label> <div class="col-md-6"> <div class="form-control-material"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input type="email" class="form-control" id="edit-mentor-profile-email" placeholder={{ user.email }}> <label for="edit-mentor-profile-email"></label> </div> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-6"> <div class="checkbox checkbox-success"> <input id="checkbox3" type="checkbox" checked=""> <label for="checkbox3">Subscribe to our Newsletter</label> </div> </div> </div> <div class="form-group margin-none"> … -
Django upload CSV from admin page and process using views
I want to uploadc csv files only and any one of them can be uploaded from admin page. Now, I don't really need to save file in database, the csvs are processed and data from the file is inserted into the database. So, it is like using import csv in postgres but manually due to some constraints. I have a funcion in views.py which does the job but for a custom template, I want this views funtion to work with admin page. Can anyone help with providing details on how to do it? I tried change_form.html but still don't know how to attach the processing part to post save part. models.py class UploadData(models.Model): details = models.FileField(upload_to='media/',blank=True,null=True) login_details = models.FileField(upload_to='media/',blank=True,null=True) change_form.html {% extends "admin/change_form.html" %} {% block title %}Upload{% endblock %} {% block content %} {% load static%} {% if user.is_superuser %} <head> <link rel='stylesheet' href="{% static 'css/log.css' %}" /> </head> <form action="" method="POST" enctype="multipart/form-data"> {%csrf_token%} Upload Login Information: <input type="file" accept=".csv" name="login_details" multiple/><br> Upload Details: <input type="file" accept=".csv" name="details" multiple/><br> <button type="submit">Upload</button> {{message}} </form> {% else %} <h1>You are not authorized</h1> <a href="{% url 'home' %}"> {% endif %} {% endblock %} views.py @superuser_only @login_required def upload(request): if request.method == … -
.NET Core vs Django in 2020? [closed]
I'm stuck with ASP.NET CORE vs Django Rest Framework for my new project. Django is a proven and well-established framework but the new .NET Core looks even more promising. Some of my questions would be, It is worth while to put extra effort in learning .NET Core ? (Considering the job market for .Net Core vs Django) Is .NET core mature enough currently ? Does Statically typed language provide better testing capabilities ? Apart from speed (.NET Core) vs simplicity (Django); what are the other benefits of .NET core over Django ? -
Django error browser is unable to connect at 127.0.0.1:8000/products/
I am creating my first Django project. I have successfully installed Django version 2.1. When I created the project, the project was successfully launched at the url 127.0.0.1:8000. Then I ran the command python manage.py startapp products. Products folder was also successfully created in the project. Then inside the products folder, inside the sub folder migrations, I opened: views.py from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse('Hello World') then products/urls: from django.urls import path from . import views urlpatterns = [ path('', views.index) ] Inside the main project folder, I opened urls.py and I modified the code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('products/', include('products.urls')) ] Then the url http://127.0.0.1:8000/products/ was not opening on browser. Browser is giving the "Unable to connect" error. I am using the PyCharm IDE. I will really appreciate your answer. -
need help to save different date in django
I am creating a app using django rest-framework to record mensuration date.I have to put a validation to date fields like if one date is already entered in database the app should avoid to enter same date which is already exist in database. Need help to do that -
My model formset was working fine until I added the formset attribute to modelformset_factory()
I finally got my model formset to work. As a last tweak I added the formset attribute and a BaseFormSet class to validate the user had completed at least form in the formset. I'd done the same on other formsets (but not model formsets), so I assumed the code would work fine. However it throws an exception that I can't solve. Views.py: def reconciliation_action(request,pk): ledger = get_object_or_404(Ledger,pk=pk) line_items = LineItem.objects.filter(ledger=ledger, reconciliation_date=None).order_by('-journal_entry__date') LineItemReconciliationFormSet = modelformset_factory(LineItem, extra=0, fields=('reconciliation_action',), widgets={'reconciliation_action':forms.CheckboxInput()}) #Following line doesn't work. The formset attribute breaks things. #LineItemReconciliationFormSet = modelformset_factory(LineItem, formset=BaseReconciliationFormSet, extra=0, fields=('reconciliation_action',), widgets={'reconciliation_action':forms.CheckboxInput()}) if request.method == 'POST': formset = LineItemReconciliationFormSet(request.POST) form = ReconciliationForm(request.POST) if formset.is_valid() and form.is_valid(): formset.save() # Count checked boxes for later confirmation message. no_of_checkboxes = 0 for form1 in formset: if form1.cleaned_data['reconciliation_action'] == True: no_of_checkboxes += 1 # If date was set then save it to lineitems if form.cleaned_data['date']: for line_item in line_items: if line_item.reconciliation_action == True: line_item.reconciliation_date=form.cleaned_data['date'] line_item.save() if form.cleaned_data['date']: messages.success(request, str(no_of_checkboxes)+" items successfully reconciled in "+ledger.name) return HttpResponseRedirect(reverse('journal:reconciliation_show_all')) else: messages.success(request, str(no_of_checkboxes)+" items successfully saved for later reconciliation in "+ledger.name) return HttpResponseRedirect(reverse('journal:reconciliation_action', kwargs={'pk': pk}) ) else: formset = LineItemReconciliationFormSet(queryset=line_items) #<-- LINE 55 WHERE THERE ERROR OCCURS!!!! form = ReconciliationForm() return render(request, 'journal/reconciliation_action.html',{'ledger': ledger, 'line_items': line_items, 'formset': … -
Getting page not found error when updating profile
I am trying to use a form to edit the details of a profile. However, I keep encountering this error message Page not found (404) Request Method: POST this is edit html file <form class="form-horizontal" action="app-instructor-profile.html" method="post" > <div class="form-group"> <label for="photo" class="col-sm-2 control-label">Avatar</label> <div class="col-md-6"> <div class="media v-middle"> <div class="media-left"> <div class="icon-block width-100 bg-grey-100"> <i class="fa fa-photo text-light"></i> </div> </div> <div class="media-body"> <a href="#" class="btn btn-white btn-sm paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated> Add Image<i class="fa fa-upl"></i></a> </div> </div> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-md-2 control-label">Full Name</label> <div class="col-md-8"> <div class="row"> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control" id="first_name" placeholder= {{ user.first_name }}> <label for="first_name"></label> </div> </div> <div class="col-md-6"> <div class="form-control-material"> <input type="text" class="form-control" id="last_name" placeholder={{ user.last_name }}> <label for="last_name"></label> </div> </div> </div> </div> </div> <div class="form-group"> <label for="email" class="col-md-2 control-label">Email</label> <div class="col-md-6"> <div class="form-control-material"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input type="email" class="form-control" id="email" placeholder={{ user.email }}> <label for="inputEmail3"></label> </div> </div> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-md-2 control-label">Change Password</label> <div class="col-md-6"> <div class="form-control-material"> <input type="password" class="form-control" id="password" placeholder="Password"> <label for="inputPassword3">Password</label> </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-6"> <div class="checkbox checkbox-success"> <input id="checkbox3" type="checkbox" checked=""> <label for="checkbox3">Subscribe to our Newsletter</label> </div> </div> </div> <div class="form-group margin-none"> <div … -
Url in template from site-package
i'm building my first Django app so i'm know i'm missing a lot of things, but i installed a gallery for my site and is inside site-packages, i set the url inside urls.py and it looks like this : from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from contacto.views import Home,Contacto urlpatterns = [ path('admin/', admin.site.urls), path('gallery/', include('gallery.urls'),name='gallery'), path('home/',Home,name='home'), path('contacto/',Contacto,name='contacto') ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I can perfectly access the gallery and its functionalities if i write the url in the browser, but i cannot reference the gallery Url inside my template like the other Urls using {% url 'gallery' %}, i keep getting this error : Reverse for 'gallery' not found. 'gallery' is not a valid view function or pattern name. -
How can I separate two different style file in Django Template?
I have Django + React.js hybird app, basically React webpack creates js files and my webpack-loader loads these js files to my index.html file. My header, navbar, footer are builded with Django Template and they have own css files (load static). But also my React app has own style files (they extract on same file with my bundle.js) and If I want use them together, they get mixed up! How can I separate two style files completely? index.html: <!DOCTYPE html> {% extends "base/layout.html" %} {% load static %} {% load render_bundle from webpack_loader %} {% block body %} {% render_bundle 'main' 'css' %}} <div class="main-container"> <div id="react-app"></div> </div> {% render_bundle 'main' 'js' %} {% endblock body %} webpack-config.js: const path = require('path'); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const ExtractText = require('extract-text-webpack-plugin'); module.exports = { entry: path.join(__dirname, 'src/js/index'), output: { path: path.join(__dirname, '../../media/output/'), filename: '[name]-[hash].js' }, plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json', }), new ExtractText({ filename: '[name]-[hash].css', }), ], module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.(ttf|eot|svg|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/, use: [ { loader: 'file-loader', }, ], }, { test: /\.css$/, loader: ['style-loader', 'css-loader'], }, { test: /\.scss$/, use: ExtractText.extract({ fallback: 'style-loader', … -
My custom widget model in Django won't submit data
So I created a custom widget for one of my form elements, and I have it rendered as a div where contenteditable='true', because I am making a simple WYSIWYG editor for my site. Here is the custom widget class DivTextWidget(forms.Textarea): def render(self, name, value, attrs=None,renderer=None): super().render(name, value, attrs) flat_attrs = flatatt(attrs) html = """ <div contenteditable='true' id='%(id)s' name='text'></div> """ % { 'attrs': flat_attrs, 'id': attrs['id'], } return mark_safe(html) And now here is the Post model class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) title = models.CharField(max_length=75) There is more the models, but the rest isn't applicable to this. And now here is my form. class PostForm(forms.ModelForm): text = forms.CharField(widget=DivTextWidget()) class Meta(): model = Post fields = ['title','text','group','image','file','tags','spoiler','NSFW','tag'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass text-title','placeholder':'Title'}), } def clean(self): cleaned_data = super(PostForm, self).clean() title = cleaned_data.get('title') text = cleaned_data.get('text') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].label = "" self.fields['text'].label = "" Again, I removed all unrelated things from the form. So in my HTML, I have the form all set up and I know it works because when I had the default Textarea, it all went through fine. I know that divs probably don't go through forms at all, but I am just wondering if there … -
ValueError: <Blog> needs to have a value for field "id" before this many-to-many relationship can be used at Admin Page
I have two models models.py class Tag(models.Model): name = models.CharField(max_length=120) class Blog(models.Model): title = models.CharField(max_length=200) description = models.TextField() tags = models.ManyToManyField(Tag, verbose_name='tags') admin.py class BlogAdmin(admin.ModelAdmin): model= Blog filter_horizontal = ('tags',) admin.site.register(Tag) admin.site.register(Blog, BlogAdmin) While saving Blog object using django default admin panel i am getting error like ValueError: "" needs to have a value for field "id" before this many-to-many relationship can be used. -
_("str") in Python , meaning of both
I am a starter in python. Now I am working on a Django project. I saw many lines of code containing _('password'), _('last_login') etc. Check the code below: username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) What is the use of _('username')? -
ReferenceError: ReconnectingWebSocket is not defined in django channels 2
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chatSocket = new ReconnectingWebSocket(ws_scheme + ':///' + window.location.host + '/chat/'+ message_id); -
Difference between uwsgi_param and proxy_set_header
When using Nginx as a reverse proxy with uWSGI/Django, what is the difference between uwsgi_param and proxy_set_header in an Nginx configuration? Background: I'm doing some tinkering around with security-related HTTP headers in Django.I have a setup using Nginx as reverse proxy, with the uWSGI serving the Django app and being the proxied server: _____________________________________ | | http or https* | uwsgi | browser --------------> | nginx --------------> uWSGI/Django | |____________________________________| * http 301-redirects to https equivalent; https response returns Strict-Transport-Security header There are two mechanisms by which http requests 'become' https requests here: Nginx redirects port 80 requests to 443, e.g. the request history chain has a 302 redirect HTTPs responses contain a Strict-Transport-Security: max-age=31536000; includeSubDomains; preload response header; in this case, there is never a 302 redirect; the browser takes the client http request and forces it to its https equivalent right off the bat. All that is to say, the related Django settings look like: # tail -n4 project/settings.py SECURE_HSTS_SECONDS = 31536000 # Seconds; *USE A SMALLER VALUE FOR TESTING FIRST!* SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") Nginx config: server { server_name .mydomain.com; listen 80; return 301 https://$host$request_uri; } server { location / { … -
Django-ckeditor's content not being styled as the con
I'm using django-ckeditor 5.8.0 settings.py CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'width': '100%', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': [ 'Styles', 'Format', 'Font', 'FontSize']}, '/', {'name': 'yourcustomtools', 'items': [ 'CodeSnippet', ]}, ], 'toolbar': 'YourCustomToolbarConfig', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'uploadimage', 'codesnippet', ]), } } models: content = RichTextUploadingField() CKEditor's static files are served in admin mode but the css file(contents.css) doesn't load in other views elsewhere. I'm using ManifestStaticFilesStorage and after running collectstatic, files exist where it should. I've also added these three line in the template: <script>window.CKEDITOR_BASEPATH = "{% static '/ckeditor/ckeditor/' %}";</script> <script type="text/javascript" src="{% static 'ckeditor/ckeditor-init.js' %}" data-ckeditor-basepath="{% static 'ckeditor/ckeditor/' %}" id="ckeditor-init-script"></script> <script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script> Here's the image of the html from the browser : Clicking on those two js files also shows its content, meaning they are accessible. contents.css file isn't loaded, hence no styling. Same story on the development server too. Any suggestions will be appreciated. -
How inspect Django models attributes and fields
Currently i am faced with a need to extend django's built-in auth user model extend and customize it for my needs. While i am reading django official documentation in explanation code use models which so purely documented or if code is documented it's dispersed throughout several links on the same django documentation. I thought that certainly developers which faced with the same problem before me wrote modules which can inspect django-modules and other django-source-code i found some of mentioned modules tools like django-inspect or also django-inspect-models but as i see their profile pages on PyPi my conclusions was that they have problems with supporting recent django versions etc. Can anyone suggest me the appropriate module ? Also before i got this thoughts i tried to find on django github source code models which i needed. But it wasnt easy because django source code structure difficult for me to understand. Can anyone suggest me appropriate and easy method to find models in django source code for example for this model from django.contrib.auth.models import User Where is i imported User model in django source code located ? -
How to start a Django app from another python script
I have multiple different User Interfaces for a Python app which get injected at runtime, one of which is a Django App. NOTE - This is not a production app. This is just for my own usage on my own PC. I'm not worried about security at ALL. For example, I have a CLI user interface, as well as a Django UI. My main file is something like this: def main(): config , test_config = load_test_config(Config, TestConfig) user_interface = None if config.user_interface() == "cli": from frontend.Cli import Cli user_interface = Cli() elif config.user_interface() == "django": from frontend.Django import Django user_interface = Django() app = TradingApplication(user_interface) app.start() if __name__ == "__main__": main() The application is quite simple for right now: # This is the main application that gets fired up. class TradingApplication(object): # We inject the UI, this could be a CLI or a web app, or desktop app etc. def __init__(self, user_interface): # Save and register UI with the app self.user_interface = user_interface # Start the UI and feed the app in as well, so the UI can make calls into the app def start(self): self.user_interface.run(self) All it does is invoke the User interface and pass a reference to itself … -
How to import a django model into an external python script
I want to be able to import my Django models into an external script to do things such as parse inputted URLs. I have tried creating a python script within the root folder of a Django app and simply importing the model as I would in views.py, however, I keep getting this error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have searched through the Django docs but so far, I haven't been able to find anything. Anybody got any ideas? Thanks! -
collectstatic yielding the error No file or directory : '/app/static' despite having that directory present
I am trying to deploy a django app via Heroku. Initially I was getting errors on deployment and set heroku config:set DISABLE_COLLECTSTATIC=1. Once collectstatic was disabled the app deployed without errors. Now that I want to add my static files I unset heroku config:unset DISABLE_COLLECTSTATIC and tried deploying again but received errors saying my push was rejected. Here is what I believe is the relevant portion of the traceback: FileNotFoundError: [Errno 2] No such file or directory:'/tmp/build_7f46d0854acc9adac5d065056bd2bc4f/s Error while running '$ python manage.py collectstatic --noinput'. My next step was to run heroku run python manage.py collectstatic to get a more accurate traceback and then I received the following error: FileNotFoundError: [Errno 2] No such file or directory: '/app/static' This step puzzles me because I have exactly that directory in my app: lang_site -- __psyache__ -- static ---- lang_site ------ pic.jpg ------ style.css -- __init__.py -- settings.py -- urls.py -- views.py -- wsgi.py As a shot in the dark I added the literal directory app/static/ in the same directory as settings.py only to yield the same error. I also added the extra static_dir and static_root lines in my settings.py as seen below: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) … -
How to query model instances outside of the current object
I have the following models: class PermanentList(models.Model): permanent_employees = models.ManyToManyField(Employee, through='PermanentMembership') class EventList(models.Model): event_employees = models.ManyToManyField(Employee, through='EventMembership') class Employees(models.Model): email = models.EmailField() And the following through models to handle the M2M relationship: class PermanentMembership(models.Model): permanent_list = models.ForeignKey(PermanentList, null=True, on_delete=models.PROTECT) permanent_employees = models.ForeignKey(Employee,null=True, on_delete=models.PROTECT) class EventMembership(models.Model): event_list = models.ForeignKey(EventList, null=True, on_delete=models.PROTECT) event_employees = models.ForeignKey(Employee,null=True, on_delete=models.PROTECT) def clean(self): // missing code 2 Questions: How can I validate each event_employee using def clean(self): to ensure that if an Employee is already on a PermanentList they can not be added to a EventList? If an Employee is already on an EventList how can I create a function to transfer them to a PermanentList? Can this be done on a Model class or would it have to be in a View? How would I go about this? -
Django REST Framework SerializerMethodField vs Django model methods
When creating a serializer in Django REST Framework, I understand that I can create a SerializerMethodField that creates a new read-only method for a model. For example: class AnswerSerializer(serializers.ModelSerializer): likes_count = serializers.SerializerMethodField() class Meta: model = Answer exclude = ["a_field"] def get_likes_count(self,instance): return instance.voters.count() A similar thing could also be done using a property or method in the models.py file: class Answer(models.Model): @property def get_likes_count(self): return voters.count() So my question is: What are the pros and cons of each? I understand that SerializerMethodField is for read_only operations but aside from that are not sure. Is it best practice to keep the models.py file for model fields only, and to use signals for update/create operations and serializers for read operations?