Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What Are The Advantages of Building a Web-Page with Django as Opposed to Solely Using HTML5/CSS3?
Essentially, my questions are as stated above in the title. What I'm really seeking to know is why it would be privy of me to build a web-page utilizing the Django framework as opposed to solely building it out with HTML5 and CSS3. I do know that Django utilizes bootstrapping of HTML5 and CSS and this is where my questions are raised over the efficiency of using the Django framework as opposed to solely using HTML5/CSS3. 1.) What are the advantages of Django? 2.) What does utilizing the Django framework offer me that HTML5/CSS3 do not? 3.) HTML5 can also build dynamic web-pages as can Django. Why would Django be better for a dynamic web-page? I am looking for a very valid answer here as I am about to start building my web-page. The responses I get to these questions will be the nail in the coffin for which method I will be using to build the web-page. Thanks ladies and gentleman and I hope you find this question to be worth your while in answering. -
Making Django & Vue.js work together with {% verbatim %}
I'm trying to make django & Vue work together even though they share the same {{ X }} template syntax. I know that from django 1.5 we can use the {% verbatim %} tag. So I thought I could use django templates as usual and in the section where I need VUE to take over I would just use the {% verbatim %} tag. However instead of loading my vue data django loads the {{ variable }}. For example my django code looks something like this: {% verbatim %} <div id='sessions'> <h2>{{message}}</h2> </div> {% endverbatim %} And in my app.js file I have: var sessions = new Vue({ el: '#sessions', data: { message: 'Hello Vue!' } }) But instead of rendering Hello Vue! it renders {{message}} The console doesn't show any error and vue loads correctly otherwise. How I can make the two work together? Ideally without the need to change the vue.js {{}} syntax. -
Django localhost gives 500 Error Server Error when DEBUG = False, however ALLOWED_HOSTS=['*']
I'm running my Django site on locally, and when DEBUG=True it works fine. However, when I set DEBUG=False, it returns a 500 Server Error. ALLOWED_HOSTS has been set to ['*'], and it still returns a 500 Server Error. Here's my settings.py: import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "u!*)ik^c1uuptc_iq$hj^o4fmb6b^r%yk((uium3h0!)o+e$4i" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Application definition INSTALLED_APPS = [ 'my_app.apps.MyAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # greater consistency between gunicorn and `./manage.py runserver`. See: # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': … -
Json to fullcalendar object
I'm new to using fullcalendar and I cant quite wrap my head around turning the json request to plot on the calendar My model instead of using title, start, end, and all_day Is instead using name, start_date, completion_date, all_day as a result the calendar wont render the objects from my model onto the fullcalendar My views.py is def view_calendar(request): jobs = Job.objects.all() return HttpResponse(events_to_json(jobs), content_type='application/json') THIS IS GENERATING A JSON OBJECT SHOWN AS [{"completionDate": "2015-11-06", "startDate": "2015-11-06", "allDay": false, "name": "342345", "id": 7}, {"completionDate": "2017-04-30", "startDate": "2017-02-19", "allDay": false, "name": "Calendars", "id": 9}, {"completionDate": "2015-02-28", "startDate": "2015-02-26", "allDay": false, "name": "Lowe's Remodel ", "id": 4}, {"completionDate": "2015-02-04", "startDate": "2015-01-18", "allDay": false, "name": "Lowe's Remodel 2", "id": 1}, {"completionDate": "2015-09-13", "startDate": "2015-05-13", "allDay": false, "name": "Lowe's Remodel 3", "id": 5}, {"completionDate": "2017-04-30", "startDate": "2017-04-21", "allDay": false, "name": "WONDER", "id": 10}, {"completionDate": "2015-09-03", "startDate": "2015-08-03", "allDay": false, "name": "aaa gfdsgfs dgfgsd daaa gfdsgfs dgfgsd daaa gfdsgfs dgfgsd daaa gfdsgfs dgfgsd d", "id": 6}, {"completionDate": "2016-04-22", "startDate": "2015-02-24", "allDay": false, "name": "dgfs3344", "id": 3}, {"completionDate": "2015-02-26", "startDate": "2015-02-01", "allDay": false, "name": "gfdgdfs", "id": 2}, {"completionDate": "2015-11-06", "startDate": "2015-11-06", "allDay": false, "name": "ssssgf", "id": 8}] I have no idea how to render this object … -
Cannot import name views from my Project Level Folder
My Django application says that it cannot import the name views in my urls.py file. This I assumed was a problem in the project level file considering Django said: Exception Location: /home/django/django_project/django_project/urls.py in , line 18 However when I navigate to this file I find this: """oop3 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ # URLS coming in here are sent to the URL file on the ticketr app # url(r'^', include('ticketr.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) No where above does it mention views. The error is coming from line 18 in my urls.py of my application which looks like this """oop3 URL Configuration The `urlpatterns` list … -
Django & gunicorn on VPS gives error: ImportError No module named 'vp.wsgi'
When I try to check the status of gunicorn I get the following error: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2017-04-22 19:23:39 UTC; 10min ago Main PID: 7295 (code=exited, status=3) Apr 22 19:23:39 vp-first gunicorn[7295]: return util.import_app(self.app_uri) Apr 22 19:23:39 vp-first gunicorn[7295]: File "/home/tony/vp/vpenv/lib/python3.5/site-packages/guni Apr 22 19:23:39 vp-first gunicorn[7295]: __import__(module) Apr 22 19:23:39 vp-first gunicorn[7295]: ImportError: No module named 'vp.wsgi' Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7300] [INFO] Worker exiting (pi Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7295] [INFO] Shutting down: Mas Apr 22 19:23:39 vp-first gunicorn[7295]: [2017-04-22 19:23:39 +0000] [7295] [INFO] Reason: Worker fai Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOT Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Unit entered failed state. Apr 22 19:23:39 vp-first systemd[1]: gunicorn.service: Failed with result 'exit-code'. It says ImportError: No module named 'vp.wsgi' When I edit my gunicorn configuration file the following is in there: [Unit] Description=gunicorn daemon After=network.target [Service] User=tony Group=www-data WorkingDirectory=/home/tony/vp/vp ExecStart=/home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:$ [Install] WantedBy=multi-user.target I have to note that my wsgi.py file is located: ~/vp/vp/vp/vp/wsgi.py My virtualenv is located at: ~/vp/vpenv My settings are located at: ~/vp/vp/vp/config/settings/production.py I … -
How to identify id of object being accessed django
So what I am trying to do in Django is writing a delete function. Basically I have a manytomanyfield set for my Course model where I specify the relationship with the User model which i have called students. students = models.ManyToManyField('User', blank=True, related_name='studies') From looking through django documentation and some other stackoverflow questions, I found that I could use course.students.remove(user). to remove a user object from a specific course. However, what I am having trouble with is understanding how I can find the specific course id at the specific instance. So this is my url. url(r'^courses/(?P\d+)$', CourseDetail.as_view(), name='courses.detail'), I want to find out the current identifier for the course object being accessed so that I can eventually filter through my course objects looking for the specific course in order to remove the student. -
How to preserve position after page reload using infinite scroll in Django
I have implemented infinite scroll for my data objects using jQuery and Waypoints. Works fine but I want to make it more convenient. First of all I`m looking for a way to preserve position after page reload. Also would be nice to add fixed pagination bar with a possibility to dislay your curent page dynamically while scrolling. I have add one, but how to dynamically display your position. Implies, I have 20 objects per page, when scrolling down for 20 next it should automatically switch current page for second one on pagination bar. And vice versa for scrolling up. Another question is when choosing exact page at my current pagination menu it opens separate page with link 'http://127.0.0.1:8000/?page=2' for example, and displays objects only from 41th to 60th. I need it to open exact page but with possibility to scroll up and down for previous and next pages. Which way it`s possible to do this? Here is my code below. models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): type = models.CharField(max_length=11) par = models.PositiveIntegerField() year_from = models.PositiveIntegerField() year_to = models.PositiveIntegerField() size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) … -
How to show perisan (jalali) calendar in django?
i want to show times and dates in persian (jalali) calendar in django template but timezone.now() just show Gregorian calendar in template , how can i use jalali calendar in django template ? -
Django serializers, foreignkeys error
I have 2 tables, class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) curp = models.CharField(max_length=50) rfc = models.CharField(max_length=12) gender = models.CharField(max_length=20) class Employee(models.Model): id = models.IntegerField(primary_key=True) joining_date = models.DateField() salary = models.DecimalField(18, decimal_places=2, max_digits=50) status = models.IntegerField() person = models.ForeignKey(Person, related_name='persons', on_delete=models.CASCADE) user = models.ForeignKey(User) branch = models.ForeignKey(Branch) On the serializer im trying to show the person data into Employee but im getting this error ot AttributeError when attempting to get a value for field persons on serializer EmployeeSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Employee instance. Original exception text was: 'Employee' object has no attribute 'persons'. Serializers class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('name', 'curp', 'rfc', 'gender') class EmployeeSerializer(serializers.ModelSerializer): persons = PersonSerializer(many=True) class Meta: model = Employee fields = ('persons') It's my first time working on django so i dont get how to call the foreing keys. In my database i have the table Employee with 3 foreign keys (user, person and branch) Thanks! -
ImportError: cannot import name '__version__' error while trying to run Django project
I am not sure whether such format of question is valid. Simply I spent three hours trying to google the issue, but I the worst think is that I can't figure out where to look for the root cause of the problem. I am not experienced at analyzing traceback beyond elementary syntax error or missing module issues. I beg you guys, could you give a hint on what direction to dig ? Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import … -
Custom template tag don't work as expected (django)
My custom template tag is called change_page and should change page=x in the url without changing anything else in the url. (That means anything in the url, before and behind the ?. That's the template code part: (it works with the standard django paginator) {% if page_obj.has_previous %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=page_obj.previous_page_number %}" class="left_sharp">Zurück</a> {% else %} <a tabindex="2" href="" class="noteditable">Zurück</a> {% endif %} <div class="screen_only"> {% for i in paginator.page_range %} {% ifequal page_obj.number i %} <a href="" tabindex="2" class="noteditable">{{ i }}</a> {% else %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=i %}">{{ i }}</a> {% endifequal %} {% endfor %} </div> {% if page_obj.has_next %} <a href="{{ request.path }}?{% change_page current=request.GET.urlencode page=page_obj.next_page_number %}" class="right_sharp">Weiter</a> {% else %} <a href="" tabindex="2" class="noteditable">Weiter</a> {% endif %} </nav> {% endif %} The code of the template tag change_page: @register.simple_tag def change_page(current="", page=""): args = current.split('&') all='' for arg in args: all += re.sub(r'page=[0-9]+', 'page='+str(page), arg) + '&' all = all[:-1] return all It doesn't work. It allways returns an empty string. What did I wrong? -
Django model lookup on reverse ManyToMany Field
I am somewhat new to Django and I'm trying to solve what is probably a fairly simple task. I have two models (Destination and Tour). Tour has a ManyToManyField to destination in that a tour can be assigned to multiple destinations. class Destination(TimeStampedModel): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) site = models.ForeignKey(Site, db_index=True, related_name='guide_destination') sub_title = models.CharField(max_length=100, blank=True) active = models.BooleanField(default=False) description = models.TextField(blank=True) image = models.ImageField(null=True, blank=True, upload_to="guide/destination/") image_caption = models.TextField(null=True, blank=True) subject_location = models.CharField('subject location', max_length=64, null=True, blank=True, default=None) slideshow = FilerFolderField(null=True, blank=True) map_embed = models.TextField(null=True, blank=True) seo_title = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) seo_keywords = models.CharField(blank=True, help_text=u'Comma separated list of keywords. Max 255 characters.', max_length=255) seo_description = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("guide-destination-detail", kwargs={"slug": self.slug}) and class Tour(TimeStampedModel): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) site = models.ForeignKey(Site, db_index=True, related_name='guide_tour') active = models.BooleanField(default=False) sub_title = models.CharField(max_length=100, blank=True) duration = models.CharField(max_length=100, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to="guide/tour/") image_caption = models.TextField(null=True, blank=True) subject_location = models.CharField('subject location', max_length=64, null=True, blank=True, default=None) slideshow = FilerFolderField(null=True, blank=True, related_name='guide_tour') destinations = models.ManyToManyField(Destination, blank=True) experiences = models.ManyToManyField(Experience, blank=True) seo_title = models.CharField(blank=True, help_text=u'Max 255 characters', max_length=255) … -
Location of urls.py in Zinnia for Django
I'm trying to use the Zinnia app in Django. My question where is 'urls.py' in url(r'^weblog/', include('zinnia.urls')), I've search but can not find it. Or does it mean find all url files inside Zinnia app not just one named urls.py -
Getting No reverse Match at /techpedia/(name of my website)
While registering new users or logging in new users ,I am getting following error NoReverseMatch at /techpedia/ Reverse for 'profile' with arguments '(u'juit',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] This error is only showing up when I am trying to use bootstrap template.Without bootstrap,there is no error I went through these questions but they are of not much help.Django NoReverseMatch Django NoReverseMatch Please tell me what additional information I need to post as I don't have any idea what is causing this error. -
Django admin CSS randomly gone
I was working on the admin interface of my Django project, trying to get the right fields to show up in the right form, then on one of the reloads the CSS stopped loading, the Chrome inspector tells me the CSS files return a 404 error. I don't know what happened and can't figure it out. It's not a static files issue - the project doesn't use static files at all, and the staticfiles app has been commented out in settings.py (this is not recent, the CSS has been working for weeks without it). Debug is set to True (this also is not recent), however the project isn't served by runserver anyway. I've tried destroying and recreating the virtual machine the project is running on, which means literally everything except the project's own files is 100% fresh. Problem still persists. The question is, what can I do to get CSS working again? -
Django 1.9.13 complains SubfieldBase is deprecated, but I'm not using it. How to resolve?
I am upgrading an old Django project from Django 1.8.3 to the current Django 1.11, but to be cautious, I am upgrading to each major release of Django along the way, so I can find errors & deprecations and fix them before taking the next step. (I haven't touched this code in almost two years, so I'm a little rusty; forgive me if I'm making a simple mistake.) I first upgraded to Django 1.9.13 (the last before 1.10), and when I manage.py runserver, I get this error: /Users/mboszko/.virtualenvs/opticaldev/lib/python2.7/site-packages/django/utils/six.py:808: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. return meta(name, bases, d) If I'm reading this error right, the error stems from the custom version of six that Django embeds. I have searched my code, and I don't seem to be using SubfieldBase anywhere in my own code. (I have also googled, with not much success, for this particular error in six.) Is this just a situation where I should upgrade to Django 1.10, and the new version of six in that package will be compatible, or is there something that I need to resolve myself before I upgrade? -
Trigger to send new rows added to database to another database in postgres?
I have 2 databases on 2 different servers (say A & B). I have some crawlers that use API functions to write data to database (A). Some of this data are new and others are just updates to previous rows. If some new rows are added to (A) I want to add id of these new rows to (B). I want this to happen in real time without full scan of (A) iteratively. I want something like a trigger in (A) to send new ids to (B). How should I do write this trigger?(If you think there is a better solution, please help me) -
Django, how to display reply form for comment and what should the views.py look like
this is my first question here. I have a post_detail function in views.py to show the comment form def post_detail(request, id=None): instance = get_object_or_404(Post,id=id) form = CommentForm(request.POST or None) if form.is_valid(): c = form.save(commit=False) c.posts_id = instance.id c.save() return HttpResponseRedirect('/hello/get/%s' % id) else: form = CommentForm() context = { 'title': instance.title, "instance" : instance, "form": form, } return render(request,'post_detail.html',context) my models look like this class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=140) .... class Comment(models.Model): posts = models.ForeignKey(Post, related_name='comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.body class Meta: ordering = ['-created'] #negative class Reply(models.Model): comment = models.ForeignKey(Comment, related_name='reply') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body class Meta: ordering = ['-created'] and the html <h2>Comments</h2> <form method='POST'>{% csrf_token %} {{form|crispy}} <input type='submit' value="Post Comment"> </form> <div> <h3><p>Total comments:{{instance.comments.count}}</p></h3> {% for comment in instance.comments.all %} {{comment.body}} <p>by:{{instance.user}}-Commented on:{{comment.created}}</p> {% for reply in comment.reply.all %} <p>{{reply.body}}</p> <p>by:{{instance.user}}-Replied on:{{reply.created}}</p> {% endfor %} <br/> {% empty %} <p> There are no comments</p> {%endfor%} </div> User is able to post comment and it is working fine. Also reply is getting displayed if done through django-admin. I want the user to … -
using querydict item for if-statement
The url: myurl/?page=1&reverse Now I want to check in the template whether reverse is in there: {% if request.GET.reverse %} do somthing {% endif %} But what's in between of if and endif never happens! What should I use instead of request.GET.reverse? -
Django - working with queryset
My models currently look like this: class Dealer(models.Model): name = models.CharField(unique=True, max_length=255, default='') url = models.URLField() def __str__(self): return self.name class Category(models.Model): name = models.CharField(unique=True, max_length=255, default='') def __str__(self): return self.name class Car(models.Model): name = models.CharField(unique=False, max_length=255,default='') category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name class Price(models.Model): car = models.ForeignKey(Car, default='') dealer = models.ForeignKey(Dealer, default='') price = models.DecimalField(max_digits=9, decimal_places=2) url = models.URLField(max_length=255) def __str__(self): return str(self.price) What I want to be able to do is answer the following question (something that will ultimately become the context of my view): Show me a list of cars in a particular category that are available at different dealerships, with their prices. The query that I'm using for testing is this: carprice = Price.objects.filter(car__category='1').values('car__name','price','dealer__name').order_by('car__name') The resulting QuerySet looks something like this: <QuerySet [{'car__name': 'Audi Model A', 'price': Decimal('32000.00'), 'dealer__name': 'Dealer A'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer B'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer C'}, '...(remaining elements truncated)...']> Question 1: Can the query be modified so that the QuerySet does not repeat the car__name every time but instead groups prices and dealers by car__name? If someone could point me to a good tutorial/documentation on QuerySets, I would be really grateful. … -
Django app on Heroku, deployed successfully but could not be served
I have built a simple blog app with Django by following a video and deployed it to Heroku by following another video. The app works fine locally, but it is not working online. Heroku gives me this error message: This app has no process types yet Add a Procfile to your app in order to define its process types. I had already added a Proclife created with Notepad with these contents: web: gunicorn mysite.wsgi But how can I add another Procfile to an app already deployed to Heroku? Where should I place it? -
Django rest framework - return objects ordered by callable method result
So basically the title says it all: how can I order the queryset that will be returned on the API by a callable method result that is not stored on the database? This field is dynamic and depends on each user's request, hence it can't be stored anywhere. I tried just using, which is what I want to achieve: queryset = Post.objects.filter('my_filters').order_by('my_method') but it doesn't work since it has to be a column on the database. I also tried: queryset = sorted(Post.objects.filter('my_filters'), key=lambda x: x.my_method()) But it throws the "AttributeError: 'list' object has no attribute 'model'" error. How can I sort the results of the queryset according to a method then? Any ideas? I will also need to limit the number of responses to the top results calculated this way. Thanks! -
Showing flash messages in DJango with close button
I want to display flash messages in Django with the close button. Existing message framework in Django allows to display messages and does not allow to close it. As an example, web2py provides such flash messages. I am looking for similar functionality in Django. If it can be done with few lines of code , it would be great. I do not want to add any other libraries or framework on top of Django. Thanks in advance. -
Django subdomain configuration for third party application integration
I am building a regular django project - the difference is this: I want the django website to only "work" on a specified subdomain - for example, http://www.foo.mydomain.com I want to use an entirely different application to run on another specified subdomain - e.g. http://www.foobar.mydomain.com How do I setup a django project, so that it only runs on a specific subdomain, and does not intercept requests to other subdomains - so other other applications can run on other subdomains on the same parent domain?