Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Posting to django from chrome extension won't set the attributes that are pass into the post
I am working on making a chrome extension that stores info from pages you are on and then posts them to my Django backend. I am having a problem with my post, the post makes it to the backend but it does not have any of the attributes that i give it. Here is my post request: I know that my post is making it to the backend here is an example of what the data looks like in my backend: as you can see all the attributes are being set as unknown. In my models.py I am setting them to unknown if no attributes are present so I believe that the post is not working right. I think that maybe my json is not formatted right and that is why it is not taking the attributes but I do not know what the correct format is. any help would be much appreciated. thanks in advance! -
Django - FileField model object - ValueError when saving a many-to-many an instance with a many-to-many relationship
I am trying to save an instance in a model called Document which has a many to many relationship with a project it refers to. Model class for Document is reported as follows: class Document(models.Model): project = models.ManyToManyField(Project, verbose_name='Projects') name = models.CharField(max_length=100, verbose_name='Name') document = models.FileField(upload_to=document_path, verbose_name="File") doc_type = models.CharField(max_length=30, choices=DOCUMENT_TYPE, verbose_name='Type', null=False) In the view.py I use the following code: .. form = DocumentUploadForm(postdata, request.FILES) if form.is_valid(): newdoc = form.save(commit=False) newdoc.document = request.FILES['document'] newdoc.name = newdoc.document.name newdoc.save() newdoc.project.add(proj) when I try to save the instance (newdoc) I receive the following error: *** ValueError: "<Document: Document object>" needs to have a value for field "document" before this many-to-many relationship can be used. although the newdoc.document field has been instantiated correctly. Could anyone explain where I am going wrong here? Thanks, Antonello -
Display based on Django WagtailCMS SITE_ID
How can I create an if block to display one of my sidemenu's based on the WagtailCMS SITE_ID? Tried this, but it doesn't work {% if settings.SITE_ID == 1 %} {% include 'includes/_home-sidebar-left.html' %} {% else %} {% include 'includes/_home-sidebar.html' %} {% endif } -
Silence exception in django template tag
I am writing a very simple template tag, which returns the verbose name of a application: @register.simple_tag def get_verbose_name(app_name): return apps.get_app_config(app_name).verbose_name According to the documentation I should return default values and not throw exceptions if possible. Should I handle the exception and return None or throw it if the question doesn't exist? -
How to make use of the Factory Object in this use case
I want to be able to generate a Factory object using Factory Boy. My current issue is that am not able to "override" the ApplicationType.objects.get() which is smack in the middle of code. models.py from django.db import models class ApplicationType(models.Model): """ Types of applications available in the system/ """ title = models.CharField(max_length=30) def __str__(self): return self.title utils.py from .models import ApplicationType self.base_details = {} def get_application_type(self, value): """ Get types of applications. When successful it Populates the self.base_details with an application_type key Args: value (object): value to be parsed Returns: bool: True when value is ok, Else false Raises: """ item_name = "Application Type" self.base_details['application_type'] = None try: if value: try: result = ApplicationType.objects.get(title=value) self.base_details['application_type'] = result.id return True except ApplicationType.DoesNotExist: self.error_msg = "Invalid Value: {}".format(item_name) return False else: self.error_msg = "Blank Value: {}".format(item_name) return False except: raise So to test, I create an ApplicationType factory tests.py import factory import pytest application_types = ['Type 1', 'Type 2'] class ApplicationTypeFactory(factory.Factory): class Meta: model = ApplicationType title = "I need the two application_types listed above to go into the creation of this Factory Object" @pytest.mark.django_db() def test_get_application_type_populates_dict_when_value_provided_exists_in_database(self): """Populates base_details dict when value is found in database""" for entry in application_types: assert self.base_info_values.get_application_type(entry) … -
how to add Subdomain per page in wagtail
sry for my bad english How can I make sub-domains for each page? I want make make a sub-domain for each store in my site and I want to be automatically added to nginx tnx -
blank=True not working on CloudinaryField()
I am sure this is something simple that I am missing. But I am setting up and image sharing site and I am using cloudinary to directly upload images to the cloud. I have the CloudinaryField field in my models.py like this image = CloudinaryField('image', blank=True, null=True) However when I try to fill out the image field by choosing an image to upload, it does not update the image field and when I submit the form it says no image detected and will not let me create the new image post. I have the page setup so the image is uploaded as soon as it is selected via the pop up window, and the images are being uploaded to cloudinary. views.py def post_new_image(request): form = PostPhotoDirectForm(request.POST) cl_init_js_callbacks(form, request) if request.method=='POST': form = PostPhotoDirectForm(request.POST) if form.is_valid(): post=form.save(commit=False) post.author=request.user post.image=form.cleaned_data['image'] post.save() return redirect('post_detail', pk=post.pk) else: form = PostPhotoDirectForm() return render(request, "blog/post_new_image.html", {'form':form}) forms.py from django import forms from .models import Post from cloudinary.forms import CloudinaryJsFileField, CloudinaryUnsignedJsFileField from cloudinary.compat import to_bytes import cloudinary, hashlib class PostForm(forms.ModelForm): class Meta: model=Post fields = ('title', 'text') class PostPhotoDirectForm(PostForm): image = CloudinaryJsFileField() post_new_image.html {% extends 'blog/base.html' %} {% block content %} <div id="direct_upload"> <h1>New Image Post</h1> <form … -
Retrieving one to one related model
I have a profile model that I related to the user model via a onetoonefield. Now I want to pass the profile on to a form so I can edit the profile. I know I can obtain the profile via current_user = request.user get_object_or_404(UserProfile, user=current_user) or current_user = request.user UserProfile.objects.filter(user=current_user) However I figured, since I have the model defined as: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, related_name='user_profile') some_data = models.CharField(max_length=255) I could just do something like myprofile = current_user.user_profile but that doesn't seem to work. Is it possible to do it in someway like that via the related name? -
Django: How to filter ForeignKey choices by request.user with ModelFormSet
I just want to filter select field in a form, regarding a currently logged user. Every user has own categories and budgets - I want to display only a models related with a currently logged user. I've tried stuff with filtering before is_valid field, but with no result. Please, find my code below: views.py @login_required def day_data_multiadd(request, no_of_lines=0): no_of_lines = int(no_of_lines) CostFormSet = modelformset_factory(Cost, form=DataAddForm, extra=no_of_lines) if request.method == 'POST' and 'form' in request.POST: formset = CostFormSet(request.POST, request.FILES) if formset.is_valid(): for form in formset.forms: f = form.save(commit=False) f.user = request.user f.save() else: formset = CostFormSet(queryset=Cost.objects.none()) if request.method == 'POST' and 'no_line' in request.POST: generate_form = MultiaddGenerateForm(request.POST) if generate_form.is_valid(): cd = generate_form.cleaned_data return HttpResponseRedirect(reverse('core_sm:day_data_multiadd', args=(cd['formy'], ))) else: generate_form = MultiaddGenerateForm() return render(request, 'core_sm/costs/multi_add.html', {'formset': formset, 'no_of_lines': no_of_lines, 'generate_form': generate_form}) forms.py class DataAddForm(forms.ModelForm): class Meta: model = Cost fields = ['title', 'value', 'publish', 'category', 'budget'] exclude = ['user'] labels = { 'title': _('Tytuł'), 'value': _('Wartość'), 'publish': _('Data'), 'category': _('Kategoria'), 'budget': _('Budżet') } models.py class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=200) publish = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_ur(self): return reverse('core_sm:category_detail', args=[self.id]) class Budget(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=200, db_index=True) value = … -
How to conditionally exclude django admin list display items
I have a quote model in my Django admin, that I set up an admin class for with a list display of some of its fields. One of these fields is a 'partner id'. I have multiple different settings files that extend from a base settings file for whatever environment I'm in. In these settings files, theres a SHOW_PARTNER_ID variable. I want to be able to remove partner_id from the list display if SHOW_PARTNER_ID is set to false, and vice versa. I have a method that returns an empty string for each row of the quote table that doesn't have a partner id, but I would rather just remove the column completely. class QuoteAdmin(admin.ModelAdmin): list_display = ('date', 'device_model', 'first_name', 'last_name', 'customer_address', 'customer_link', 'customer_history', 'site_name', 'status', 'partner_id') def partner_id(self, obj): from django.conf import settings try: if settings.SHOW_PARTNER: if obj.partner: return u'<a href="/admin/quote/partner/{}/">{}</a>'.format(obj.partner.id, obj.partner.id) else: return '' else: return '' except Exception as e: logging.error(e) return '' -
Travis CI Error : No Module name common
I am running my tests on Travis-CI container but the tests seems to be failing with the following output The command "flake8" exited with 0. 0.39s$ py.test --cov Traceback (most recent call last): File "/home/travis/virtualenv/python2.7.11/bin/py.test", line 11, in <module> sys.exit(main()) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/config.py", line 47, in main config = _prepareconfig(args, plugins) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/config.py", line 132, in _prepareconfig pluginmanager=pluginmanager, args=args) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda> _MultiCall(methods, kwargs, hook.spec_opts).execute() File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 595, in execute return _wrapped_call(hook_impl.function(*args), self.execute) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 249, in _wrapped_call wrap_controller.send(call_outcome) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/helpconfig.py", line 32, in pytest_cmdline_parse config = outcome.get_result() File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 279, in get_result _reraise(*ex) # noqa File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 264, in __init__ self.result = func() File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 596, in execute res = hook_impl.function(*args) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/config.py", line 880, in pytest_cmdline_parse self.parse(args) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/config.py", line 1030, in parse self._preparse(args, addopts=addopts) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/config.py", line 1001, in _preparse args=args, parser=self._parser) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__ return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 338, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 333, in <lambda> _MultiCall(methods, kwargs, hook.spec_opts).execute() File "/home/travis/virtualenv/python2.7.11/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 595, in … -
Integrating django with mean stack
I'm working on a project that requires us to implement an email client using web sockets. The problem is, the protocol is written in django and the front end is built in Angular 2 with a node api for user authentication. As we cannot use a library for the protocol in node and lack of skill and time to redo the front end in django we don't have much choice but to integrate both. The question is how to achieve this? I have tried to google it and came up with solutions that involve using socket.io and redis. The solutions I found was based on a model where django is used to build the application and node is a middle-ware service. I am looking for guidance from experienced professionals who might have came across a similar problem. From what little I know the only other option is to integrate the front end ( Angular 2 ) with django and remove the node api. I'm open to different approaches to this problem and/or suggestions on which technologies to use (socket.io or redis or any other). Thanks in advance. -
Python - Cycle Tags Not Working Properly
I have this code <div class="product"> <div class="container"> <div class="product-right-top"> <div class="top-product"> <div class="col-sm-3 chain-grid simpleCart_shelfItem" style="width: 250px; height: 400px;"> {% for product in products %} <div class="grid-span-1"> {% if product.productimage_set.all %} {% for item in product.productimage_set.all %} {% if item.featured %} <a href="{{ product.get_absolute_url }}"> <img class="img-responsive " src="{{ item.image.url }}" alt=" " \ style="height: 400px; width: 200px; border: Highlight; border-radius: 10%;"> <div class="link"> <ul > <li><i> </i></li> <li><i class="white1"> </i></li> </ul> </div> </a> {% endif %} {% endfor %} {% endif %} </div> <div class="grid-chain-bottom "> <h6><a href="{{ product.get_absolute_url }}">{{ product.title }}</a></h6> <div class="star-price"> <div class="price-at"> <ul class="star-footer"> <li><a href="#"><i> </i></a></li> <li><a href="#"><i> </i></a></li> <li><a href="#"><i> </i></a></li> <li><a href="#"><i> </i></a></li> <li><a href="#"><i> </i></a></li> </ul> </div> <div class="price-at-bottom "> <span class="item_price">{{ product.price }}</span> </div> <div class="clearfix"> </div> </div> <div class="cart-add"> <a class="add1 item_add" href="{{ product.get_absolute_url }}">VIEW PRODUCT <i> </i></a> <a class="add2" href="#"><i> </i></a> <div class="clearfix"> </div> </div> </div> {% cycle " " "</div><div class='col-sm-3 chain-grid simpleCart_shelfItem'>" %} {% endfor %} </div> </div> </div> Now My Problem is that it is iterating after 2 loops and from 3 product it is starting in new line. I checked all possible way to correct near cycle tag. Please help with this tag … -
Performing a Javascript function on a django form before adding to database
I have created a template in Django that makes a form based off a model. When the form is submitted currently the data that was previously in the password field of the form is placed into the database rather than the changed value that is included in the "id_Password" field once the onclick action is performed. What is want is the JavaScript to perform it's function, then the form is submitted with the data that is in the field once the function has been performed. Can anyone provide any incite? {% extends "base.html" %} {% load staticfiles %} {% block content %} <h2> To add an account to your wallet fill in the form below and click "Add account to wallet" </h2> <h3>Load your encryption file</h3> <input type="file" id="input"> <form action="/yourwallet/addpassword/" method="post">{% csrf_token %} <script type="text/javascript" src="https://cdn.rawgit.com/ricmoo/aes-js/e27b99df/index.js"></script> <ul> {{form}} </ul> <input type="submit" name="submit" value="Add account to wallet" onclick="handleFiles()"> <input type="button" name="test" value="test" onclick="handleFiles()"> <script> function handleFiles() { var file = document.getElementById('input').files[0]; var reader = new FileReader(); reader.readAsText(file); reader.onload = function(e) { var key = reader.result; var element = document.getElementById("id_Password") var password = element.value; var key_256 = aesjs.utils.utf8.toBytes(key) var textBytes = aesjs.utils.utf8.toBytes(password); var aesCtr = new aesjs.ModeOfOperation.ctr(key_256); var encryptedBytes = aesCtr.encrypt(textBytes); … -
Invalid version number Error whilst attempting to use Django-notifications-hq
I'm trying to use the django-notifications app within my project. However, when I try to put it into my installed apps and then run 'makemigrations' command, I am given this error about a strictversion. Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/hamidadelyar/Documents/django/django/django/core/management/__init__.py", line 349, in execute_from_command_line utility.execute() File "/Users/hamidadelyar/Documents/django/django/django/core/management/__init__.py", line 323, in execute django.setup() File "/Users/hamidadelyar/Documents/django/django/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/hamidadelyar/Documents/django/django/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/hamidadelyar/Documents/django/django/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/hamidadelyar/Library/Python/2.7/lib/python/site-packages/notifications/models.py", line 8, in <module> if StrictVersion(get_version()) >= StrictVersion('1.8.0'): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/version.py", line 40, in __init__ self.parse(vstring) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/version.py", line 107, in parse raise ValueError, "invalid version number '%s'" % vstring ValueError: invalid version number '1.10.dev20151115101025' I've updated the setuptools to the latest version with no luck. Any ideas? Thanks! -
render additional information with form in formview django
I'm writing a contact application for django, where users can contact another one responding to a specific post. Here is my message model: class Message(models.Model): person_src = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) person_dst = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) replyTo = models.ForeignKey("self", on_delete=models.CASCADE) # reply to another message post = models.ForeignKey(Post, on_delete=models.CASCADE) # posts concerned by the message date = models.DateTimeField() content = models.CharField(max_length=1000) This is my django form for message class NewMessageForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea) class Meta: model = Message fields = ['content'] And the associated view: class NewMessageFormView(View): form_class = NewMessageForm template_name = 'messaging/new_message.html' #get just displays an empty form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): message = form.save(commit=False) message.content = request.content message.date = datetime.date.today() message.save() if message is not None: return redirect('messages:detail', message.id) return render(request, self.template_name, {'form': form}) I want to be able to send in addition to the form, the associated post which the user is responding to, and all previous messages associated with the current one (in case the user is answering). Is it possible to render additional information in the view ? -
Object id in Django url
I have a Post model like the one below: class Post(models.Model): user = models.ForeignKey(User) posted = models.DateTimeField(auto_now_add=True) content = models.CharField(max_length=150) picturefile = models.ImageField(upload_to="post_content", blank=True) I want to be able to put the id of each post in an url so I can visit each post individually. I did this before with the id of an user to view the user their profile page. url(r'^profile/(?P<username>\w+)/$', Dashviews.public_profile_view, name='public_profile_view'), But how do I make the same type of url, but instead with an id of a post? -
how can i create an web app that will communicate with hive and display the results on webpage
I want to create an web app that will communicate with hive and display the results on webpage. How can i proceed with this idea using Python and Django -
how to perform a django test with a request.post?
ive got a view method i would love to test. i am supplying the self.client.get method with the data but it fails to validate the form. what am i doing wrong? using django 1.8 python 3.5 this is the view method def saveNewDriverInfo(request): if request.user.is_authenticated(): form = DriverForm(request.POST) if form.is_valid(): new_Driver = form.save() carid = form.cleaned_data['carID'] Car = get_object_or_404(Car, pk=carid) return redirect('carmanager:carDetails', carID=carid else: return HttpResponse("something went wong some where! yes i said wong!") this is the test method def test_saveNewDriverInfo(self): self.client.login(username="testuser",password="testuser321") response= self.client.get(reverse('carmanager:saveNewDriverInfo'),data={'form':{'carID':'1034567','Driver_Last_Name':'daddy','Driver_First_Name':'daddy','Driver_Middle_Initial':'K','entered_by':'king'}}) #self.assertRedirects(response, expected_url, status_code, target_status_code, host, msg_prefix, fetch_redirect_response) self.assertNotContains(response, 'something went wrong' ,200) also note this test work cause it gets the response is what i got. but the line that is commented is what i want to use But i cant seem to feed the information to the DriverForm. any help will be greatly appreciated -
Appending to an object in Django
I need to append information to an object in Django rather than update it. I have this database: Database: ----------------------- ColA | ColB ----------------------- 1 | "Test string." And the code that updates: o = Model.objects.select_related().filter(ColA=1).update( ColB = "Entry 2") This will set ColB to Entry 2. I want to be able to append rather than update. Is there a way I can append the text so that ColB will be set to "Test string. Entry 2."? -
error: list of session IDs must follow -s
celeryd is stoped working and its not starting. i tried below code: sudo nohup python manage.py celeryd & ps -els | grep celeryd and getting error: error: list of session IDs must follow -s Your valuable reply help me a lot. -
Django regular class vs model class
I try to manage a small video sites for personal purposes. I have created a class named Video and have a lot of attributes to set inside this class. But there's also a lot of them I don't want to save in my project database. The solution I found for now is to create a volatile "working" class and a model class aside. Selected attributes that are worth to be saved in the database are declared in the model class and the other ones (+ the ones to be saved) are also present in the working class. A kind of "hash id" make the link between the 2 class. For example when I instanciate an object from the working class I will need to retrieve the name of the video it represents in the database and then check for the model object stored in the DB that have the same hash id. I have the feelling this is not the best way to proceed. What would be the straight way to do this kind of thing? Thanks, -
How to test a Django class-based view receives correct arguments?
I can't work out how to test that a Django class-based view receives the expected kwargs from a URL pattern. If I have my urls.py: from django.conf.urls import url from myapp import views urlpatterns = [ # ... url( regex=r"^people/(?P<pk>\d+)/$", view=views.PersonDetailView.as_view(), name='person_detail' ), ] And my views.py: from django.views.generic import DetailView from myapp.models import Person class PersonDetailView(DetailView): model = Person I can test that a request to the URL calls the correct view like this: from django.test import TestCase from django.urls import resolve from myapp import views from myapp.factories import PersonFactory class UrlsTestCase(TestCase): def test_person_detail_view(self): PersonFactory(pk=3) self.assertEqual(resolve('/people/3/').func.__name__, views.PersonDetailView.__name__) But I'd also like to test that a request to /people/3/ results in {'pk': '3'} being passed to PersonDetailView, and I can't work out where in a class-based view receives the kwargs in order to test it (by patching the receiving method, I guess). -
bootstraps CSS and JS files not working
I am trying to get bootstraps affixed side bar menu to work following the code used in this link. http://www.bootply.com/109952 I have the CSS and the JS in respective files, but when i load the web page, it looks a lot different, and none of the functionality works!! Am i refernecing the files wrong in my HTML? Do i need to include some other ref, like the Jquery library? If so, how? {% load staticfiles %} <link rel="stylesheet" href="{% static 'mainCSS/mainWEBcss.css' %}" type="text/css"> <script type="text/javascript" charset="utf-8" src="{% static 'mainJS/sideBarJS.js' %}"></script> The rest of the code is the exact same from the web site i copied and pasted from, with the addition on the three lines pasted above. I know my load static files is fine though! -
use own hook with django clearsessions
I store some elements during a user-session in the database (I can't use the sessionbase items). Is there a posibility to write my own cleaning-proc which is called when the "clearsessions" command is called with managed.py? I want to clean up this elements out of the database together with the cleaned session. I didn't found something in the docs. Thanks Martin