Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sitemaps, two pages using he same object
I am trying to add a sitemap to a jobsite I have built (first time using the sitemaps framework in Djnago, so not 100% sure what I should be doing). Anyway, I have two pages, a "job detail" page, and a "job apply" page. These are both based on the Job model, and have urls referencing the job id. urls.py url(r'^job-details/(?P<pk>\d+)/$', views.JobDetailView.as_view(), name='job_detail' ) , url(r'apply/(?P<pk>\d+)/$', views.JobApplyView.as_view(), name='job_apply' ), sitemap.py class JobsSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Job.objects.filter( active=True, venue__contacts__account_verified=True, date_expires__gte=date.today()) def lastmod(self, obj): return obj.date_posted models.py class Job(models.Model): ... field definitions here .... def get_absolute_url(self): return reverse('job_detail', kwargs={'pk': self.id}) Now the problem is that I have already specified get_absolute_url() on the Job model to point to the job detail page. So I can't point it to the job_apply page as well. I tried configuring it according to the "Sitemap for static views" section in the docs, but that complains that there is no reverse match for that URL (as it is expecting the kwargs argument). What is the correct way to deal with pages based on the same object? -
'env' is not recognized as an internal or external command, operable program or batch file?
Currently i am working on django with postgresql (locally and on heroku). I many data in my locally installed postgresql almost (5000 rows). i am trying to push my local db to heroku. What i have done so far is. 1) heroku pg:push postgres://postgres:postgres@localhost:8000/ DATABASE --app djangoshopnroar after this command, it give me error to run command heroku pg:reset after this command. data from heroku get deleted. again i run the first command e.g heroku pg:push postgres://postgres:postgres@localhost:8000/ DATABASE --app djangoshopnroar where as, djangoshopnroar is my app on heroku where postgresql is placed. but when i run this command again, i initially received this message "'env' is not recognized as an internal or external command, operable program or batch file?" can anybody tell me where i am wrong? how can i push my local data from postgree to postgree on heroku? i will be very thankful for any help or suggestions. -
NameError: name 'urlpatterns' is not defined
I'm trying to show an image using "ImageField" from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = '' MEDIA_URL = "/media/" -
Exception Value: column home_profile.goal does not exist
I'm really stuck here and i'm a little confused as to why this error is being thrown. I'm running Django 1.10 and the live database is a postgresql DB. I'm not that familiar with postgres. I've been doing all of my development work with sqlite for flexibility. I've recently added two new fields to my model. They are both IntegerFields I've not had any issues with them locally. I've not deployed my changes to my live environment and i'm getting the above error. goal = models.IntegerField(default=1, choices=weight_goal, null=True, blank=True) I have tried removing the fields, deleting all the migration files and even removing the model itself. However, when i add the field back in it throws the same error. I've done some research and all i can see is 'Drop the DB and create it again". Well this isn't possible as i'll lose all of the data inside the live DB. I don't really feel comfortable diving into a live database and trying to add the column manually. I mean, this seems a little OTT anyway? Any help would be much apprecited. Full traceback below: Environment: Request Method: GET Request URL: / Django Version: 1.10 Python Version: 2.7.13 Installed Applications: … -
How to POST data in Django - urls.py
I am using djoser for authorization. i want to logout using djoser - /auth/logout/ but it require token data using POST method. my URL is, url(r'^logout/$', "{}/auth/logout/".format(API_URL), {'token':token}), how do i bind post data into it? and how to call external API from urls.py along with POST data Note : My djoser was in another django app. i need to do external API call for logout. -
Django Apply Model Foreign Key Default Value to Existing Record and Updates with New User
thank you very much for taking your time. Previously, I posted this question, How to Get Unread Posts for Users. The problem was: I cannot filter out which article one user has not read while this article has already been read by another user. I figured out why I cannot do that---- because I have data that I wrote into the database without using Django although I set the reading default for each post to False---- there is simply no record. Then, I manually set one article to unread to a user in the Admin, everything works, because now in the database there is one record stating that this certain article has not been read by this user. The problem now is: How do I set "unread" for every existing article that I have in the database for all existing users? And how can articles stay unread for every new user unless the new user actually read it? For your convenience, I copied the codes to here. My model: class Posts(models.Model): title = models.CharField(max_length=255) content_url = models.URLField(unique=True) content = models.CharField(max_length=255) post_date = models.DateField(default="2999-12-12") Another class readstatus(models.Model): reading_status = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article = models.ForeignKey(Posts, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) … -
How does django migrate it's test models?
I am reading django's unit tests, and I stumbled on the test models which seems to have no migrations. How does django migrate it's test models? I want to use this on my project's unit tests, because each time i want to use test models I use schema_editor.create_model() on my setUp() for individual test case. -
Add data to custom django user model
I am new to web devolopment and django. Currently I am developing a simple dashboard web application for our computational cluster and have configured a custom user model, which looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) processor_hours = models.FloatField(null=True, blank=True) All of the default user fields are taken from our ldap server, and authentication works. However, I want to add data to the custom field for each user. I have a text file with the information in columns, username1 hours username2 hours I tried using the manage.py shell to run a python script and add the data to the corresponding fields but it doesn't seem to be saving it to the database. What am I missing? -
Django does not migrate app
I'm working on a django project for learning purpose. I created app organization and installed it. When I run python manage.py makemigrations organization it works fine shows the changes. Migrations for 'organization': organization/migrations/0001_initial.py: - Create model Organization - Create model Principle But when I run python manage.py migrate organization it doesn't migrate and shows no changes to apply. Operations to perform: Apply all migrations: organization Running migrations: No migrations to apply. I'm using postgresql and tried drop owned by user_name; after deleting all migrations folders. But still doesn't work. It shows every time the same thing. How to resolve this ? Environment: OS version Ubuntu 16.04 Django version 1.10.3 PostgreSQL version 9.5.7 organization/models.py from django.db import models from django.contrib.postgres.fields import JSONField class Principle(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=256) contact_no = models.CharField(max_length=256) status = models.BooleanField() class Organization(models.Model): name = models.CharField(max_length=256) liceneses = [ ('pvt','Private Limited',), ('pub','Public Limited',), ('part','Partnership',), ('prop','proprietary',) ] licenese_type = models.CharField(max_length=10, choices=liceneses) key_person_name = models.CharField(max_length=256) key_person_position = models.CharField(max_length=256) key_person_contact_no = models.CharField(max_length=45) primary_organization_contact = models.CharField(max_length=45) organization_address = models.TextField() additional_info = JSONField() date_of_registration = models.CharField(max_length=45) status = models.BooleanField() -
React router chunk bundle not fetched when visited that route
I want to load the bundle when that route url is visited. My server is django localhost:8000. My webpack splits up the bundle.enter image description here my router component import React from 'react'; import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom'; import App from '../app'; //import CollegeList from '../apps/college/CollegeList'; import CollegeDetail from '../apps/college/CollegeDetail'; import CourseList from '../apps/course/CourseList'; import CourseDetail from '../apps/course/CourseDetail'; import UniversityList from '../apps/university/UniversityList'; import UniversityDetail from '../apps/university/UniversityDetail'; import AdmissionList from '../apps/admission/AdmissionList'; import AdmissionDetail from '../apps/admission/AdmissionDetail'; import CareerList from '../apps/career/CareerList'; import CareerDetail from '../apps/career/CareerDetail'; import EventList from '../apps/event/EventList'; import EventDetail from '../apps/event/EventDetail'; import NewsList from '../apps/news/NewsList'; import NewsDetail from '../apps/news/NewsDetail'; import ScholarshipList from '../apps/scholarship/ScholarshipList'; import ScholarshipDetail from '../apps/scholarship/ScholarshipDetail'; import VacancyList from '../apps/vacancy/VacancyList'; import VacancyDetail from '../apps/vacancy/VacancyDetail'; import RankList from '../apps/rank/RankList'; import RankDetail from '../apps/rank/RankDetail'; import FacultyCourseList from '../apps/faculty/FacultyCourseList'; import LoginForm from '../apps/users/components/LoginForm'; import SignUpForm from '../apps/users/components/SignUpForm'; import Header from '../components/Header'; import Footer from '../components/Footer'; import LoadingComponent from '../components/LoadingComponent.js'; function loadRoute(cb) { return module => {console.log(module);cb(null, module.default)}; } class AppRoute extends React.Component { render() { return ( <Router> <div> <LoadingComponent/> <Header /> <Route exact path='/' component={App}/> <Route exact path='/colleges' getComponent={(location, cb) => { System.import('../apps/college/CollegeList') .then(loadRoute(cb)) .catch((error) => {console.log('error')}); }}/> <Route path='/colleges/:slug' component={CollegeDetail}/> <Route exact path='/courses' component={CourseList}/> <Route path='/courses/:slug' component={CourseDetail}/> … -
Django settings - customize attributes per Site from admin
I'm using django sites framework. I've a model with a OneToOneField to Site model. This way the admin users can customize each site attributes from the admin panel. class CustomSite(models.Model): site = models.OneToOneField(Site) email_host_user = models.EmailField() ... Some of these fields are actually values that should be used in the settings file, like EMAIL_HOST_USER. How can I use these values in the settings file of the custom sites? is this the correct approach? -
Image not showing in Django [duplicate]
This question already has an answer here: How to display images from model in Django? 1 answer I don't know why the images aren't showing in Django. Something to do with the media root? settings code STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')' models code image = models.ImageField(upload_to='img',default='media/placeholder.png') I didn't add a url for the picture, could that be a problem? urls urlpatterns = [ url(r'^post/(.*)', blogViews.post), url(r'^about/$', blogViews.about), url(r'^$', blogViews.index), url(r'^admin/', admin.site.urls), index.html code <img src="{{post.image}}"> <p> {{post.image}} </p> In the website all that shows is a blank picture as well as the file name (either placeholder.png which is the default or img/... which I uploaded through admin) Thanks in advance, first question on this site! -
Server error(500) in django==1.5.4 I already set Allowed Host=['*'] in settings.py file
DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-host ALLOWED_HOSTS = ['*'] -
Django,HTML:Display the loader after submitting the post request
In my application after pressing the submit button the POST request will be sent to server.I want to display the loader until the server responds. Here is my HTML template: {%load static %} {% load staticfiles %} <html> <style> form { } input[type=text], input[type=password] { width: 30%; padding: 12px 20px; margin: 12px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } button { background-color: #35a5f0; color: white; padding: 14px 20px; margin: 6px 0; border: none; cursor: pointer; width: 30%; } button:hover { opacity: 0.8; } .cancelbtn { width: auto; padding: 10px 18px; background-color: #f44336; } .container { padding: 16px; } span.psw { float: right; padding-top: 16px; } /* Change styles for span and cancel button on extra small screens */ @media screen and (max-width: 300px) { span.psw { display: block; float: none; } .cancelbtn { width: 100%; } } </style> <body> <div style="display: flex; justify-content:center;"> <img src = "{% static 'logo.png' %}" width="150" height="100"> <img src = "{% static 'Timesheets.png' %}" width="150" height="100"> </div> <form action="/new_user/" method="post"> <div class="container"> <div style="display: flex; justify-content:center;"> <input type="text" placeholder="Enter valid Email ID" name="email_id" required> </div> <div style="display: flex; justify-content:center;"> <button type="submit">Submit</button> </div> </div> <div style="display: flex; justify-content:center;"> <p> {{status}}</p> </div> <div style="display: … -
How to extract metadata from File object in Python Django
How to extract metadata from File(image) received from form to Django 1.10(python3.5) backend. I am currently using exifread tool. I am successfully able to do read metadata from file saved in the file system. I am looking for some code like this : imagefile = request.FILES['image'] imagetype = imagefile.content_type.split('/')[1] metadata = exifread.process_file(imagefile, strict=True) -
Trying to build a website with a change language button in django
I'm trying to build a simple website using Django which would have a "change language" button and display the page in the respective language chosen by the user. I have only done the following so far in the command line: django-admin startproject mysite python manage.py startapp main I had previously tried modifying settings.py by adding from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('ru', _('Russian')), ) and to MIDDLEWARE django.middleware.locale.LocaleMiddleware I know what I've done isn't much. What else do I have to do? Please help. Thanks in advance. -
How to call url from a java script file in django?
I am new to django and Developing a dashboard webapp. i have a javascript file which renders table. i want to render new tables according to user's click on a cell. So i am passing the cell value to urls.py. Below is the code, which i wrote to pass cell value from JS file to urls.py but not successful. var product_table = document.getElementById("cbugs"); if (product_table != null) { for (var i = 1; i < product_table.rows.length; i++) { for (var j = 0; j < product_table.rows[i].cells.length; j++) product_table.rows[i].cells[1].onclick = function () { tableText(this); }; } } function tableText(tableCell) { alert(tableCell.innerHTML); var product=tableCell.innerHTML; //console.log(tableCell.innerHTML); location.href="{% url 'visual:bugsc' product %}".replace(/product/, product.toString()); } And my urls.py from django.conf.urls import include, url from . import views app_name='visual' urlpatterns = [ url(r'^$', views.project_tracking, name='project_tracking'), url(r'^project_tracking/$', views.project_tracking, name='project_tracking'), url(r'^bugs/$', views.bugs, name='bugs'), url(r'^mttw/$', views.mttw, name='mttw'), url(r'^customerbugs/$', views.cbugs, name='cbugs'), url(r'^(?P<product>.+)/$',views.bugsc,name="bugsc"), ] -
VAPT Issue Data Validation - HTML Injection Django
How to solve this issue can anyone have Idea OBSERVATION : It was observed that application vulnerable to html injection IMPACT : Disclosure of a user's session cookies that could be used to impersonate the victim, or, more generally, it can allow the attacker to modify the page content seen by the victims. RECOMMENDATION : It is recommended that application escapes all un-trusted data in headers, cookies, query strings, form fields, and hidden fields. Escaping ensures that un-trusted data can't be used to convey an injection attack. The web server should also verify the client side data prior to accepting and acting on it to ensure it is expected and not malicious. -
Django import-export: new without update
I'm using 'django import export' (DIE) for importing some data. I have a problem with import data. my admin.py: class TestResource(resources.ModelResource): class Meta: model = Test exclude = ('id',) import_id_fields = ['VS',] skip_unchanged = True class TestAdmin(ImportExportMixin,admin.ModelAdmin): fieldsets = [ ('VS', {'fields':['VS']}), ('pool', {'fields':['pool']}), ('pool_port', {'fields':['pool_port']}), ('idc', {'fields':['idc']}) ] list_display = ('VS','pool','pool_port','idc') list_filter = ['pool_port'] search_fields = ['VS','pool','pool_port','idc'] resource_class = TestResource admin.site.register(F5,F5Admin) I want to import excel file like: enter image description here BUT: enter image description here I want all row had import . Please tell me how to ignore dereplication.Thanks ! -
how to use onelogin saml with curl or python shell
I want to use the OneLogin SAML Python toolkit for my Django application but I do not have any GUI yet. I have registered and setup the idp connector at OneLogin and want to test it with linux curl or python shell. Is it possible and what is the format of the requests I need to make? -
Django not inserting data into database when I execute subprocess.Popen
I am using django and inserting data into database and downloading images. When I call the function it works fine but it blocks the main thread. To execute the process in the background I'm using : subprocess.Popen( ['python get_images.py --data=data'], close_fds=True, shell = True ) But when I call: python get_images.py(data="data") it works fine but it runs on the main thread. How can I fix it ? BTW I'm using python 2.7. Note: Please don't suggest Celery . I'm looking for something which runs the task async or any other alternative. -
Python Import Error when pyqtgraph,pyside, pyqt5 already installed
>>> import pyqtgraph Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\sudha\Anaconda3\mysite_project\env_mysite\lib\site-packages\pyqtgraph\__init__.py", line 13, in <module> from .Qt import QtGui File "C:\Users\sudha\Anaconda3\mysite_project\env_mysite\lib\site-packages\pyqtgraph\Qt.py", line 153, in <module> from PyQt5 import QtGui, QtCore, QtWidgets, uic ImportError: DLL load failed: The specified module could not be found. -
Correctly defining this data relation in Django models
I'm working on a Django project, where I have amongst others, two models that have a relationship. The first model describes a dish in general. It has a name and some other basic information, for instance: dish(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_lenght=255) vegetarian = models.BooleanField(default=False) vegan = models.BooleanField(default=False) The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So the dish gets a new field, which points to the current preparation text. preparation = models.???(???) So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated. The preparation itself looks like this: preparation(models.Model): prep_test = models.TextField() ingredients = models.TextField() last_update = models.DateTimeField() As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation. Is my assumption with the one-to-one relation correct and if so, how do I correctly define it? -
Django - joining multiple tables (models) and filtering out based on their attribute
I'm new to django and ORM in general, and so have trouble coming up with query which would join multiple tables. I have 4 Models that need joining - Category, SubCategory, Product and Packaging, example values would be: Category: 'male' SubCategory: 'shoes' Product: 'nikeXYZ' Packaging: 'size_36: 1' Each of the Model have FK to the model above (ie. SubCategory has field category etc). My question is - how can I filter Product given a Category (e.g. male) and only show products which have Packaging attribute available set to True? Obviously I want to minimise the hits on my database (ideally do it with 1 SQL query). I could do something along these lines: available = Product.objects.filter(packaging__available=True) subcategories = SubCategory.objects.filter(category_id=<id_of_male>) products = available.filter(subcategory_id__in=subcategories) but then that requires 2 hits on database at least (available, subcategories) I think. Is there a way to do it in one go? -
Django:Import data from External database and storing in mongo db
I have a project in which i need to import the data from external database like SQL and convert that data into my local django database(mongodb). Is there any libraries or any project available which does the same?