Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku cannot find wsgi app
I am trying to deploy a Django app on Heroku. The deployment works but when I run the web page I get the following error: ImportError: No module named hello.wsgi My Proc file reads as: web: gunicorn hello.wsgi --log-file - I would appreciate suggestions if anyone knows why I get this error. -
Django AWS Postgres Time Mismatch
I have hosted my Django application in Amazon Elastic Beanstalk and using a postgresql database. In my settings.py I have: TIME_ZONE = 'America/Chicago' Then I have logged into my Elastic Beanstalk instance and issued the following commands: sudo vim /etc/sysconfig/clock Then edited the ZONE parameter as follows: ZONE="America/Chicago" Then opened up the Postgresql RDS and created a new parameter group named timezoneinfo and set the following: timezone = America/Chicago However, when I edit some date time field in the django admin, the today and now is correctly set to Chicago's local time, but after saving the record, time time appears to be 5 hours ahead, which is UTC time. Where else do I need to change to make sure the local time is being used? -
Django error: has no attribute 'ForeingKey'
everyone! I jus start leaning Python and Django. Can somebody help me with this topic. I can't understand why it doesn't work: from django.db import models # Create your models here. class Topic(models.Model): """ Тема которую изучает ползователь""" text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): """возвращает представление модели""" return self.text class Entry(models.Model): """ Информация изученная пользователем """ topic = models.ForeingKey(Topic) text = models.TexField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'entries' """ Возвращает строковое представление модели""" def __str__(self): return self.text[:50] + "..." The result is: File "/Users/stepankurakin/pystudy/learning_log/learning_logs/models.py", line 14, in Entry topic = models.ForeingKey(Topic) AttributeError: module 'django.db.models' has no attribute 'ForeingKey' How can i fix it? -
templateDoesNotExist error when trying to render template
I'm new to Django, and I'm trying to render a template but it keeps showing me this error: templateDoesNotExist at / baseTemplates/base.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.11.4 Exception Type: TemplateDoesNotExist Exception Value: baseTemplates/base.html Exception Location: C:\Users\Sheuntopsax\lib\site-packages\django\template\loader.py in get_template, line 25 Python Executable: C:\Users\Sheuntopsax\python.exe Python Version: 3.6.2 Python Path: ['C:\Users\Sheuntopsax\Desktop\mypicky', 'C:\Users\Sheuntopsax\python36.zip', 'C:\Users\Sheuntopsax\DLLs', 'C:\Users\Sheuntopsax\lib', 'C:\Users\Sheuntopsax', 'C:\Users\Sheuntopsax\lib\site-packages'] -
Using either SQLAlchemy or DjanjoOrm, what is the most efficient method of retrieving and displaying a "comment" post and all of its "reply" posts?
Take any typical comment system; every comment can have a reply and every reply can have more replies. I've having a hard time wrapping my head around the methodology that could be used to most quickly, and using python(3) and either flask/django ORM's: > query all comments in commentDB where page_id == x > cycle thru each result and build a list of lists where each entry gets added to it's parent_id list and after each entry re-sort the list based of time of entry and then in the view/template: > cycle through each list and format according This seems like such an incredibly taxing operation to complete every time a new comment is added. I'm hoping to gather some insight on how this can be done "at scale". Is it better to run a separate query against every comment looking for other comments that has its id as the other's parent_id? My database will be Postgres, in case that is helpful to know. -
linking css file to base html docuemnt - django
I have a django project and i have been trying to link a css file to the base.html document to begin implimenting some css to my file. I have bootstrap linked already but i want to add more customization... Here is what i have so far.. {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'css/blog.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script> </head> <body> <div class="container-fluid blue5"> {% block content %} {% endblock %} </div> </body> </html> here is the css file .blue5 { background-color: lightblue, } -
How to get equally distanced rows based on date from a django query?
I am writing a django application where I am collecting data from database. My model contains a datefield called date. I want to fit the dates into a line chart. As there can be hundreds of dates in the table. I want to minify the data by selected 10 equally distanced dates from the entire table. For example, if my rows contain dates 1/09/2013 - 20/09/2013, I want to get: 1/09/2013 3/09/2013 5/09/2013 7/09/2013 9/09/2013 11/09/2013 13/09/2013 15/09/2013 17/09/2013 19/09/2013 Here is my query: data = Model.objects.all() I want to do it in the safest way possible since dates present in my database can be irregular. How do I divide data based on data.date like this? Is there a prebuilt function for django? Any suggestions would be appreciated. -
Graphene-Django: Would like to use graphene.ObjectType for custom query
I currently have a working query that is in this form: class Query(graphene.AbstractType): algorithms = graphene.String(id=graphene.String()) def resolve_algorithms(self, args, context, info): # Much code here that goes to external server to get data algorithms = {} # Instantiate dictionary # Code here to populate this dictionary return algorithms While this does work, it's a kludge because I'm forcing the dictionary object to be returned as a string. I've looked around for articles to show me how to change the type to graphene.ObjectType() but with no success. Might someone know how? Robert -
ManyToMany filter not working Django
I have the following models class A(models.Model) a_id = models.IntegerField(primary_key=True) created_by_id = models.ManyToManyField(User,db_column="user_id", related_name="created_by_id") last_updated_by = models.ManyToManyField(User, db_column="user_id", related_name="last_updated_by",) resolved_by_id = models.ManyToManyField(User, db_column="user_id", related_name='resolved_by_id') class B(models.Model): .... class C(models.Model): .... class User(models.Model): user_id = models.IntegerField(primary_key=True) user_name = models.CharField(max_lenght=30) field_1 = models.ForeignKey(B) field_2 = models.ForeignKey(C) when I apply serialization on the class A I get the following error in SQL table not found, I am using OracleDB ORA-00942: table or view does not exist ('SELECT "USER"."USER_ID", "USER"."USER_NAME" FROM "USER" INNER ' 'JOIN "A_CREATED_BY_ID" ON ("USER"."USER_ID" = ' '"A_CREATED_BY_ID"."USERMST") WHERE ' '"A_CREATED_BY_ID"."A_ID" = %s') I have looked into the Django docs for ManytoMany still unable to figure out what the problem was. -
python manage.py runserver not working? why?
enter image description here I can't start server. I am reinstall python and django. Why not working? -
How to use .date() from the query performed earlier in django?
I am writing a django application where I have to get data using date part of a datetimefield as a part of result of a query stored in a variable. Here is my code: datas = Model1.objects.all() for data in datas: new_data = Model2.objects.get(date = data.datetime.date()) Model1 has a field called datetime which is a datetimefield and Model2 has a field called date which is a datefield. When I run the server, this is the error I get: self.model._meta.object_name data.models.DoesNotExist: Model2 matching query does not exist. I am guessing date = data.datetime.date() is what is causing this. Any idea what's going on? -
Django Union of ManyToMany Model Querysets
Here's a basic many to many relationship model: from django.db import models class ManyToManyModel(models.Model): name = models.CharField(max_length=50) class MainModel(models.Model): name = models.CharField(max_length=50) many_to_many_ref = models.ManyToManyField(ManyToManyModel) I create instances of these models as follows, tying the ManyToManyModel instances to MainModel instances: from app1.models import ManyToManyModel, MainModel m2m1 = ManyToManyModel(name='Number 1') m2m1.save() m2m2 = ManyToManyModel(name='Number 2') m2m2.save() m2m3 = ManyToManyModel(name='Number 3') m2m3.save() m2m4 = ManyToManyModel(name='Number 4') m2m4.save() mm1 = MainModel(name='Main 1') mm1.save() mm1.many_to_many_ref.add(m2m1) mm1.save() mm2 = MainModel(name='Main 2') mm2.save() mm2.many_to_many_ref.add(m2m1) mm2.many_to_many_ref.add(m2m2) mm2.many_to_many_ref.add(m2m3) mm2.save() mm3 = MainModel(name='Main 3') mm3.save() mm3.many_to_many_ref.add(m2m4) mm3.save() Now, I want to get a Queryset of ALL ManyToManyModels associated with all MainModel objects constructed. There may be a better way to do this, but this example uses union (new in django 1.11): for mm in MainModel.objects.all(): try: m2m_union = m2m_union.union(mm.many_to_many_ref.all()) except NameError: m2m_union = mm.many_to_many_ref.all() Now, the m2m_union contains four entries in its QuerySet, but let's filter out to one that I care about, e.g. this query should only return ManyToManyModel with name='Number 1': m2m_union.get(name__endswith='1') This returns the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File ".../lib/python3.6/site-packages/django/db/models/query.py", line 384, in get (self.model._meta.object_name, num) app1.models.MultipleObjectsReturned: get() returned more than one ManyToManyModel -- it returned 4! … -
Serializer Nested relationships not working as it sholuld be
Nested relationships django 1.11 serializer: class PostDetailSerializer(ModelSerializer): url = post_detail_url user = UserSerializer(read_only=True) image = SerializerMethodField() html = SerializerMethodField() tags = TagSerializer(many=True) category = CategorySerializer() source = SourceSerializer() class Meta: model = Post fields = [ 'id', 'url', 'title', 'image', 'slug', 'content', 'source', 'source_link', 'category', 'tags', 'html', 'publish', 'timestamp', 'user', ] Response: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 3, "url": "http://127.0.0.1:8000/api/v1/posts/new-postas/", "title": "New Postaas", "image": null, "slug": "new-postas", "content": "asssaasssasa", "source": { "id": 1, "name": "prothom alo", "slug": "prothom-alo" }, "source_link": "http://prothom-alo.com/", "category": { "id": 2, "url": "http://127.0.0.1:8000/api/v1/posts/category/news/", "name": "news" }, "tags": [ { "id": 1, "name": "tech", "slug": "tech" } ], "html": "<p>asssaasssasa</p>\n", "publish": "2017-08-31", "timestamp": "2017-08-31T12:28:28.686538Z", "user": { "id": "ac32460f-fb7e-4755-9f7e-7c13085ee92b", "email": "hello@ihemel.net", "first_name": "Hasibul Amin", "last_name": "Hemel" } } This is fine nested relation retrieving the data. But again in my category details api serializer below: class CategoryDetailSerializer(ModelSerializer): url = category_detail_url posts = PostDetailSerializer(many=True, read_only=True) class Meta: model = Category fields = [ 'id', 'url', 'name', 'posts' ] Here my post serializer does not output any data in the api. I don't know. there no bug or error, just the value is not coming. The category details api response: HTTP 200 … -
queryset object not callable django
So... I want to make a search bar in django and have come up with this so far: view: class IndexView(LoginRequiredMixin, generic.ListView): template_name = 'patients/index.html' context_object_name = 'all_patients' def get_queryset(self): queryset = patient.objects.all() query = self.request.GET.get('q') if query: queryset = queryset.filter( Q(First_Name__icontains=query) | Q(Surname__icontains=query) | Q(DOB__icontains=query) ).distinct() return queryset else: return patient.objects.all() and my button on my template: <form class="navbar-form navbar-left" role="search" method="get" action="{% url 'patients:index' %}"> <div class="form-group"> <input type="text" class="form-control" name="q" value="{{ request.GET.q }}"> </div> <button type="submit" class="btn btn-default">Search</button> </form> and the model: class patient(models.Model): TITLE_CHOICES = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Ms', 'Ms'), ('Miss', 'Miss'), ) Title = models.CharField(max_length=100, blank=True, choices=TITLE_CHOICES) First_Name = models.CharField(max_length=250, default='') Surname = models.CharField(max_length=250, default='') DOB = models.DateField() Address_line_1 = models.CharField(max_length=250, blank=True, default='') Address_line_2 = models.CharField(max_length=250, blank=True, default='') City = models.CharField(max_length=250, blank=True, default='') Postcode = models.CharField(max_length=20, blank=True, default='') Occupation = models.CharField(max_length=250, blank=True, default='') Referring_manager = models.CharField(max_length=250, blank=True, default='') Telephone = models.PositiveIntegerField(blank=True, null=True, default='') Mobile = models.PositiveIntegerField(blank=True, null=True, default='') Email = models.EmailField(null=True, blank=True, default='') Employer = models.CharField(max_length=100, blank=True, default='') Notes = models.TextField(max_length=1000, blank=True, default='') OH_Provider = models.CharField(max_length=100, blank=True, default='') def get_absolute_url(self): return reverse('patients:patientInfo', kwargs={"pk":self.pk}) def __str__(self): return self.First_Name + " " + self.Surname I am getting the error: [31/Aug/2017 18:55:04] "GET /patients/patients?q=rupali HTTP/1.1" 500 … -
Bokeh change source data in CallbackJS
I am trying to create a bokeh plot in a Django app to graph swimming events for an athlete. I am plotting duration (time swam) vs date (date of swim meet). The idea is to have one plot and be able to use a SelectBox widget to choose which event is shown on the graph. The problem is that when I change the source of the data in a CallbackJS function, the graph does not update and instead goes blank. I plot an initial line source = ColumnDataSource(data=dict( x=data_source['x_'+first_event], y=data_source['y_'+first_event], date=data_source['date_'+first_event], time=data_source['time_'+first_event] )) plot.line('x', 'y', source=source) so that a line is displayed when the page loads, then I update the source data in my callback function like so if (f == "50 Freestyle") { source.data['x'] = data.x_50_free; source.data['y'] = data.y_50_free; source.data['date'] = data.date_50_free; source.data['time'] = data.time_50_free; } for each event. Finally, at the end of the function I call source.change.emit(); to update the ColumnDataSource. This seems to work as I am able to log source.data[] to the console and see it update depending on the select widget option, but the plot itself does not update it simply goes blank. How do I also update the plot to reflect the change … -
Error in javascript - Replace hash tags with links
I have the following problem: I have a simple View.py: def Article_view_2(request): return render_to_response('articles.html', {'articles': Event.objects.all()}) There is an HTML part where I output all the data from the model to get a news line: {% block name %} {% for event in articles %} {{ event.cover_event.url}} {{ event.author }}</h4> {{ event.event_date|date:'F j' }} {{ event.event_title }} div class="item" {{ event.event_text }} div {{ event.event_a }}{{ event.event_b }}{{ event.event_c }} {{ event.all_rate }} {{ event.index }} {% endfor %} {% endblock %} I also use the javascript code to replace #hastags with links: var str = $('.item p').html(), regex = /(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/gi; function replacer(hash){ var replacementString = $.trim(hash); return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>'; } $('.item p').html( str.replace( regex , replacer ) ); But when I open the page, I get the same description - {{event.event_text}} - for all posts. What's my mistake??? -
Django-Crispy-Forms - how to put inline fields inside a fieldset
I need to put inline fields of a form in crispy forms but inside a fieldset. I can make this without the fieldset but if i use the Fieldset this is not compatible with the Div Class of crispy-froms. I can make this to show the fielset legend but obviously the form fields are not inside the fieldset in the html code. def __init__(self, *args, **kwargs): super(NewOrderForm, self).__init__(*args, **kwargs) self.fields['sector'].empty_label = None self.helper = FormHelper() self.helper.layout = Layout( Div('sector'), Fieldset( 'Datos del Dispositivo', ), Div( Div('article', css_class="col-sm-12"), Div('serial', css_class="col-sm-8"), Div('article_password', css_class="col-sm-4"), css_class='row', ), Fieldset( 'Datos de la Orden', ), Div( Div('work', css_class="col-sm-4"), Div('article_details', css_class="col-sm-8"), css_class='row' ), Div( Div('cash_advance', css_class="col-sm-6"), Div('initial_price', css_class="col-sm-6"), css_class='row' ), ) self.helper.add_input(Submit('submit', 'Crear Orden')) When i put the Div iside the Fieldset get this error 'Fieldset' object has no attribute 'Div' Is there any way to create a fieldset with multicolumn fields??? -
Django template tag format
I have the following method on a model: @property def get_total_planned_stops(self, *args, **kwargs): owner = self.owner planned_total = DailyRoute.objects.filter(stage=1).aggregate(Sum('planned_stops')) return planned_total In my template the variable {{ item.get_total_planned_stops}} renders as: {'planned_stops__sum': 183} I only want the number to be displayed. What am I doing wrong? -
Django displace image and some text separately in checkbox options
I have a ManyToManyField of 'services' in form in which I would like to display the 'service' image and some other 'service' information underneath the image. Here is the code I have so far in my Form class BookingForm(forms.Form): services = CustomMultipleChoiceField( queryset=Service.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class CustomMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): #Some how pass the obj.image separately here!!! <------ return u"{0}<br/>{1}min / R{2}".format(obj.title, obj.duration, obj.price) And in my template I show the option as follows: <input {% for m2moption in model.m2moptions.all %}{% if m2moption.pk == pk %}checked="checked"{% endif %}{% endfor %} type="checkbox" id="id_form_services-{{forloop.parentloop.counter0}}-{{forloop.counter}}" value="{{ pk }}" name="form-{{forloop.parentloop.counter0}}-services" /> <label for="id_form_services-{{forloop.parentloop.counter0}}-{{forloop.counter}}" class="checkbox-label"> <div class="service-img" style="background-image: url(/media/{{choice.3}}); width: 50px; height: 50px;"></div> {% autoescape off %}{{choice}}{% endautoescape %}<br/> </label> As you can see in my template I need some way to access the object value for the 'service' image and the rest of the information separately. How can I achieve this? Thank you. -
Is it possible to use django-modeltranslation outside of admin?
I use django-modeltranslation app in my Django 1.11 project. I successfully install app and make settings, also registered models for translation as it was recommended in docs. Question: Is it possible to use this app outside of admin? If it possible what I need to do? translation.py: class ArticleTranslationOptions(TranslationOptions): fields = ('title', 'body',) translator.register(Article, ArticleTranslationOptions) -
My admin section is not showing all the data of post
I was making a Django app. I make a Model and registered it on admin section but all I can see in admin section is message and user. My Model is:- class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) total_votes = models.IntegerField(editable=False,default = 0) def __str__(self): return self.message and my admin file is:- from django.contrib import admin from .models import Post,Comment # Register your models here. admin.site.register(Post) admin.site.register(Comment) I could not find the error can anyone help please. If you need any extra information my repository is here -
Preventing model save and raising a validation error from a pre_save signal
I am trying to prevent a model save if I have a page where the name is changed on an update. Ideally I would use the clean method and raise a validation error: def clean (self): // if the name of the page has changed raise ValidationError({'name':'Sorry you cannot change this'}) However, I can't obtain the original name to compare it against the new instance name (can I?) So I then tried using signals which enables me to grab the original name @receiver(pre_save, sender=Page) def prevent_save_if_name_same(sender,**kwargs): instance = kwargs.get('instance') old_model = sender.objects.get(pk=instance.id) if old_model.name == instance.name: // i would like to raise a validation error However, I can't raise a ValidationError from within the signal which will propagate to the model save() method. When I try this I get the Django debug page - not the display of the error next to the name field as you would expect. Any help much appreciated! -
How to add custom domains(SSL enabled) to user profile in Django?
I have a Django (DRF) enabled web app where users can create their profile. Profile url looks like this - https://mywebsite.com/username . I want to add a feature where users can map their custom domain(buy a new domain or use existing domain)to the profile page. How do I do this? How to make sure SSL is enabled in all custom domains without making my users buy separate SSL certificates? -
Error when deploying Django app on Heroku
I am trying to deploy new code at Heroku. The changes I made are simple, no changes to settings or requirements or anything fundamental. However, when running git push, I get... =====> Downloading Buildpack: https://github.com/heroku/heroku-buildpack-python.git =====> Detected Framework: Python -----> Installing requirements with pip ImportError: No module named site ! Push rejected, failed to compile Multipack app. ! Push failed Does anybody have a clue what may be going on here? I found similar questions already posted, but no clear answer and the proposed solutions didn't work in this case. Heroku support suggested so far: $ heroku config:unset PYTHONPATH $ heroku config:unset PYTHONHOME Following this, the deployment was possible, but the application stopped working. By adding those variables back, the application was online again, but deployment would again fail. Looking for a solution for two days now - I would appreciate any advice. -
How to integrate Geodjango with Google Maps API 3?
I have a geodjango queryset containing several fields, but want to use only user_name, location (point field) which I want to use as a marker in google maps api 3. Bear with me as I don’t know Javascript and I have a series of questions. Take this as conceptual brainstorming for a novice. My stackoverflow search suggests, I need to serialize the queryset objects to JSON. I use the built-in serializer module to convert to JSON. I think the JSON objects are converted in views.py (let’s call it ‘json_data’). Are these JSON objects stored in the postgis database? Wouldn’t that be redundant? Furthermore, how do I reference them in the map.js (google maps api 3) javascript file? I want to (import?link?) JSON objects to display them as location markers. Thirdly, I want to know how to declare and iterate the javascript variable ‘locations’. Guide me if I went unnecessarily convoluted way to do a simple task. For var(i=0;i< locations.length;i++){[ [json_data.user_name, json_data.point], ] var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(49.279504, -123.1162), zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP }); var infowindow = new google.maps.InfoWindow(); var marker, i; for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new …