Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named graphite.settings
Intro I had a running instance of Graphite-Web 0.9.15, due to recent bug fixes and general slowness when loading data with Grafana I decided I should probably try and upgrade Graphite. What I did I went on and git cloned all the repositories and then ran python setup.py install to the default location, the config files stayed where they were, I didn't merge. When I tried to run the uwsgi app again I got the following error: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 219, in __call__ self.load_middleware() File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 37, in load_middleware for middleware_path in settings.MIDDLEWARE_CLASSES: File "/usr/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner self._setup() File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 95, in __init__ raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e)) ImportError: Could not import settings 'graphite.settings' (Is it on sys.path?): No module named graphite.settings I'm not sure running pip install will do the trick since PyPI only has the 0.9.15 version. Conclusion What I need is to find a way to make this django instance recognise the graphite.settings module. I did manage to import graphite.settings module when runnning python externally at some point, now it's … -
Query a Django PostGres field defined as ArrayField(HStoreField))
The Django documentation mentions possible queries for ArrayField and HStoreField. However, if I have a model like this: class MyModel(models.Model) entry = ArrayField(HStoreField()) how would I query for MyModel entries where any array entry contains a dictionary pair? E.g. if the data looks like instance entry 1 [ {a:5, b:6, c:1} {a:3, b:2, c:} {a:, b:9, c:7} ] 2 [ {a:4, b:6, d:1} {a:2, b:2, d:} {a:5, b:4, d:7} ] 3 [ {e:5, b:6, c:1} {e:3, b:2, c:} {e:, b:1, c:7} ] and I want to get all instances where a:5, then instances 1 and 2 will be returned, and if I want those where b:4 then only instance 2. -
Trying to pass a session from a Model Save into a view
I have some custom validation on one of my models, and I generate errors based on which validation failed. I want to pass these errors to my view. class TimeSheet(models.Model): O = "Open" S = "Submitted" A = "Approved" R = "Needs review" STATUS_CHOICES = ( (O, "Open"), (S, "Submitted"), (A, "Approved"), (R, "Needs Reviewing"), ) start_date = models.DateField() end_date = models.DateField() person_id = models.ForeignKey(Person) status = models.CharField(max_length= 50, default="Open", choices=STATUS_CHOICES) submitted_id = models.IntegerField(default=0) approved_id = models.IntegerField(default=0) submitted_date = models.DateTimeField(auto_now_add=True, blank=True) approved_date = models.DateTimeField(auto_now_add=True, blank=True) def get_absolute_url(self): return reverse('tande:timesheet', kwargs={'id': self.id}) def save(self, *args, **kwargs): ok_to_continue = True start_date = self.start_date end_date = self.end_date if end_date < start_date: error = "ERROR: Start date must be before end date" ok_to_continue = False # make sure both dates are in the same month if start_date.month != end_date.month: error = "ERROR: Start and end dates must be in the same month" ok_to_continue = False # VALIDATION if ok_to_continue: super(TimeSheet, self).save(*args, **kwargs) else: print error self.request.session['error_from_save'] = error However this raises the error - AttributeError: 'TimeSheet' object has no attribute 'request' Why is self.request.session not working? Is there another way to pass this back to my view? -
sorl.thumbnail not showing img in admin panel
I'm using django 1.10 and last sorl.thumbnail Here is my models.py from sorl.thumbnail import ImageField class StockImage(models.Model): image = models.ImageField(upload_to='stock', blank=True, null=True, verbose_name=_('Image')) here is admin.py from sorl.thumbnail.admin import AdminImageMixin class StockImageInline(AdminImageMixin, admin.StackedInline): model = StockImage extra = 1 @admin.register(Stock) class StockAdmin(TranslationAdmin): group_fieldsets = True list_display = ('title', 'city', 'start_date', 'finish_date', 'unlimited', 'publish') inlines = [ StockImageInline, ] -
Filter by value from Db
i need to filter all objects by some value from db for each object in models.py: class CurrencyLot(models.Model): seller = models.ForeignKey(User, on_delete=models.CASCADE) stock = models.PositiveIntegerField() order = models.PositiveIntegerField() lot_status =models.BooleanField() created_at = models.DateTimeField(auto_now_add=True, auto_now=False) updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) in view.py: def currency_list(request): lot_list = Lot.objects.all().filter(lot_status=True).filter(stock__gte=???) return render(request, 'lots/list.html', {"lot_list":lot_list}) in need to fiter stock__gte by min_orderfor each object. It is possible without for loop? With for loop i may check this and append correct lots to new lot_list -
how to add link to choicefield(selectpicker) django
i want add a href link to choisfield(selectpicker)django, but i dont hve eny idea how it wille work class facture_form(forms.Form): description_article = forms.ChoiceField(required=True, widget=forms.Select(attrs={'class': 'selectpicker','data-live-search':'True'}), label="") def __init__(self, *args, **kwargs): super(facture_form, self).__init__(*args, **kwargs) articles = article.objects.values_list('ref_article', 'description') self.fields['description_article'].choices = articles -
how to allow user to create only one profile in django?
views.py class CreateProfile(LoginRequiredMixin, CreateView): login_url = '/accounts/login/' template_name = 'profile/new_profile.html' model = Profile fields = ['full_name','profile_pic','title','summary'] def user_redirect(request): if request.user.is_authenticated(): return render(request, '#redirect to some page') if the user is already logged in he should not be able to access the 'profile/create' url. -
Is it possible/easy to use postgreSQL instead of Redis with Stream-Framework?
How can I tweak stream-framework to make it use postgreSQL instead of Redis -
Django - ImageField, static files and collectstatic
I'd like to have an ImageField in the admin form for my model (say, for an individual's profile). And I'd like to display this image in a view later on. This is the model I have : class Individual(models.Model): ind_name = models.CharField(max_length=100) ind_photo = models.ImageField(default="default.jpg") def __str__(self): return self.ind_name This is what I have in the settings for my website : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = '/static/media/' MEDIA_ROOT = os.path.join(BASE_DIR,"static/media") These are the urls of my app: urlpatterns = [ url(r'^$', views.index, name="index") ] I know how to use static files (e.g. CSS, Javascript), and to get them to work in both development and production. But I have no clue how to get images to work. I've read Managing static files and Deploying static files, but I still don't get it. With the code above the image gets saved in the proper folder (i.e. /static/media at the level of my site). But I have no clue : 1) how to display it in a template, 2) whether it would be best to keep these images in my app's static folder, 3) and (if 2) whether I would need to run collectstatic every time someone uploads an … -
How to redirect two pages [duplicate]
This question already has an answer here: How do I redirect with Javascript? [duplicate] 6 answers it is my edit and delete pagethis my alert page using javascript 1.How to redirect those pages while clicking delete button. plz some one help me -
django 1044 access denied for user 'my created azure db username'@'%' to database 'my created azure db name'
I have a Django app on Heroku, I'm trying to connect that app to a Microsoft azure mySQL database. but the following error while in the Heroku BASH terminal when trying to create a superuser of migrating appears. django.db.utils.OperationalError: (1044, "access denied for user 'azure username' to database 'azure db name'") where azure username and azure db name are my personal corresponding database parameters that i've created through Microsoft's portal my password is correct i've double checked it. this is my production settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'azure db name', 'USER': 'azure username', 'PASSWORD': '', 'HOST': 'eu-cdbr-azure-north-e.cloudapp.net', 'PORT': '3306' } } is there an extra parameter that i need to enter for validation? or an extra package that i need to install? this is requirements.txt appdirs==1.4.0 dj-database-url==0.4.2 Django==1.10.2 gunicorn==19.6.0 packaging==16.8 pyparsing==2.1.10 six==1.10.0 MySQL-python==1.2.5 mysqlclient==1.3.9 Thanks -
Images are cracked
Images are cracked. I wrote in photo.html, {% extends "registration/accounts/base.html" %} {% block content %} <div class="container"> <h2 class="page-header">{{ photos.title }}</h2> <div class="row"> <div class="col-xs-4"> <img class="img-responsive" src="/media/{{ photos.image }}"> </div> </div> <a class="btn btn-primary" href="{% url 'accounts:upload' photo.id %}">UPLOAD</a> </div> {% endblock %} I do not know why.How can I fix it? Is "img tag" wrong? -
Post form with return key does not post the submit button name
I have multiple form on the same page. Each form as a submit button that look like that: <button type="submit" name="button_name" style="display:none;" class="btn btn-primary btn-striped" disabled="disabled"><span class="glyphicon glyphicon-floppy-saved"></span><span class="button-text"> {% trans "Save" %}</span></button> When I click on the save button, everything works OK, I can distinguish in the view which form as been posted like that : if request.method == 'POST': if 'button_name' in request.POST: [...] elif 'button_name_2' in request.POST: [...] But if I press the enter/return key once I have completed a text field, the form is posted but I got no button name in the request.POST dictionnary. The only buttons I have ont the page are submit button and they all have type="submit" name="button_name" in it. -
Django-graphos not working with ModelDataSource
I am trying to render a Line chart in my html page using Django-graphos library. It works when I use hard coded data & SimpleDataSource but not with ModelDataSource. It throws a -'dict' has no attribute 'Column_Name' error. Following are the files & code in them- models.py class promo_input(models.Model): Store_Week = models.TextField('Tesco_Week',max_length=100, blank=True, null=True) Category_Name = models.TextField('Category_Name',max_length=100, blank=True, null=True) Promo_Sales = models.DecimalField('Promo_Sales', max_digits=20, decimal_places=10, default=0.0) def __str__(self): return '%s' % (self.Tesco_Week) views.py from graphos.sources.model import ModelDataSource from graphos.renderers.gchart import LineChart class PromoProfile(LoginRequiredMixin, generic.View): def get(self, request, *args, **kwargs): the_form = forms.InputForm(request.GET or None) week_exclusions = ['YTD', 'PTD'] trend_sales_promo = promo_input.objects.filter(Category_Name="Beers, Wines & Spirits").values('Store_Week').exclude(Store_Week__in= week_exclusions).annotate(ty_promo_sales_cw = Sum('Promo_Sales'),ly_promo_sales_cw = Sum('Promo_Sales_LY')) print(type(trend_sales_promo)) print(trend_sales_promo) data_source = MyModelDataSource(trend_sales_promo,fields=['Store_Week','ly_promo_sales_cw']) # Chart object chart = LineChart(data_source) context = {"form" : the_form,"chart":chart} return render(request, "sales/promotions_view.html", context) promotions_view.html <div class="row"> <div class="col-lg-12"> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript">google.load("visualization", "1", {packages:["corechart"]});</script> {{ chart.as_html }} </div> </div> Error- Exception Type: AttributeError Exception Value: 'dict' object has no attribute 'Store_Week' -
Django cannot import settings
I'm trying to use django-admin dbshell (any other cmd gives the same result) on my project. And I got You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So I did export DJANGO_SETTINGS_MODULE=mysite.settings and now I get no module named 'mysite' Of course I replace 'mysite' with the name of my app. Btw I already had this in my code: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "firmflaws.settings") any idea? Thanks -
Can I create and pass a session from a custom save() method to a view
I have a custom save method on one of my models where I have some custom validation. I run a lot of checks and create a custom 'error' that I then want to pass back to my view so i can display it on my template. So i am trying to use a session to pass over my set error to my view so I can add it to some response data. However, I get a global name request is not defined... because this is a save method not a view(!?). So I'm a bit confused about how I can make this work.... and whether I can use sessions like this... def save(self, *args, **kwargs): ok_to_continue = True start_date = self.start_date end_date = self.end_date person = self.person_id if end_date < start_date: error = "ERROR NUMBER 1" ok_to_continue = False # make sure both dates are in the same month if start_date.month != end_date.month: error = "ERROR NUMBER 2" ok_to_continue = False # VALIDATION if ok_to_continue: print "it's trying to save" super(TimeSheet, self).save(*args, **kwargs) else: print error request.session['error_from_save'] = error print "save is unsuccessful" And then in my view I want to access my session to pass the error to my … -
Form with simple-captcha not showing and no errors
Django form with simple-captcha is not showing on the productions server with nginx and uwsgi. No errors in logs. But when running development server the form is showing. What could be the problem? Python 2.7.3 uwsgi 2.0.14 -
pytest transaction not commited
I am using python pytest to write unite test and mysql database for my project. Pytest setup method use sqlachecmy for testing data generation. I have python function call_my_flow() which execute two different flow depending on condition.First flow use sqlalchemy connection and second flow use django connection for database insert. I have written two unit test using pytest to check both flow. First flow (where sqlalchemy connection used) commited process flow transaction in database and pytest running as per expectation. But second flow (where django database connection used) not commited process flow transaction in database and test fails. import pytest from myflow import call_my_flow @pytest.fixture(scope="class") @pytest.mark.django_db(transaction=False) def setup_my_flow(): call_my_flow() @pytest.mark.usefixtures("setup_my_flow") class TestGenerateOrder(object): @pytest.fixture(autouse=True) def setuporder(self): self.first_count = 2 self.second_count = 5 @pytest.mark.order1 @pytest.mark.django_db def test_first_flow_count(self): db_count = get_first_count() assert db_count == self.first_count @pytest.mark.order2 @pytest.mark.django_db def test_second_flow_count(self): db_count = get_second_count() assert db_count == self.second_count -
Django rest framework get one to many relationship data
I have a django model named Event, which referes to Customer model. event_name = models.CharField(max_length=200, unique=True) customer = models.ForeignKey(customer_models.Customer, db_index=True, on_delete=models.SET_NULL, related_name='customer_events', null=True) event_location = models.CharField(max_length=200, default='') event_date = models.DateField() I need to get the customer list along with the latest event name for each user. I need it for the API. Customer serializers.py file is class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' Customer views.py file is class CustomerViewSet(viewsets.ModelViewSet): queryset = Customer.objects.all() serializer_class = CustomerSerializer How I can I accomplish the result? -
Convert JavaScript date() to Python Django models.DateTimeField
I using django model forms to submit data to the database. I use JavaScript to auto-fill the form with the following document.getElementById('id_date_received').value = Date(); This outputs: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) while django's models.DateTimeField expects: 2017-02-06 11:39 How do i convert: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) to 2017-02-06 11:39 Thanks -
How to translate object attributes in Django?
Is it possible make translations for Django objects? Let's say I have model Category and Product. When user adds new product, they have to choose from Category objects. I would like to translate those names. class Category(models.Model): name = models.CharField(max_length=100, verbose_name=_('Category')) def __unicode__(self): return u'{}'.format(self.name) class Meta: verbose_name_plural = _('Categories') class Product(models.Model): user = models.ForeignKey(User, verbose_name=_('Company'), related_name='products') name = models.CharField(max_length=200, verbose_name=_('Name'),) category = models.ForeignKey('Category', verbose_name=_('Category'), related_name='products') class Meta: verbose_name = _('Product') verbose_name_plural = _('Products') def __unicode__(self): return u'{}'.format(self.name) So before running the server, I create couple of categories like 'Electronics'. What should I do to make name 'Electronics' translated to name 'Elektronika' for SK language? -
Django get values from bootstrap checkbox
I am trying to get values from bootstrap checkbox. Here is my fancy checkbox: <div class="container"> <div class="[ col-xs-12 col-sm-6] text-center"> <div class="[ form-group ]"> <input type="checkbox" name="fancy-checkbox-success-custom-icons" id="fancy-checkbox-success-custom-icons" autocomplete="off" /> <div class="[ btn-group ]"> <label for="fancy-checkbox-success-custom-icons" class="[ btn btn-success ]"> <span class="[ glyphicon glyphicon-plus ]"></span> <span class="[ glyphicon glyphicon-minus ]"></span> </label> <label for="fancy-checkbox-success-custom-icons" class="[ btn btn-default active ]"> Nature </label> </div> </div> <div class="[ form-group ]"> <input type="checkbox" name="fancy-checkbox-info-custom-icons" id="fancy-checkbox-info-custom-icons" autocomplete="off" /> <div class="[ btn-group ]"> <label for="fancy-checkbox-info-custom-icons" class="[ btn btn-info ]"> <span class="[ glyphicon glyphicon-plus ]"></span> <span class="[ glyphicon glyphicon-minus ]"></span> </label> <label for="fancy-checkbox-info-custom-icons" class="[ btn btn-default active ]"> History </label> </div> </div> </div> In my views I'm tryign to get which checkboxes are on like this: def random_trip(request): keyword = request.POST.get('keyword') checks = request.POST.getlist("checkbox-success-custom-icons" ..... However, all I get is empty list. Where is the problem? -
Managing Stream APIs in Django 1.7 App ( like twitter, facebook, weather ... etc)
I am new to Django architecture and currently working on a projet where I want to make a generic/flexible batch to manage multiple streaming APIs ( like Twitter, Facebook, Weather APIs, ... ) and frequently update the feed using javascript. I find difficulty in finding 3rd party packages which I can build on top of them a flexible solution like GetStream.io. Any hints or tips on how achieve such feature will be highly appreciated. -
python regex to replace all single word characters in string
I am trying to remove all the single characters in a string input: "This is a big car and it has a spacious seats" my output should be: output: "This is big car and it has spacious seats" Here i am using the expression import re re.compile('b(?<=)[a-z](?=)\b') this matchs with first single character in the string ... Any help would be appreciated ...thanks in Advance -
Pythonic method for Django loop
I am pretty beginner with Python and Django and I would like to know How I could improve few Python lines with a better Pythonic syntax. Reasons : I have two tables : BirthCertificate and Identity which have a folderId field. This field corresponds to a directory ID in LogicalDOC web application. When I create different PDF documents to the same person, all documents have to go on the same directory thanks to this directory ID. My objective : I fill an Identity form, my function create a new directory if the person doesn't exist (and by the same way, I get a new directory ID) or takes an existing ID directory if the person already exists. With BirthCertificate table, I want to know if the same person already exists in Identity table. If yes : I take the Identity folderID and I update my BirthCertificate table with this number If no : I redirect user to Identity form. Why ? Because users have to create Identity form before BirthCertificate form. In my script, When I generate BirthCertificate PDF to a person X, I want to check before if the person X is already registered in Identity. If yes, I …