Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set up a db one-to-many relationship in both ways?
For example, one team has N members, but one member could be in N teams. How can I express this both-way relationship in django? or in Databases in general? Maybe I'm thinking about it wrong, but on the frontend I want to show all teams for example, or the teams of a player...Don't I need this? Thanks -
I can't migrate at another database
I have well working project on local. I use postresql. Ok. I create another database in postgres locally and specify new name/user/password in settings.py of project. When I do $ python manage.py makemigrations I get error as relation 'report_person' not exist And I have tried delete (and not delete) directory 'migrations'. delete pycache. I tried specify Sqlite3 as database - but the same error. Why I ask? My project don't want to work with another database) I succesfully push project on heroku. Specify parameters in settings.py. Create postgresql. But I can't make migrate on heroku) the same error. I do makemigrations and git commit before push on heroku, but no result Help me please. Thank you Have a nice day! -
Add button in table django Admin for view informations in template
I need to add a button to display the information in a template Here's my code: models.py class Worker (models.Model): name = models.CharField ('Name', max_length=30) surname = models.CharField ('Surname', max_length=30) class Salary (models.Model): worker = models.ForeignKey(Worker) salary_uah = models.IntegerField ('Salary', max_length=5) urls.py urlpatterns = [ url(r'^$',home, name='home'), url(r'^add/$',add_worker, name='add'), url(r'^act/$',acts, name='act') views.py def acts (request, id): if not request.user.is_authenticated(): return redirect('/admin/') worker = get_object_or_404(Worker, id=id) return render(request, 'zpapp/act.html', worker) admin.py @admin.register(Salary) class SalaryAdmin (admin.ModelAdmin): list_display = ('worker', 'salary_uah', 'button') search_fields = ('worker', 'salary_uah') list_filter = ('worker', 'salary_uah') def button(self, obj): return '<a class="button" href="{}">Print</a>'.format(reverse('act', args=[obj.id])) button.short_description = 'Actions' button.allow_tags = True When I run my code, I get an error: NoReverseMatch at /admin/zpapp/salary/ Reverse for 'act' with arguments '(2,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['act/$'] I used this post What is a NoReverseMatch error, and how do I fix it?, but it has not solved my problem -
Multi Django Project Single Celery Server
I have 3 Separate Django Projects sharing same DB running on same Machine. What I require is to configure Celery For them. Now my question is: 1.) Whether should I run separate celery daemons for separate projects, and set different vhosts and users in rabbitmq which I don't want to opt as it would be a waste of resources or 2.) Is there a way I can target all the tasks from different projects to a single celery server. Also, How would supervisord would be handy in the solution? -
Django- NoReverseMatch
I recently took over the development of a Python/ Django project, which uses Git as its version control, having not used either Python/ Django or Git much previously. Having pushed some changes I made to the server, I found that although the changes I made had fixed the bug I was working on (the bug was to do with a date value not sticking/ being saved when the user selected a date in a form on one of the pages), another part of the project had somehow broken (a page titled 'AddsOmits')... but I'm not sure how, as I hadn't made any changes to that part. The part that my fix actually broke may have come from an earlier version of the project, as I needed to checkout an earlier commit due to some errors I had while merging my changes to the master branch. So it may be that this is a bug which existed in an earlier commit. I have now reverted the version on the live server to what it was before I uploaded the fix- so it is now in a working state, apart from the 'date' bug that I am currently working on. On my … -
Django: invalid form
I am new to Django and is currently trying to make a user registration form for my application. Does anyone know why form.is_valid() is returning False? forms.py class RegistrationForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput) password = forms.CharField(widget=forms.PasswordInput) email = forms.CharField(widget=forms.EmailInput) class Meta: model = User fields = ['username', 'password', 'email'] views.py def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): print "valid" username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] User.objects.create_user(username=username, email=email, password=password) user = authenticate(username=username, passsword=password) if user is not None: login(request, user) return redirect('/admin') else: # return a blank form print "invalid" return render(request, 'registration/register.html', {'form': form}) -
Show data of another database in templates, not from django models
I just want to know if is it possible to show the data from the collections of my other two MongoDBs in my Django templates? Not just the ones from the django database. This is what my app does: I have a form for the user and that uses my models database. I uses two apps to process that, via subprocess in Celery, and each of them produces a MongoDB for the results. I want to show those results in my templates, but I don't know if what I'm doing is correct, or if Django offers some help. Here is what I've done so far: At the start of views.py, to check connection and access the documents: #This is calling my model and form from .forms import SampleForm from .models import Sample ....#some code here import logging # Get an instance of a logger logger = logging.getLogger(__name__) sys.path.append(settings.APP1_PATH) sys.path.append(settings.APP2_PATH) #MongoDB connection for App1 try: app1_db = pymongo.MongoClient(settings.MONGO_HOST, settings.MONGO_PORT)[settings.app1_MONGO_DB] except pymongo.errors.ConnectionFailure, e: logger.error("Could not connect to App1 MongoDB: %s" % e) #For the GridFS connection try: conn=pymongo.MongoClient(settings.MONGO_HOST, settings.MONGO_PORT) db = conn.app1fs app1fs_db = GridFS(db) except pymongo.errors.ConnectionFailure, e: logger.error("Could not connect to App1FS MongoDB: %s" % e) #MongoDB connection for App2 try: … -
Migration of Django field with default value to PostgreSQL database
https://docs.djangoproject.com/en/1.10/topics/migrations/ Here it says: "PostgreSQL is the most capable of all the databases here in terms of schema support; the only caveat is that adding columns with default values will cause a full rewrite of the table, for a time proportional to its size. "For this reason, it’s recommended you always create new columns with null=True, as this way they will be added immediately." I am asking if I get it correct. From what I understand, I should first create the field with null=True and no default value then migrate it and then give it a default value and migrate it again, the values will be added immediately, but otherwise the whole database would be rewritten and Django migration doesn't want to do the trick by itself? -
Django Setup with uwsgi and nginx determine if nginx is running
First time setting up a django site using nginx. I'm using uwsgi documentation to setup the site. So far the site renders, on debug = True static loads and without it static doesnt. I've detailed it here. What would be the best way to determine if requests for static are going to nginx. I suspect they're not because \var\log\nginx are both 0kb access and error . I use uwsgi --http :8000 --socket kb.sock --logto /tmp/kb.log --module kb.wsgi to run the server. -
Curl under proxy for django restframework giving value: Unable to parse connection string: ""
When i use curl under proxy for rest framework api testing in django i'm getting this error Exception Value: Unable to parse connection string: "" i have used curl -v --noproxy localhost -X POST -H "Authorization: Token <token id >" -d "email=d@c.co" "http://localhost:4000/api/....." and also tried export http_proxy="" while was working properly when i was not under proxy curl -X POST -H "Authorization: Token <token id >" -d "email=d@c.co" "http://localhost:4000/api/....." -
Specify limit_choices_to in model dynamically
Could you please help me to understand how do limit choices work in the model if it is necessary to limit by field of another model. Currently, I have two models: Group: class Group(models.Model): name = models.CharField(max_length=10, null=True) leader = models.OneToOneField( 'Student', related_name='+', null=True, blank=True, on_delete=models.SET_NULL, limit_choices_to={'group': 2}, ) and Students: class Student(models.Model): group = models.ForeignKey(Group, on_delete=models.PROTECT) name = models.CharField(max_length=140, null=True) brd_date = models.DateField(null=True) ticket = models.IntegerField(null=True, unique=True) So as you see every Student has it's group (configured by ForeignKey). But every group may or may not have its own leader. It's just one specific Student (configured by OneToOneField) who is chosen from the group to which he/she actually belongs. Without limiting by Group, it becomes possible to choose every Student as a leader to every group. In the provided Group model I've set limit_choices_to options to limit choices just to the Group 2 (for testing purposes). Is it possible to set this parameter dynamically and as a result have a possibility of creating Form class based on Group Model in which selection for Group leader allows choosing only students in this particular group? Thanks in advance. -
Unable to access media file belonging to nobody:nobody
When I deploy django project to centos, the media files uploaded from django admin belong to user and group nobody:nobody. I'm unable to access it through url. When I change the ownership to my user, then its accessible. How to allow these files to be accessed without specifying chmod explicitly? -
Django/Flask apps for data/config data management
I have a few applications where I have data in csv files. I want to move them into a web app where I can see the data in a web page (fetched from DB tables, one for each type of data) and have a generic way to edit the data in the tables/grid on the page. Is there any package/module that already provides this? I could build a small one myself but seeing if i can reuse something that exists -
Django: multiple ManyToMany values ALL contained queryset?
models.py class Tag(BaseModel): name = models.CharField(max_length=256,unique=True) class Product(BaseModel): tag_set = models.ManyToManyField(Tag) Getting queryset, products = Product.objects.filter( Q(tag_set__id__in=[12, 13, 14]), Q(is_active=True), ) This queryset would include products of which tag's id is any of 12 or 13 or 14. I want only products where all tags it has include 12, 13, 14 (ALL) ex) product -- tags(id): 12, 13, 14, 15 (O) ex) product -- tags(id): 12, 13, 15 (X) ex) product -- tags(id): 12 (X) (Sorry for bad English) How can I implement this? -
Copy a database column into another in Django
I am writing a migration that requires me to fill a field with existing data from another field (with same type and constraints). Is it possible in Django to copy the data in a single operation? The destination column already exists when I need to copy the data. In SQL, I would have written something like that: UPDATE my_table SET column_b = column_a; -
module object has no attribute 'rindex'
I recently converted my django project into individual apps. They seemed to be working fine before but when i tried making a login app for all the account views etc. I get an error AttributeError at /auth/login/ **Traceback:** File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ravinkohli/PycharmProjects/untitled1/login/views.py" in user_login 48. return redirect('/auth/accounts/profile/') File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/shortcuts.py" in redirect 116. return redirect_class(resolve_url(to, *args, **kwargs)) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/shortcuts.py" in resolve_url 205. return urlresolvers.reverse(to, args=args, kwargs=kwargs) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse 578. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix 432. self._populate() File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in _populate 307. for name in pattern.reverse_dict: File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse_dict 337. self._populate() File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in _populate 325. lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args)) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in callback 246. self._callback = get_callable(self._callback_str) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/utils/lru_cache.py" in wrapper 101. result = user_function(*args, **kwds) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable 95. mod_name, func_name = get_mod_func(lookup_view) File "/Users/ravinkohli/env_app_pw/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_mod_func 158. dot = callback.rindex('.') Exception Type: AttributeError at /auth/login/ Exception Value: 'module' object has no attribute 'rindex' my login view def user_login(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('/auth/accounts/profile/') else: return render(request, 'registration/login.html', {'error': 'User is not active'}) else: return render(request, … -
DJANGO RestFramework: override validate method to return custom data dict
class MySerializer(serializers.Serializer): field1 = serializers.CharField(max_length=100, required=False) field2 = serializers.CharField(max_length=100, required=False) # more fields def validate(self, data): data.update({'new_field': "some value"}) # print data return data when i use my POST api to upload payload and use this serializer to return formatted data, i miss this new_field key. although data var is updated with this new key, as I checked by printing data (as you can see commented print statement) but in my viewset, If I print serializer data, it doesn't show new_field key def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) # print serializer.data return Response({}) Am I missing something? -
How to add a form element on the new page that allows the user to change a topic from private to public
How to add a from element that allows the user to change a topic from private to public ? " Note: I am doing this in Django and Python {% extends "learning_logs/base.html" %} {% load bootstrap3 %} {% block header %} <h2>Add a new topic:</h2> {% endblock header %} {% block content %} <form action="{% url 'learning_logs:new_topic' %}" method='post' class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary">add topic</button> {% endbuttons %} </form> {% endblock content %} -
How to upload image using ckeditor in django?
models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = RichTextUploadingField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) url.py urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^accounts/login/$', views.login, name='login'), url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'', include('blog.urls')), ] # serving media files only on debug mode if settings.DEBUG: urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT }), ] I will upload image using CKeditor. There is no error. However, it looks like a picture. [https://i.stack.imgur.com/xrR6C.png] -
Implementing Django style API, chaining dots, inheritance
I'm trying to implement client for JSON API. I've worked with Django and i found the way it handles queries pretty interesting. For example: >>> from django.contrib.auth.models import User >>> user = User.objects.get(username='johndoe') >>> user <User: johndoe> >>> user.objects.get(username='johndoe') AttributeError: Manager isn't accessible via User instances I'm interested what Manager exactly is and if there is a simple way to implement it. I tried to do something similar, but failed miserably. Here is my first attempt: class Api(object): def __init__(self, api_key): self.api_key = key @property def player(self): return Player(api=self) class Player(object): def __init__(self, api): self.api = api def get(self, id_): ''' gets json and turns it into dictionary ''' self.name = data['name'] self.id_ = id_ return self So the usage would look like this: >>> api = Api('api_key_here') >>> player = api.player.get('player_id_here') However to me it feels sketchy and simply wrong to do it this way(which is certainly true). Problems here are: I have to send whole Api object to Player object Player object will still have get() method I don't know if using @property this way is acceptable Here is how i would like to use my Api class: api = Api('api_key_here') player = api.player.get('player_id') #getting player object item … -
Vagrant - Django server - Why is host redirecting to https?
I setup a vagrant VM with django installed, and setup the port forwarding like this: config.vm.network "forwarded_port", guest: 8000, host: 8001 So in the guest machine I run the django server like this: python manage.py 0.0.0.0:8000 And the server starts up and tells me its running on http://127.0.0.1:8000 When I open up firefox on the host machine and point it to http://127.0.0.1:8001, it automatically redirects to https://127.0.0.1:8001 and I get this error: An error occurred during a connection to 127.0.0.1:8001. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG Nowhere in the settings.py file does it force https. I don't know whats causing it to redirect to https, or how I can go about figuring that out. Is this a problem with virtualbox, vagrant or django? These error messages appear in the terminal where I run the server: [06/Jan/2017 05:17:22] code 400, message Bad request syntax ('\x16\x03\x01\x00¥\x01\x00\x00¡\x03\x03d') You're accessing the development server over HTTPS, but it only supports HTTP. [06/Jan/2017 05:17:31] code 400, message Bad HTTP/0.9 request type ("\x16\x03\x01\x00¥\x01\x00\x00¡\x03\x03É\x8aVY@¦Û2\x 9c'\x1a5n¬òðÿ𪪮pÛ%å\x15#8jÕQé\x00\x00") You're accessing the development server over HTTPS, but it only supports HTTP. So the question is why is my browser trying to access the server over … -
How to set Paypal redirect url in django oscar?
I got error while redirecting to local server through https request... i did't find any redirect paypal url settings to change the redirecting url to use http method .. how can i set paypal redircting url manually ? and a terminal error like this "You're accessing the development server over HTTPS, but it only supports HTTP." -
Django override_settings wont't work when running the whole test suite
I am getting a bit odd behaviour using the override_settings decorator, basically works when I run the test alone, but won't work if I run the whole testing suite. Explaining... In this test I am changing the REST_FRAMEWORK options, because when running this suite I want to set the authentication settings, with the other tests do not use authentication: @override_settings(REST_FRAMEWORK=AUTH_REST_FRAMEWORK) class AuthTestCase(TestCase): @classmethod def setUpClass(cls): super(AuthTestCase, cls).setUpClass() cls.client = Client() def test_i_need_login(self): response = client.get('/') self.assertEqual(response.status_code, 401) so if I do... $ python manage.py test myapp/tests/test_auth.py The settings are applied and works great! but if run the whole testing suite like: $ python manage.py test The test will fail. It seems to me that these settings (or some objects) are being cached from other tests. I also have another class in another test file that uses a Client instance in similar way. Python: 2.7 Django: 1.10 -
CKedit image upload not working
this is my urls.py from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from django.conf import settings urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^accounts/login/$', views.login, name='login'), url(r'^accounts/logout/$', views.logout, name='logout', kwargs={'next_page': '/'}), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'', include('blog.urls')), ] settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_JQUERY_URL = 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' error code enter image description here I will upload image using CKeditor. However, there is a 404 error. What should I do? -
Django/Python Library for importing and producing Excel documents?
Looking for an Excel library for Django and Python with specific requirements. There looks to be a number of libraries for Django and Python that enable the user to upload an Excel document into the database. What I am wondering is if there is a library that allows you to create an Excel document and export with conditional formatting, live formulas, creating tabs, and VLOOKUPS? The company I work for produces Excel reports for our analysts to review that requires these types of things. Researching as we are exploring other solutions than using Access, which is it pretty easy to control Excel from.