Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I enable the users delete and edit post they create in Django?
I am trying to have users delete and edit post they create. I was told "Post.user needs to be an object instance what you wrote is incorrect." but I am still newer to django and would like to know the steps to do this as I created this project with some help. here is my models from django.db import models from django.db.models import Count, QuerySet, F from django.utils import timezone from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils.text import slugify from markdown_deux import markdown from django.utils.safestring import mark_safe from taggit.managers import TaggableManager from comments.models import Comment def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1 ) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) image = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) description = models.TextField() tags = TaggableManager() public = models.BooleanField(default=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-created", "-updated" ] def get_markdown(self): description = self.description markdown_text = markdown(description) return mark_safe(markdown_text) @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = … -
Python dependencies resolving with authomatic
My first attempt to use authomatic with Django was ok, but not clean: I have a huge "CONFIG" dictionary which makes reference to openid, and gaeopenid (and a bit more actually) in my view file, which is not clean. So I wanted to move all that stuff to my settings.py. The problem is that I can't do this: from third_party.authomatic_0_1_0.authomatic.providers import oauth1, oauth2, \ openid, gaeopenid as long as I haven't modified the search path like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR+'/third_party/defusedxml-0.4.1') sys.path.append(BASE_DIR+'/third_party/python-openid_2_2_5') sys.path.append(BASE_DIR+'/third_party/google_appengine_1_9_25') sys.path.append(BASE_DIR+'/third_party/authomatic_0_1_0') So I need to move the import after I have modified the search path. So I'm breaking PEP8: module level import not at top of file. Is there a clean way to go 'round this? -
Testing abstract models in Django
I am trying to test some functionality of abstract base models in my Django app. I have been reading on how to do these tests and everyone seems to say that I need to create a test model. So I have done so, I have crated a directory called my_app/tests and created a models.py in there. Where I have my test model UniqueSlugTestModel. Now I guess I need to call makemigrations and migrate on the test app. So I add my new test app to the settings in the test and call migrate. But for some reason the makemigrations and migrate are not seeing that the my_app.tests app is not in settings. Why are they looking at different settings than the live settings that I am overriding in my tests? Is this the best way to test abstract models in Django? How can I make the management commands look at the overridden settings? from django.conf import settings from django.core.management import call_command from django.test import TestCase from django.test import override_settings from my_app.tests.models import UniqueSlugTestModel class UniqueSlugModelTestCase(TestCase): @override_settings(INSTALLED_APPS=settings.INSTALLED_APPS + ['my_app.tests']) def setUp(self): print(settings.INSTALLED_APPS) call_command('makemigrations', 'my_app.tests', interactive=False) call_command('migrate', 'my_app.tests', interactive=False) @override_settings(INSTALLED_APPS=settings.INSTALLED_APPS + ['my_app.tests', ]) def tearDown(self): call_command('migrate', 'my_app.tests', 'zero', interactive=False) @override_settings(INSTALLED_APPS=settings.INSTALLED_APPS + ['my_app.tests', … -
Django 1.9 - makemigrations/migrate on Heroku does not create relation
I am trying to deploy my 1.9 Django project to Heroku, but have problems with applying my migrations. After running 'python manage.py migrate', all tables are created expect for one relation that is used for a many-to-many relationship. It is defined as follows: class CardInJar(models.Model): card = models.ForeignKey(ContentCard) jar = models.ForeignKey(MessageJar) seen = models.BooleanField(default=False) class Meta: auto_created = True I've already tried making the migrations locally and commiting them, and making them on the server, resetting the database in between. After migrating, all other tables are created and are working correctly. When I try to use the CardInJar relation however, I get a relation "YourShoeBox_cardinjar" does not exist error. The local app works perfectly. -
Display Pandas output in html page
i am using Django as a web-framework, i have been trying to display data from csv file onto HTML page with pandas, i tried to find any available project online but i couldn't, I have an index.html file /appl/templates/appl/index.html i don't have exact idea of how exactly i should display the data from python code, i tried to put all python code inside {{...}} in html but it gave me errors, inside /appl/data.py file i am trying to read data with pandas code .... file_data=pd.read_csv('F:\lending-club-data.csv') .... i want to somehow put the output of 'file_data' inside html file and display but i am unable to do it. a basic small snippet of work_around code for the above problem is needed. -
Create a queryset to compare two models
I'm just new using Django. I just created my models and migrate information to my sqlite3 database using the .cvs import module. This are my modules: class Backlog(models.Model): sales_order = models.CharField(max_length=30) po_number = models.CharField(max_length=30) order_number = models.IntegerField(blank=True) line_number = models.IntegerField(blank=True) ship_Set = models.IntegerField(blank=True) product_id = models.CharField(max_length=30) ordered_quantity = models.IntegerField(blank=True) class Material(models.Model): product_id = models.CharField(max_length=50) tan_id = models.CharField(max_length=50) Now that I have the information inside my tables I want to do the following: Find if product_id from Backlog is in Materials model, once it finds it verify the first two digits from the tan ID. If is 74 clasify as '1', if is 800 clasify as '3' else set as '2'. (TAN ID format commonly are 74-102345-03, 800-120394-03) My two questions are: How to do that and if I have to create a new column to add the information from every product id. -
'HttpResponseNotFound' object has no attribute 'render'
I'm developing a django application using django rest framework. I have the following code: #For get request client = APIClient() client.login(username='username', password='password') response = client.get('http://103.x.x.x/api/get_last_thread/?format=json') response.render().content client.logout() and I have the error of response variable as an empty value (None), I don't know why, if I copy the url to any browser i will have the results. I have changed the url for a random url and I received the same error, it seems like client.get is not executing the request. Thank you -
I redefined AUTHENTICATION_BACKENDS in Django settings.py, but it still equals to the default ['django.contrib.auth.backends.ModelBackend']
I am playing with Django-REST-JWT and trying to implement JWT authentication. For that end, in my settings.py I defined: AUTHENTICATION_BACKENDS = ['authentication.backends.AuthBackend'] where authentication is the name of my app with User model and custom authentication backend, based on Django-REST-JWT. Now, when I'm trying to generate a token, given username and password, my implementation fails, but Django debug page reports that AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] Seems, like Django ignored my AUTHENTICATION_BACKENDS settings. This is NOT a typo error, I double-checked. Why would that happen? Code: authentication/backends.py class AuthBackend(ModelBackend): def authenticate(self, username=None, password=None): try: user = User.objects.get(pk=username) except Exception as e: user = None return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None -
converting simple SOAP client code from php to python
so here is my php code $client = new SoapClient('https://someservice.com/Tokens.xml', array('soap_version' => SOAP_1_1)); $params['merchantId'] = 'ABC'; $params['invoiceNo'] = 1; $result = $client->__soapCall("MakeToken", array($params)); $token = $result->MakeTokenResult->token; so i've installed suds and i've came this far from suds.client import Client def test(request): client = Client(location="https://someservice.com/Tokens.xml" ) return(HttpResponse('something !! ')) im not sure what the next step is in this line $result = $client->__soapCall("MakeToken", array($params)); this is what i came up with which is obviusly wrong ! client.service.__soapCall('MakeToken' , 'merchantId:ABC' , 'invoiceNo:1' ) -
Prevent delete object if has related objects
Using Django's Admin I'd like to prevent deletion for objects with related objects: class User(models.Model): ... contract = models.ForeignKey(Contract, null=True, on_delete=models.SET_NULL) class Contract(models.Model): ... The schema above is what I have now, but I'd like to prevent deletion for a Contract object if some User object is related to it, this should show a message in Contract list Admin page with the reason. If a Contract object does not has any associated User it could be deleted. I've tried with the has_delete_permission method from admin.ModelAdmin: @admin.register(Contract) class ContractAdmin(admin.ModelAdmin): ... def has_delete_permission(self, request, obj=None): ... But when I run in debug mode, obj is always None, I can not identify the object and check is it has or not related Users. Thanks. -
ELFCLASS32 with psycopg2 on Django Mezzanine
im trying to deploy a Django Mezzanine app to my brand new VPS server and im getting some trouble. When running fab deploy command to deploy the app, i got the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: ./env/lib/python2.7/site-packages/psycopg2/_psycopg.so: wrong ELF class: ELFCLASS32 The server is runing ubuntu 14.04 LTS. I tried to install de psycopg2 package directly on the VPN via SSH but still the same. -
Django - Is_authenticated method works only on one view
I have a following problem. In login.html I added {% If user.is_authenticated %} and there everything work. I also added this in navbar.html and home.html, but there it doesn't work, and I don't know why. This is my views.py def index(request): return render(request, 'website/home.html', {'user': user_panel}) def register(request): registered = False if request.method =='POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print (user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() return render(request, 'website/register.html', { 'user_form': user_form, 'profile_form': profile_form, 'registered': registered}) def auth_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Konto jest nieaktywne") else: print ("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return render(request, 'website/login.html', {}) basic.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Bootstrap 101 Template</title> <link rel="stylesheet" … -
How do i use a part of HTML template in my various other templates using django templates language?
I have a template named 'popup.html' and I have to use this part of code (ie) the html in to my other templates whenever needed. I tried using {% extends 'popup.html' %} whenever needed but it throws me error PS. I already use {% extends 'layout.html' %} for my navbar inheritance in all pages. -
Python 3.5.2/Django 1.9.8 deprecation warning. What should I replace with?
My line: urlpatterns = [ url(r'^signout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), ... ... The warning: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got django.contrib.auth.views.logout). Pass the callable instead. 2016-08-23T14:56:28.580019+00:00 app[jobQueue.1]: url(r'^signout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}), What should I be replacing this line with? -
Django Rest Framework Recursive Nested Parent Serialization
I have a model with a self referential field called parent. Model: class Zone(BaseModel): name = models.CharField(max_length=200) parent = models.ForeignKey('self', models.CASCADE, blank=True, null=True, related_name='children') def __unicode__(self): return self.name Serializer: class ZoneSerializer(ModelSerializer): parent = PrimaryKeyRelatedField(many=False, queryset=Zone.objects.all()) parent_disp = StringRelatedField(many=False, source="parent") class Meta: model = Zone fields = ('id', 'name', 'parent', 'parent_disp') Now I want to serialize the parent of the zone and its parent and its parent till parent is none. I found recursive serialization methods for children but not for parent. How can I do this? -
How to differ formsets in django when using modelformset_factory?
Let's say I have an Contact object and I want to have two groups of contact Formsets in django(1.8) divided by fieldset tag in html template. I use modelformset_factory. Regardless I use one or two different factory functions, fields in these two formsets have same id in html. Since http.Request.body is dictionary, I lose information about one of the two formsets. contacts_formset = modelformset_factory( models.Contact, form=forms.ContactDetailForm, extra=2) contacts_escalation_formset_new = contacts_formset( queryset=models.Contact.objects.none()) contacts_other_formset_new = contacts_formset( queryset=models.Contact.objects.none()) in HTML: input id="id_form-0-name" maxlength="155" name="form-0-name" type="text" input id="id_form-0-name" maxlength="155" name="form-0-name" type="text" For simple django form, there is keyword "prefix=..." . But this factory function does not have this argument. How can I solve it? -
Django collectstatic command not finding and copying static files
I'm setting up my static files for Django to collect with this setup, STATIC_URL = '/static/' STATIC_ROOT = "127.0.0.1:8000/static/" I made a static folder inside my app my_app/static/my_app/my_css_framework_directory My my_css_framework_directory contains the following directories, css, img, and js. But when I ran python manage.py collectstatic, 0 files are copied? -
Dreamhost PyCharm Django Python 3 Launching a Site
I'm new to python/django and created a simple django website using PyCharm. The site works fine running on my computer, but I'm really lost when it comes to taking the site onto my host (Dreamhost). I'm able to upload the files to the correct directories fine, and I believe I made the correct changes for the database to be on mysql. I'm not sure where to go from there though. Right now, the page just shows the files rather than the site. Any direction would be greatly appreciated. Thanks so much! -
Signals working only in shell,not working in admin and frontend
I am trying to assign some values to a model field after post-save.The model is class Authority(models.Model): no_of_feeds=models.PositiveIntegerField() no_of_rf=models.PositiveIntegerField() no_of_urf=models.PositiveIntegerField() class Feed(models.Model): auth=models.ForeignKey(Authority,blank=False) @receiver(post_save, sender = Feed) def update_model_feed(sender, **kwargs): if kwargs['created']: #only fire when creating new objects kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count() kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count() kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count() print '******************************' elif not kwargs['created']: kwargs['instance'].auth.no_of_feeds=kwargs['instance'].auth.feed_set.all().count() kwargs['instance'].auth.no_of_rf=kwargs['instance'].auth.feed_set.filter(resolved=True).count() print '-------------------------------' kwargs['instance'].auth.no_of_urf=kwargs['instance'].auth.feed_set.filter(resolved=False).count() As you can see,The signal is used to assign values to Authority fields after saving Feed model.This works in shell,as the fields are automatically updated but it doesnt work on creating or editing a feed instance in admin or front-end website.Though its print out the '-------' and '****' on execution in the console.Pls kindly help -
AttributeError: 'module' object has no attribute 'get_version'. Django
I'm following rosetta initial steps and getting an error in step 3: AttributeError at /rosetta/pick/ 'module' object has no attribute 'get_version' Request Method: GET Request URL: http://localhost:8000/rosetta/pick/?rosetta Django Version: 1.9.7 Exception Type: AttributeError Exception Value: 'module' object has no attribute 'get_version' Python Executable: /path/to/my/project/venv/bin/python Python Version: 2.7.6 Python Path: ['/path/to/my/project/app', '/path/to/my/project/app', '/path/to/my/project/venv/lib/python2.7', '/path/to/my/project/venv/lib/python2.7/plat-x86_64-linux-gnu', '/path/to/my/project/venv/lib/python2.7/lib-tk', '/path/to/my/project/venv/lib/python2.7/lib-old', '/path/to/my/project/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/path/to/my/project/venv/local/lib/python2.7/site-packages'] I'm pulling my hair off for not finding answers for this error. -
Pass URL arguments to Django via Java HttpUrlConnection
I started coding in Python and the Django framework recently because I heard it was great for web-based scripting and very easy to use and succinct compared to other languages such as PHP. I've run into a problem here however in trying to pass arguments to a view from a Java class. It's something I found very easy to do in PHP/Laravel but I just can't seem to get it working in with Python/Django. Basically what I'm trying to do is get the user to enter and name and surname and send them off using the Java HttpUrlConnection. I'll leave the working version in Java/PHP below and also what I have in Python. I'm sure it's something that is quite straightforward to do but I'm just starting out with this framework and I've looked all over but still can't seem to figure it out! Any help is appreciated, cheers! Java class using HttpUrlConnection: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class Networking { private static Scanner in; public static void main(String[] args) throws IOException { in = new Scanner(System.in); String name; String surname; System.out.println("Enter your name: "); name = in.next(); System.out.println("Enter your surname: "); … -
django - form fields for individual entries of model field
I have a model Analysis that has a json field description. description = JSONField(default=list) The field is suppose to hold a list json objects each having desc and extra_desc fields. I have a view that allows updating this Model. class AnalysisForm(forms.ModelForm): desc = forms.CharField(max_length=1000, widget=forms.Textarea) extra_desc = forms.CharField(max_length=1000, widget=forms.Textarea) class Meta: model = Analysis fields = ('risk', 'status', ) When this form renders, I get only a single textarea for desc and one for extra_desc. How can I display seperate seperate textareas for each json entry in the list -
Connect to AS400 database with Django (ibm_db_django)
I have created a new project in Django and am following this tutorial to help me pull data from my remote database. Whenever I try to run migrate in manage.py I get the following error: "C:\Program Files (x86)\JetBrains\PyCharm 2016.2.1\bin\runnerw.exe" C:\Users\ecjohnson\AppData\Local\Programs\Python\Python35-32\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 2016.2.1\helpers\pycharm\django_manage.py" migrate U:/incoming_parts_monitor Traceback (most recent call last): File "C:\Users\ecjohnson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\ibm_db_dbi.py", line 585, in connect conn = ibm_db.connect(dsn, '', '', conn_options) SQLCODE=-30081 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\ecjohnson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Users\ecjohnson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) I've connected to this database before in other .NET web applications so I'm not sure why this is not working. -
Connect and present data from two different tables in django
I'm trying to easily present data from two different tables (classes). I have an "Environment" class with all the environments details and a "Changes" class which contain history changes on all my environments. My view is currently showing all my environment details. I want to add to this view the last change been made on each environment (e.g last modified by: USER). My models.py look like this: class System(models.Model): system_name = models.CharField(max_length=40, blank=True) system_id = models.CharField(max_length=100, blank=True) system_clusters = models.ManyToManyField(Cluster, blank=True) system_owner = models.CharField(max_length=20, blank=True) def __str__(self): return self.system_name class Changes(models.Model): date = models.DateTimeField(auto_now_add=True) cluster = models.ForeignKey(System, on_delete=models.CASCADE) user = models.CharField(max_length=20, blank=True) change_reason = models.CharField(max_length=50, blank=True) def __str__(self): return self.date At first, i though to pass a dictionary to my template with the "system" as a key and a "change" as a value: last_changes = {} change = Changes.objects.filter(cluster__in=s.system_clusters.all()).order_by('-id')[0] last_changes[s.system_id] = change.change_reason Even though it partially works (I still trying to pars the dict in my template), I feel like this is not the right approach for the task. I'm hoping to reach a result where I can just call system.last_change in my template. Can I add another field for System class that will point to his last change in … -
How to make link between .Net and Django
Is there any research interested to show the differences between .NET and Django(Is it platform) And can I add what I want to Django library...