Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django order_by('?') filter with distinct()
I want to retrieving unique foreign key instances and ordering randomly However, I got an error when I want to use order_by('?') my query is like this: qs=Course.objects.distinct('courseschedule__object_id').order_by('courseschedule__object_id') this query is works fine, but right now I want to order randomly(to get random result every time),I try this qs=qs.order_by('?') I got this error : django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions any idea how to fix it? my database is Postgres, I don't want do rawSQL.... I really appreciate you guys help!!!! -
How can reset django apps which migration folder was deleletd?
In my django app path, the migrations folder was deleted, but I want to recover it, when executing migrate command: python manage.py migrate --fake api.desktops CommandError: App 'api.desktops' does not have migrations (you cannot selectively sync unmigrated apps) How can reset those app? -
Django: Distinct Not Working
I have a Question Model & a Answer model. Answer is related to Question through a Foreign key. I'm trying to Print out the Questions with most recent Answers. Here's what I tried, questions = Question.objects.filter(answer__isnull=False).order_by('-answer__id').distinct() But, It's repeating the Question in case it has multiple Answers. I tried something like .distinct('id'). But it said, it must match initial order by condition. SO, I tried .distinct('answer__id', 'id') but it still repeating the same Question if it has multiple Answers. How can we fix that? Thank You :) -
AttributeError at /accounts/signup/ 'Person' object has no attribute 'META'
When I try to sign up a new user, the page returns an AttributeError, as shown here: I am using a custom model, and here is my models.py and forms.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Person(AbstractUser): pass and # -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.contrib.auth.forms import UserCreationForm from .models import Person # Create your forms here. class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Person fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) Finally, here's my views.py for the accounts app: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from .forms import SignUpForm # Create your views here. def signup(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(user) return redirect('lists:index') else: form = SignUpForm() context = { "form": form } return render(request, 'accounts/signup.html', context) def login(request): context = { } return render(request, … -
Is it possible to realize dynamical ForeignKey, or other way to achieve?
Is it possible to realize dynamical ForeignKey? I have a Task class, which is used for Server model, IP model, WorkOrder model and so on. class =Task(models.Model): """ Task for Server, IP, WorkOrder ... """ name = models.CharField(max_length=16) desc = models.CharField(max_length=1024) belong_to = models.ForeignKey(to=`There should be be `Server, IP, WorkOrder``) .... My requirement is design one Task class, then relevance to one of the models, but in Django, looks like impossibility. If this is not possible, is there other method to achieve it? Otherwise I will write the Task for each model. -
Form is not shown in detail.html
Form is not shown in detail.html. I wanna make a page which shows POST's models' detail is shown.When I access the page, search's form is not shown there.I wrote in views.py from app.forms import SearchForm def top(request): content = POST.objects.order_by('-created_at')[:5] form = SearchForm() return render(request, 'top.html',{'content':content,'form':form}) class DetailView(generic.DetailView): model = POST template_name = 'detail.html' form = SearchForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context in detail.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>DETAIL</title> </head> <body> <div class="search_box"> <form action='/app/search/' method="POST"> <table> {{ form.as_table }} </table> <button class="btn btn-secondary search" type="submit">Search</button> {% csrf_token %} </form> </div> <div class="col-xs-12 col-sm-6 text-xs-center content"> <img src="./image/{{ content.image }}"/> <h2>{{ object }}</h2> <p>{{ object.text }}</p> </div> </body> </html> In top method,I read form like 'form':form , so form is shown in the html.But DetailView class is generic view, I cannot understand how I can read form.I rewrote context['search_form'] = SearchForm() but form is not shown.What is wrong in my codes?How should I fix this? -
Django CharField None vs empty string global default standardization
It is always a pain to do this to get objects with not Null: Object.objects.filter(some_field__isnull=False).exclude(some_field='') Or this to get objects with only Null: Object.objects.filter(Q(some_field__isnull=True) | Q(some_field='')) By default it is Null, but if empty form submitted, it becomes empty string.. Is there any practice in Django to set CharField behaviour somehow uniformly by default, somehow easy and globally? To never think about this in development? Probably it is not about Django, but, anyway -
ImproperlyConfigured at /app/category/Python/
I wanna make a page which shows POST's models' contents is shown each category.For example, when I put Python link in in detail.html,only POST's models' contents with Python's category is shown in category.html.When I put Python link in category.html,I got an error,ImproperlyConfigured at /app/category/Python/ CategoryView is missing a QuerySet. Define CategoryView.model, CategoryView.queryset, or override CategoryView.get_queryset(). I wrote codes in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] category_content = Category.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,'category_content':category_content,"page":page}) class CategoryView(BaseListView): template_name = 'category.html' def get_queryset(self): category_name = self.kwargs['category'] self.category = Category.objects.get(name=category_name) queryset = super().get_queryset().filter(category=self.category) return queryset def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['category'] = self.category return context in urls.py urlpatterns = [ path('top/', views.top, name='top'), path('category/<str:category>/',views.CategoryView.as_view(), name='category'), ] in models.py class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class POST(models.Model): title = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title in top.html <div class="list-group"> <a href="#"> Category </a> <div> {% for category in category_content %} <a href="{% url 'category' category.name %}"> {{ category.name }} </a> {% endfor %} </div> </div> in category.html {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Category</title> </head> <body> <div> {% for content in queryset %} <h2>{{ content.title … -
Bootstrap 4 input-group-append not working
Using the following HTML: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../../../favicon.ico"> <title>Starter Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <!-- jQuery libraries --> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> <!-- Custom styles --> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <main role="main" class="container"> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">@</span> </div> <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Recipient's username" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append"> <span class="input-group-text" id="basic-addon2">@example.com</span> </div> </div> <label for="basic-url">Your vanity URL</label> <div … -
Django display data for current user only
I'm looking to show the data of the Performance model for the current user only. Right now the page shows all performance data, not only the data of the logged in user. I'm not sure if I have the models.py setup incorrectly (does every model need to have a foreignkey related to the user?) or if there is a solution for this in the views.py file (I tried this using get_context_data but couldn't get it to work) Any help is much appreciated! models.py class Adaccount(models.Model): accountname = models.CharField(max_length=250) def __str__(self): return self.accountname class Performance(models.Model): adaccount = models.ForeignKey(Adaccount, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) campaign = models.CharField(max_length=500) adset = models.CharField(max_length=500) clicks = models.IntegerField() impressions = models.IntegerField() ctr = models.FloatField() cpc = models.FloatField() cpm = models.FloatField() conv1 = models.IntegerField() conv2 = models.IntegerField(blank=True, null=True) conv3 = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.date) + ' - ' + str(self.adaccount) class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) adaccounts = models.ForeignKey(Adaccount,null=True) company = models.CharField(max_length=250, blank=True) website = models.CharField(max_length=30, blank=True) def __str__(self): return self.company views.py class IndexView(LoginRequiredMixin, generic.ListView): model = Performance context_object_name = 'all_performance' template_name = 'dashboard/index.html' login_url = '/login/' redirect_field_name = 'redirect_to' def get_queryset(self): return Performance.objects.all() class HomeView(TemplateView): model = Adaccount template_name = 'dashboard/home.html' HTML Template <strong>CTR | CPC … -
How do I get all rows of MultiPolygons within four points of a rectangle?
I have a PostGIS table named table with a MultiPolygon column geom. I've integrated this table into Django, where it's model name is MyTable. I want to use Django to fetch all objects in MyTable within the following coordinates: -97.82381347656252, 30.250444940663296, -97.65901855468752, 30.29595835209862. I tried running this code in a Python shell: >>> from django.contrib.gis.geos import Polygon, MultiPolygon >>> theme.models.MyTable.objects.filter(geom__inside=Polygon.from_bbox((-97.82381347656252, 30.250444940663296, -97.65901855468752, 30.29595835209862))) But I got this error: FieldError: Unsupported lookup 'inside' for MultiPolygonField or join on the field not permitted.. When I tried changing "Polygon" to "MultiPolygon" I got this error: 'AttributeError: type object 'MultiPolygon' has no attribute 'from_bbox'. I want to replicate the following PostGIS SQL query that fetches the rows within the specified bounds: SELECT * FROM myTable WHERE ST_MakeEnvelope(-97.82381347656252, 30.250444940663296, -97.65901855468752, 30.29595835209862, 4326) && ST_Transform(myTable.geom,4326); What Django code must I run? -
Django-Channels and requesting data from external API. Support for multiple users
A part of the application that I have been working on has 'live' Twitter wall. This Twitter wall is unique per user. It provides them with an ability to pull the Tweets containing a specified phrase. Once the user is no longer interested in 'watching' the data it is being wiped out. The Scenario: User comes to the search page and he is connected to a socket that is waiting for his input. A user inputs the phrase that he is interested in and he presses the 'search button' consumer.py inside the receive method tries to provide the request. It received the data from the input and now I need to create a (not sure here) a process/task/loop [?!] that will call the API and return the data. As long as the user is on the page the page data will be pulled and presented to the user. If the user exits the page o call disconnect function and stops the process/thread/loop. I have tried different approaches with Loop, Threads (probably wrong idea) to handle that but I had no luck. The biggest problem is that when I exit the page the process is still running even though I am … -
Template does not exist. Django looking for wrong path
im following a django tutorial but have had this error coming up for a while now. i've had the course code up next to mine to comepare it to try to find the bug but i haven't had any luck with it TemplateDoesNotExist at /posts/new/ posts/post_form.html Request Method: GET Request URL: http://127.0.0.1:8000/posts/new/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: posts/post_form.html Exception Location: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/template/loader.py in select_template, line 53 Python Executable: /Users/chrismaltez/anaconda3/envs/simplesocialenv/bin/python Python Version: 3.5.0 Python Path: ['/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python35.zip', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/plat-darwin', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/lib-dynload', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages'] Here is the postmortem traceback: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/admin/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/auth/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/bootstrap3/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/accounts/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/groups/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/posts/templates/posts/post_form.html (Source does not exist) This is the last line of the traceback: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) From what I can tell, it might not be looking in the right place -simple_social_clone --simplesocial ---posts ----templates -----posts ------post_form.html from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.HomePage.as_view(), name='home'), url(r'^accounts/', … -
openshift 3 django - request too large
I migrated a django app from Openshift 2 to Openshift3 Online. It has an upload feature that allows users to upload audio files. The files are usually larger than 50MB. In Openshift3 if I try to upload the file it only works for files up to around 12 MB. Larger than 12 MB leads to an error message in the firefox saying "connection canceled". Chromium gives more details: Request Entity Too Large The requested resource /myApp/upload does not allow request data with POST requests, or the amount of data provided in the request exceeds the capacity limit. I'm using wsgi_mod-express. From searching on this error message on google, I could see that it I'm probably hitting any limit in the webserver configuration. Which limit could that be and how would I be able to change it? -
BITGO - Can't Get Hash on Request
What is the key to call from BitGo API to get from a webhook immediately an address receive BTC. From my ngrok, I saw this { "hash": "26ba9cc3218962417f529803d82dd63850b895fbee74517dff", "type": "transaction", "coin": "bitcoin", "walletId": "2Mzb4KMAp" } So when I did the following in the 'hook callback url', I'm getting error. 500 Error. 1. txId = request.POST.get('hash') 2. txId = request.GET['hash'] 3. txId = request.POST['hash'] How do I get the hash since all the above method failed. I'm using Python/Django. -
Copy/clone Django Model
I am trying to make a copy of this model class Quiz(models.Model): title = models.CharField( verbose_name=_("Title"), max_length=60, blank=False) description = models.TextField( verbose_name=_("Description"), blank=True, help_text=_("a description of the quiz")) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category")) random_order = models.BooleanField( blank=False, default=False, verbose_name=_("Random Order"), help_text=_("Display the questions in " "a random order or as they " "are set?")) max_questions = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Max Questions"), help_text=_("Number of questions to be answered on each attempt.")) answers_at_end = models.BooleanField( blank=False, default=False, help_text=_("Correct answer is NOT shown after question." " Answers displayed at the end."), verbose_name=_("Answers at end")) exam_paper = models.BooleanField( blank=False, default=False, help_text=_("If yes, the result of each" " attempt by a user will be" " stored. Necessary for marking."), verbose_name=_("Exam Paper")) single_attempt = models.BooleanField( blank=False, default=False, help_text=_("If yes, only one attempt by" " a user will be permitted." " Non users cannot sit this exam."), verbose_name=_("Single Attempt")) pass_mark = models.SmallIntegerField( blank=True, default=0, verbose_name=_("Pass Mark"), help_text=_("Percentage required to pass exam."), validators=[MaxValueValidator(100)]) success_text = models.TextField( blank=True, help_text=_("Displayed if user passes."), verbose_name=_("Success Text")) fail_text = models.TextField( verbose_name=_("Fail Text"), blank=True, help_text=_("Displayed if user fails.")) draft = models.BooleanField( blank=True, default=False, verbose_name=_("Draft"), help_text=_("If yes, the quiz is … -
Using django form wizard loop through a form to save multiple of that type
I was wondering anyone came across this before or know what is best way to tackle the issue. I am using Django and the form wizard. I have a registration process that goes in a linear path but I want to make it more dynamic by allowing the user to register multiple of the same object with different information by looping through step 2 and 3 to create multiple of these objects to be stored into the database under one person. Any help would be appreciated -
Return updated session variables (while page is loading) through Ajax call using Django
What I'm trying to do and accomplishing now: A user comes to my Django web page to submit a simple form with a couple of input fields that kicks off a complex background process in my background_process view function. I am trying to use session variables so that I can handle multiple users without variables overwriting each other during background processing. Ajax runs during the background processing calling my other view function callback_progress. callback_progress is updating JSON with variables that are returned to my javascript/jquery ajax through return JsonResponse(data): def callback_progress(request): request.session["data"]['numgames'] = request.session["numgames"] request.session["data"]['progress'] = request.session["progress"] request.session["data"]['win_ratio'] = request.session["win_ratio"] response = JsonResponse(request.session["data"]) return response I can successfully return a JsonResponse from my Ajax call. Here is what my Ajax looks like and what console.log(data) looks like: Ajax (simplified a little for readability, I'm updating some html elements in the success block that I removed) $("#myButton").click(function result_poll() { function ajax_call() { $.ajax({ headers: {'X-CSRFToken': csrftoken}, type : "POST", url : "/callback_progress/", data: "{{ data }}", success: function(data) { console.log(data); if (data["progress"] == data["numgames"] && data["progress"] != "0") { clearInterval(interval_id); } }, error: function() { console.log("something went wrong"); } }); }; var interval_id = setInterval(ajax_call, 2000); }); Console.log output {numgames: "0", … -
Dango - cant find my static files even after manually correcting the path
I've encountered a problem that, even after an evening of trying , I've not yet been able to resolve. For my project I have a single static directory, and I've included the css files for the 'login' page in there. Yet when I try to load the webpage I get a 404 error. When I try to find the files with the 'findstatic' or 'collectstatic' commands the files get skiped. Its like the 'static' directory is invisible to django. I've even directly copies the 'Login' folder to 'static_root', but even then the program was Django was unable to find the files. Does anyone have an idea what I am doing wrong? My project folder looks like this: * MPS (main folder) * Scraper (app) * Database (app) * Templates * Static_root * Static * Login * css * style.css My settings.py has been configured like so: STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/') And I call the static files in the template with the following code: {% load staticfiles %} (...) <link rel="stylesheet" href="{% static 'login/css/style.css' %}"> -
re.match output not deterministic [on hold]
I am doing a rather complex match with python using re.match, which takes the form of (some_pattern_1)?(some_pattern_2)?..(.*) On the other side of it I have a unit test with about one hundred examples I am checking, which are all sending request asynchronously to my (local, development) server. The server is in django. I am sometime seing the match apparently be non-greedy (i.e. too many things end up in the last catch all block) and the unit test fail, but can't really reproduce it in isolation, and I don't really have an idea what's going on. Are there know conditions where this could happen (and am I correct to assume that the regex match is guaranteed to be fully deterministic in principle?) ? -
Django with a list of primary key in detail view
In my program, the index page shows a list of products in a table with a checkbox in each rows, and a dropdown list of the price level (for example: Retail, Distributor) When the user selects the price level and multiple products by checking the checkboxes, they click process and the program with run a query based on the selected items and selected price levels So, it has 2 views: index view which lists everything and detail view which just lists whatever selected. The index view is the view that has the POST button and is where I capture the selected price level and selected items. These parameters will be passed over the detail view using the return redirect. The problem I have is the URLConfig url.py In the detail views, there are 2 parameters passing in: the selected price level and selected items. With the selected price level, I have no issue capturing it as it's a single value: either Retail or Distributor. The selected items is the problem: I don't know how to pass an array of selected items in the URL Config. The path should be like this /detail/Retail/{product A, product B, product C} Here is what … -
What type of instance can django.conf.urls.url() be counted as?
While reading the official Django documentation, specifically the chapter 'URL dispatcher' about how Django processes requests, I stumbled upon something which made me uncertain. The docs stated that the variable 'urlpatterns' is a list containing django.conf.urls.url() instances. This made me wonder, is django.conf.urls.url(), or url() as commonly written within the framework, a function or a class? I have understood that everything in Python can be considered a class, however is it syntactically speaking a function or a class? My first instinct was to research the django.conf.urls.url(), url(), within the Django documentation, but I was unable to find much to read. This same question has now become relevant for me regarding other functions/classes that Django provides. How can you be sure whether or not foo() is a function or a class? From my understanding, these are definitely functions, but I am having a hard time expressing why. Thank you in advance. -
Wagtail moving sqlite to postgres database
The issue I have an empty (migrated) postgres database to which I want to move the data from my sqlite database. What I've tried I export with ./manage.py dumpdata --exclude auth.permission --exclude contenttypes and consequtively load the data into the postgres db with ./manage.py loaddata. The problem here is that wagtail requires the contenttypes and I get a runtime error FooPage matching query does not exist. at /wagtail/wagtailcore/models.py:639 return content_type.get_object_for_this_type(id=self.id) Don't exclude contenttypes with dumpdata. Now the loaddata command fails with an IntegrityError: Key ... already exists. I have tried to remove all ContentType model objects before loading in the data so that it doesn't whine about duplicate keys. While that works when using the sqlite db, it fails on the postgres db with an IntegrityError Key (id)=(1) is still referenced from table "wagtailcore_page". Used versions django 1.11.9 wagtail 1.12.3 python 3.5 Related Problems with contenttypes when loading a fixture in Django -
No Module Name django right after installing
I'm trying to install django in a virtual environment on my Windows machine (I have python 3.6.4). I create the virtual environment and install django and get the success message. But when I try to see my django installation, I get the error below: I'm seeing several similar questions on Stackoverflow like this or this but they are either on a different OS or have used a different means of installation and I've tried some of the suggestions with no luck. Does anyone know what is causing this and how to resolve? -
how to make custom view in django template
I have to display currency values in a table and have problems seting it up. The currency values are stored against CHF (swissfrancs) in the db as exchange_rate_to_chf. This is my models.py: from django.db import models from decimal import Decimal import datetime class ExchangeRate_name(models.Model): name = models.CharField(max_length=200, unique=True) def __str__(self): return self.name class ExchangeRate_date(models.Model): date = models.DateField('%Y-%m-%d', unique_for_date=True) def __str__(self): return str(self.date) class ExchangeRate(models.Model): name = models.ForeignKey(ExchangeRate_name) date = models.ForeignKey(ExchangeRate_date) exchange_rate_to_chf = models.DecimalField(max_digits=12, decimal_places=5) def __str__(self): return str(self.name) I whant to get a template that shows currency ExchangeRates in a Table as one line per date. some like this: DATE | USD | EUR | JPY | GBP ------------------------------------------ 2018-01-01 | 0.9 | 1.15 | 115.2 | 0.7 2018-01-02 | 0.9 | 1.14 | 115.3 | 0.76 I easealy made a list out of the model with view.py currency_list = ExchangeRate.objects.all() return render(request, 'currencies/index.html', {'currency_list': currency_list} And a template index.html <!DOCTYPE html> <head> </head> <body> <div> <h1>Currencies in CHF</h1> <ul> {% for currency in currency_list %} <li> {{ currency.date.date }} : {{ currency.name.name }} : {{ currency.exchange_rate_to_chf }} </li> {% endfor %} </ul> </div> </body> </html> But im realy strugling to make a customized view because the date key is …