Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django logout and redirection
i am using django authentification to make a oneToone relation with the user table. I try to use decorator @login_required to the next page after the login. when i logout and click on the back button of firefox, i always go to the previous page even if @login_required is apply. but when i refresh it redirect me on the login page. Is it a cache problem? how can i solve it? I want to do it like how the administration works def logout(request): from django.contrib.auth import logout from django.shortcuts import redirect logout(request) request.session.flush() return redirect('/') from django.contrib.auth.decorators import login_required @login_required(login_url='/') def administration(request): do something return something -
Wagtail CMS: RichTextField | URL embeds cannot be found
I have started using Django and Wagtail as an alternative to PHP solutions. I installed Wagtail following the docs and a small tutorial to get started. I have no custom settings in my settings/base.py concerning the WAGTAILEMBEDS_FINDERS. The only changes I made so far to the Home Page: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): templates = "home/home_page.html" banner_title = models.CharField(max_length=100, blank=False, null=True) banner_imgname = models.CharField(max_length=100, blank=False, null=True) body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel("banner_title"), FieldPanel("banner_imgname"), FieldPanel('body', classname="full"), ] And this is the simple home_page template: {% extends "base.html" %} {% load static %} {% load wagtailcore_tags %} {% block body_class %}template-homepage{% endblock %} {% block content %} {{ self.banner_title }} {{ self.imgname_title }} {{ page.body|richtext }} {% endblock %} All simple outputs of text from a CharField and RichTextField work fine, but the embed feature, which I -unfortunately - need the most (blog sharing all kinds of embed stuff), does not work properly. I tried Soundcloud, Deviantart, Vimeo, Instagram. Only YouTube embeds. (To confirm there are no other restrictions for the chosen links I embedded them in an editor of a WP installation (sorry :-)). I … -
Fields in custom serializers.Serializer
Why class Meta: fields = ('name') not working fields not working? I see all object, not only name. It is problem class ProjectsSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField(required=True, allow_blank=False, max_length=100) isActive = serializers.BooleanField() def create(self, validated_data): return Project.objects.create(**validated_data) def update(self, instance, validated_data): instance.id = validated_data.get('id', instance.id) instance.name = validated_data.get('name', instance.name) instance.isActive = validated_data.get('isActive', instance.isActive) return instance class ProjectsCreateSerializer(ProjectsSerializer):enter code here class Meta: fields = ('name') I expect the output of fields in ProjectsCreateSerializer to be {"name": ""} but the actual output is {"name": "","isActive": false} -
Get a list of all active session keys using default session engine?
Using Django's default session engine, not the database-driven one, is it possible to get a list of all active session keys? -
should ihave to install django every time i want to access my project?
please help how to acces the django project when i quit the command prompt it just dissappears and cannot locate it yet.should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command should ihave to install django every time i want to access my project? how can i do it because it keeps asking me django-admin is not an internal command -
django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace
I have a Django projects with two apps, "projects" and "codebox", they were running fine, then at some point I got the following error: django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace If I remove the link to my admin panel from my template this error goes away, but then I can't get to my admin panel: <a href="{% url "admin:index" %}">Admin</a> I was working in the urls.py files when this error occurred, have I changed something that is inadvertently having an impact on the admin link? Here is my top level urls.py file: from django.contrib import admin from django.urls import include, path, re_path urlpatterns = [ # path('', include('projects.urls')), path('projects/', include('projects.urls')), re_path('^accounts/', include('django.contrib.auth.urls')), re_path('^logged_out/', include('projects.urls')), path('codebox/', include('codebox.urls')), ] Here is my urls.py for "projects": from django.urls import path, include from . import views app_name = 'projects' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('insight/', views.InsightView.as_view(), name='insight'), path('logged_out/', views.LoggedoutView.as_view(), name='loggedout'), path('insight/subgen/', views.SubgenView.as_view(), name='subgen'), ] And here is urls.py for my second app, codebox: from django.urls import path, include from . import views app_name = 'codebox' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('form/', views.CreateView, name="form"), ] -
Config nested location NGINX
I have a basic issue about Nginx hope you guys help me: Now I config my location in Nginx: server { location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I want to change it into nested location: http://exp.com/api instead of the current: http://exp.com/ I tried but it's not success: server { location / { location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } } -
In Django Admin, can I display a listing of an unrelated record set alongside an admin form?
My use case is to implement something like a messaging form, allowing an administrator to write a message, then send it to group that they will filter from a list of users, from the User model. This is similar to the messaging to usergroups functionality in Joomla! so it's not too weird a use case. So my admin page for the "Message" model would need to contain the Message creation form and a second recordset of site Users, which could be filtered down to those who the administrator wishes to contact. Is this kind of thing possible in Django Admin, or do I need to dip into heavily customising an admin page? -
Django only create model for testing
I want to test a custom field. How can I create a (dummy) model just for testing? e.g.: myapp/tests/test_fields.py import pytest from django.db import models from ..fields import Percentage100Field class DummyModel(models.Model): percentage = Percentage100Field() @pytest.mark.django_db def test_percentage_100_field(): d = DummyModel.objects.create(percentage=19) -
Django ORM strange behavior; model's data retrieves just by '.values()' and not by direct access
I faced with strange behavior of django orm and cannot solve this problem. Below are interpreter output for some commands. All fields are filled right in the database and all goes fine with using '.values()' Can someone explain me that's wrong and how to fix it? >>> Models.objects.filter(id=55)[0].id 0 >>> Models.objects.filter(id=55).first().id 0 >>> Models.objects.filter(id=55).values()[0]['id'] 55 -
ChartJS graph flickering on mouseover
I'm having a ChartJS graph refresh every half-second, in order to keep up with any changes on the API. The problem I'm having is that the chart flickers and resizes on mouseover. This video captures it pretty well. I'm aware that this issue has been addressed on SO before (e.g., here and here), but the solution proposed there - to make sure to .destroy() the graph before redrawing/refreshing it - isn't solving it for me. Here's the relevant section of my code: function refresh_graph() { {% block jquery %} var chart_endpoint = "{% url 'scenario_chart_data' scenariomarket.id %}" var defaultData = [] var labels = [] $.ajax({ method: "GET", url: chart_endpoint, success: function(data){ defaultData = data.current_prices var mostLikelyIndex = indexOfMax(defaultData) labels = data.descriptions var mostLikely = labels[mostLikelyIndex] document.getElementById('mostLikely').innerHTML = mostLikely; var ctx = document.getElementById('myChart').getContext('2d'); if(myChart){ myChart.destroy(); } var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets : [{ label: 'Market price', data: defaultData, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 2 }] }, options: { elements: { line: { tension: 0 } }, legend: { display: false, }, scales: { yAxes: [{ ticks: { suggestedMin: 0, suggestedMax: 1 } }] }, animation: { … -
How to give permission to specific users in django?
I'm creating a website in which i have to give permission to my company members to view a specific page from where they can create there profile and many things, when they apply for it by clicking on (i am company member) and submit there documents and i will verify them . And i want the normal user(customers) to view the website as it is. I thought that i will create a role for my company members and I'll assign them that role from the admin panel when the apply. Is this process of giving permission is right? Or is there any best method of giving permission to the user? Any suggestions , step by step answers and tutorial link will be very helpful. -
Is it right that django migrations are running the filter of django tables2 module before running the migrations?
I have a semi large software. At one point I included tables2 into that project and started to work with it. I the filter.py file I included some basic Model filtering. Now if I delete my database and try to run a fresh migrations I get the error, that this table is not avaible. I builded a try catch around and it's working since it does not run the code snipped before the migration. class PracticephaseProjectFilter(django_filters.FilterSet): omni = django_filters.CharFilter(method=omni_search, label="Suche") practice_phase = django_filters.ModelChoiceFilter(queryset=PracticePhase.objects.filter(pk__in=get_pp_for_specialpermit())) class Meta: model = PracticePhaseProject fields = ['practice_phase'] def __init__(self, *args, **kwargs): super(PracticephaseProjectFilter, self).__init__(*args, **kwargs) def get_pp_for_specialpermit(): pp = [] today = date.today() # check if SS or WS required if 4 <= today.month <= 9: # current SS, project will be sought for WS this year pp_str = [str(today.year)[-2:] + "s", str(today.year - 1)[-2:] + "w"] # we are in WS, check correct year for SS elif today.month > 9: pp_str = [str(today.year)[-2:] + "w", str(today.year)[-2:] + "s"] # we are allready in the year of next SS else: pp_str = [str(today.year - 1)[-2:] + "s", str(today.year - 1)[-2:] + "w"] try: for _pp in PracticePhase.objects.filter(semester__name__in=pp_str): pp.append(_pp.pk) except: pass return pp Now if I remove the … -
ModuleNotFoundError: No module named 'oscar.app' in Django Oscar
I just installed Oscar module for my website and all tables are stored in database, but now i am using this module on my urls.py file but it's giving me an error ModuleNotFoundError: No module named 'oscar.app' Please help me to solve this issue... Here is my urls.py file.... from django.conf.urls import include, url from django.urls import path, re_path from django.contrib import admin from oscar.app import application urlpatterns = [ url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^admin/', admin.site.urls), (r'', include(application.urls)), # path('', include("frobshop.urls")), ] -
Create a python file on Server
We got a wierd problem I habent found a solution for on stackoverflow. I realised that when ever i need to create a .py file the server is getting an Internal Server - Error 500. When i test everything local on my windows 10 it works fine and creates the files and is running without an error. Now on my Windows Server i get always an error 500 but the files will be created. HTTP Error 500.0 - Internal Server Error d:\django\virtualenv0\scripts\python.exe - The FastCGI process exited unexpectedly I already added permission to all the python files to be able to create a new file. I never had such an error and i dont know why. lines = f1.readlines() with open("alpha/alpha/settings_inspectdbF.py", 'w+') as f2: for line in lines: f2.write(line) Is there a way to get more information to this error or not? DEBUG = TRUE is already active but i dont get a yellow error page. Can I ignore that error or does anyone have any idea? Thanks -
How to send data from React form to Django backend server without getting the Unsupported media type error?
React newbie here, I am trying to create a simple form in React for my backend based on Django, and I keep getting the error 415 Unsupported Media Type. My backend is not getting the data sent at all. What am I doing wrong here? import React, {Component} from 'react'; import ReactDOM from "react-dom"; class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { console.log(this.state.value); fetch("http://192.168.0.133:8000/createrfq/", { method: "POST", cache: "no-cache", headers: { "content_type": "application/json" }, body: JSON.stringify(this.state.value), }) .then(response => response.json()) } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange}/> </label> <input type="submit" value="Submit"/> </form> ); } } export default NameForm -
celey: ImportError: No module named time
Trying to start celery. I get an error. Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django_celery_beat/models.py", line 19, in <module> from .clockedschedule import clocked File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django_celery_beat/clockedschedule.py", line 6, in <module> from celery.utils.time import maybe_make_aware ImportError: No module named time I'm use celery == 3.1.25 django-celery == 3.1.17 django-celery-beat == 1.5.0 Celery versions> 4.0 cannot be used. -
How can i deploy a Shiny app and django app on the same server using Apache2?
I would like to deploy both a django app and a Shiny app using apache2 on the same server. I have set up configurations for both of these applications, and on their own they work. However, these do not work when both sites are enabled. How can I get this to work? Django application config: djangoapp.conf LoadModule wsgi_module "/home/djangoapp/config/env/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" WSGIPythonHome "/home/djangoapp/config/env" <VirtualHost *:80> ServerName www.example.com ServerAlias example.com ServerAdmin webmaster@localhost DocumentRoot /usr/local/Django/DjangoApp <Directory /usr/local/Django/DjangoApp> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/djangoapp_error.log CustomLog ${APACHE_LOG_DIR}/djangoapp_access.log combined WSGIScriptAlias / /usr/local/Django/DjangoApp/myapp/wsgi.py WSGIProcessGroup hydratest WSGIDaemonProcess hydratest python-home=/home/hts_django/config/env python-path=/usr/local/Django/DjangoApp <Directory /usr/local/Django/DjangoApp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static /var/www/django/static <Directory /var/www/django/static> Require all granted </Directory> </VirtualHost> Shiny App config : shinyapp.conf <VirtualHost *:80> ProxyRequests On ProxyVia On <Proxy "*"> Allow from localhost </Proxy> RedirectMatch permanent ^/shinyapp$ /shinyapp/ RewriteEngine on RewriteCond %{HTTP:Upgrade} =websocket RewriteRule /(.*) ws://localhost:3838/shinyapp/$1 [P,L] RewriteCond %{HTTP:Upgrade} !=websocket RewriteRule /hmrpredictor/(.*) http://localhost:3838/shinyapp/$1 [P,L] ProxyPass /hmrpredictor/ http://localhost:3838/shinyapp/ ProxyPassReverse /hmrpredictor/ http://localhost:3838/shinyapp/ Header edit Location ^/ /shinyapp/ ProxyRequests Off ErrorLog ${APACHE_LOG_DIR}/shinyapp.error.log CustomLog ${APACHE_LOG_DIR}/shinyapp.access.log combined </VirtualHost> When both sites are enabled, the ShinyApp -
Django asking for instance instead of value
I have a django app with these models (only relevant fields): class Device(models.Model): serial = models.PositivewSmallIntegerField(unique=True, defeult=0000) …. class Conexion(models.Model): serial = models.ForeignKey(Device, to_field='serial', null=True, blank=True, on_delete=models.DO_NOTHING) …. When I try to assign a integer value to serial in Conexión, django asks for a Device instance. But this is wrong, because I have set to_field='serial'. I have exactly the same Foreign key in another model and it works ok. This is the exception: ValueError: Cannot assign "11": "Conexión.serial" must be a "Device" instance -
Is there any way to use the return value of custom python script to django template?
I'm trying to run a custom python script and return its value to template. The return function from custom script is returning value in the script but i can't use it in template. This is my custom script which returns the label value: def genre(f): K.clear_session() model = joblib.load('music/finalized_CNNmodel.sav') print(model.layers[0].input_shape) mel_spec(f) test_image=image.load_img(f'media/{f.file.name}.png', target_size=(256,256), color_mode='rgb') test_image=image.img_to_array(test_image) test_image=np.expand_dims(test_image,axis=0) result=model.predict(test_image) label = np.argmax(result) return label I'm calling this function through views as: def model_form_upload(request): documents = Document.objects.all() if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): print(request.FILES) newdoc = Document(file=request.FILES['file']) newdoc.save() print(newdoc.file.name) genre(newdoc) return render(request,'music/result.html', {'documents':documents,'form':form}) else: form = DocumentForm() return render(request,'music/result.html', {'documents':documents,'form':form}) This is my template: {% if genre.label == 0 %} CLASSICAL {% elif genre.label == 1 %} DOHORI {% else %} POP {% endif %} I expected to show the result in the template but the return value is not passing to the template. -
Path to image in Django Template for emails not work
I want to add the images to my html template for the emails. In my project settings i have MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.media', ], }, }, ] in my url i have urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my project structure my email method message = render_to_string('recovery_password.html', { "code": code, "MEDIA_URL": settings.MEDIA_URL }) mail_subject = 'Recovery password' email = EmailMessage(mail_subject, message, to=[to_email], ) email.content_subtype = "html" email.send() and in the recovery_password.html i have link on the image <a><img src="{{MEDIA_URL}}image1.png/></a> But my image in the email not work. It doesnt display in the temlate -
How to Solve Name Error Global Name Not Defined
I am getting a Name Error when trying to render my view. It says the global name 'form' is not defined. But when I look at my code, I feel like I am defining the name form. I am getting the error for the code below : if form.is_valid() def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() return redirect('edit_manifest_frombrowse') else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference=reference_id) form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) context = { 'reference_id': reference_id, 'form': form, 'data': data, } return render(request, 'edit_manifest_frombrowse.html', context) TRACEBACK Environment: Request Method: POST Request URL: http://127.0.0.1:8000/manifest_reference_view Django Version: 1.10 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'unit'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/andrews/Desktop/WBU/web_unit/unit/views.py" in manifest_reference_view 236. if form.is_valid(): Exception Type: NameError at /manifest_reference_view Exception Value: global name 'form' is not defined -
Nginx server error 500?The detail view works on development system but on the server gives server error (500)?
I have a Django app configured with Nginx and gunicorn on ubuntu machine. The detail view works fine on my machine but when deployed it gives Server Error (500) I checked the python versions on the virtual env of the server and my machine and both are Python 3.6.5 I checked the logs of Gunicorn and Nginx and nothing suspicious, I enabled the debugging and still, nothing was found. I checked if the template file reference matched in the views.py what should I do next? -
How to Fix the Code In Order to lets the Function Working
I'm getting a django project to fix the error inside the code, may i know what is the problem of this few line of code which cause the add and delete button on the webpage does not function well? I've try fix some typo error in the code, but it's still not working so i changing bck the code to its original way. {% extends "app/layout.html" %} {% block content %} <script> $(document).ready(function () { var i=1; $("#add_row").click(function(){ $('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='item_id' type='item_id' placeholder='Item ID' class='form-control input-md' /> </td><td><input name='item_name' type='text' placeholder='Item Name' class='form-control input-md'></td><td><input name='description' type='text' placeholder='Description' class='form-control input-md' ></td><td><input name='quantity' type='text' placeholder='Quantity' class='form-control input- md' /> </td><td><input name='unit_price' type='text' placeholder='Price Per Unit' class='form-control input-md' /> </td>"); $('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>'); i++; }); $("#delete_row").click(function(){ if(i>1){ $('#addr'+(i-1)).html(''); i--; } }); }); </script> <div class="formpurchaseorder margintop" > <form class="purchaseordersubmission" action="purchaserequisitionconfirmation" method="POST"> {% csrf_token %} <div class="row margintop"> <div class="col"> <input type="text" class="form-control" name="purchase_requisition_id" value="{{purchase_requisition_id}}" placeholder="Purchase Requisition ID" readonly> </div> <div class="col"> <input type="text" class="form-control" name="person_id" id="person_id" value="{{person_id}}"placeholder="Person ID" readonly> </div> </div> <br/> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-bordered table-hover" id="tab_logic"> <thead> <tr > <th class="text-center">#</th> <th class="text-center">Item ID</th> <th class="text-center">Item Name</th> <th class="text-center">Description</th> <th class="text-center">Quantity</th> <th class="text-center">Price Per Unit</th> </tr> … -
Wagtail modeladmin: Pass data to create_view_class
Im creating a modeladmin with special viewmodels for create/edit/delete. I need to pass data to the create view (a pk for a foreign key that is not part of the form). What is the best way to go about this?