Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirecting user values from one template to another - Django
Trying to redirect the values given by the user from one page to the next. Everything can be done in one view, but when I try to redirect to the next one using HttpResponseRedirect Django return error 'NameError at /search_results, name '' is not defined'. How to pass the 'text' value from one view to another (to my search results) My views.py (Works well, the values given by the user in one field, return the corresponding results of the cure from django-filters) def test_views(request): form = MeanForm(request.POST) if form.is_valid(): text = form.cleaned_data['name'] else: text = None search_users = SearchWoman(request.GET, queryset=Woman.objects.all().filter(city=text)) context = { 'form': form, 'text': text, 'filter': search_users } return render(request, 'test.html', context) My test.html <h1>TEST_1</h1> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Submit</button> </form> <h2> {{ text }} </h2> <h1><br></br></h1> {% for profile in filter.qs %} <li>{{ profile.name }} </li> {% endfor %} My filters.py from .models import Woman import django_filters class SearchWoman(django_filters.FilterSet): class Meta: model = Woman fields = ['city', 'rating'] My forms.py from django import forms from .models import Mean class MeanForm(forms.ModelForm): class Meta: model = Mean fields = ('name',) How I try to do a redirect (it returns error … -
NoReverseMatch at /twitterprojects/datasets/
I have the next url.py: from django.urls import path from . import views from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from two_factor.urls import urlpatterns as tf_urls urlpatterns = [ path('', views.index, name='index'), url(r'', include(tf_urls)), url(r'datasets/$', login_required(views.mostrar_Model_Dataset), name="mostrar_Model_Dataset"), url(r'datasets/(\d+)/$', login_required(views.mostrar_Model_Dataset), name="mostrar_Model_Dataset_i"), ] And this view: def mostrar_Model_Dataset(request, Model_Dataset_id=None): conjuntos_datos = Model_Dataset.objects.all() ... context = {"conjuntos_datos": conjuntos_datos, "Dataset_id": Dataset_id, "datos": paginated_data, "fixed_pager": page_range,} return render(request, 'datasets.html', context) If I try to access to http://localhost/twitterprojects/datasets/1 or http://localhost/twitterprojects/datasets/20 or http://localhost/twitterprojects/datasets/256 this work fine, but when I try to access to http://localhost/twitterprojects/datasets/ (without argument) I receive the next message: Exception Type: NoReverseMatch Exception Value: Reverse for 'mostrar_Model_Dataset' with arguments '(1,)' not found. 1 pattern(s) tried: ['twitterprojects\/datasets/$'] some idea? -
Rendering Static file in Wkhtmltopdf in Django
I have followed too many answers to this but I need some more explanation on this topic as I want to know the root cause for it. I am trying to create pdf using wkhtmltopdf. This is my setting files look like : Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) And the URL to reference static file is : <link rel="stylesheet" href="/static/css/template_pdf.css" type="text/css" /> or <link rel="stylesheet" href="file:///static/css/template_pdf.css" type="text/css" /> or I used this too: https://gist.github.com/renyi/f02b4322590e9288ac679545df4748d3 and provided url as : <link rel='stylesheet' type='text/css' href='{{ STATIC_URL }}static/css/template_pdf.css' /> But the issue I understood is, all of the above except last one works perfectly while rendering view : def view_pdf(request): """View function for home page of site.""" context= {'title': 'Hello World!'} # Render the HTML template index.html with the data in the context variable return render(request, 'pdf/quotation.html', context=context) But for creating pdf using wkhtmltopdf it specifically needs the url to be specified like : <link rel="stylesheet" href="http:localhost:8000/static/css/template_pdf.css" type="text/css" /> I know I am missing something in the static file. But I want to know why it works with rendering template but not with Generating pdf using wkhtmltopdf. I dont think it is good idea to put directly domain … -
How represent pyhton file code in django?
I am working on Django and already open a project according to guide from their site. Now I have the project and when I start it on anaconda prompt I can see it on localhost:8000. it shows me the content of template of HTML page name it works. I want to try the opportunity of sending mail in Gmail in python. I want to make HTML file that has a button that if it clicked email will send. I have the code to send mail but I'm not sure how to connect HTML page to python file and how do I represent it in the localhost. Thanks -
Passing JSONified object to back-end in Django?
Im trying to turn an Object created in js into JSON and then passed to my back-end in Django. First I make a list of lists: function get_account_info(){ var account_list = []; $('.card').each(function(e){ var account = []; account.push($(this).find('.name').val()); account.push($(this).find('.username').val()); account.push($(this).find('.password').val()); if(account[0] != null){ account_list.push(account); } }) return account_list; } Then I try to post it: var account_info_json = JSON.parse(get_account_info()); $.ajax({ type:'POST', url:'/create_new_group/create_group/', data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), account_info: account_info_json, } , success:function(data){ if(data.status == 1){ //success! console.log('Success!') } else if(data.status == 2){ //failed console.log('Failed!') } } And this is what I get when I print(json.dumps(request.POST)) in my views.py {"csrfmiddlewaretoken": "token_data_is_here", "account_info": "[[\"1111111\",\"1111111\",\"1111111\"],[\"222222\",\"222222\",\"222222\"]]"} I can only acces this data like a stirng, not JSON. How can I make it so I access it like JSON? -
DjangoBackendFilter and filtering by id
I have a very simple filter made using DjangoBackendFilter and Ordering filter. It works with all the query parameters such as ?part_number=12345 but when it comes to the id field it does not work at all, i.e. ?id=12345. I don't have any list filters yet so I do not expect multiple filter values to work. But I do expect every field to work for single value input. Seems strange that only the id field does not work. I have also tried using ?pk=12345 in the API URL but it does not filter anything either. views.py class PartList(generics.ListAPIView): queryset = Part.objects.all() serializer_class = PartSerializer pagination_class = StandardResultsSetPagination filter_fields = '__all__' ordering = 'id' pagers.py class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 1000 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) serializers.py class PartSerializer(serializers.ModelSerializer): class Meta: model = Part fields = '__all__' -
django navbar how I do pass the product pk to each different link
This is a question about how to pass a Product model pk to a navbar where the call can originate from different pages / views, ie not always from the product details page. I'm using a base template for my navbar and then I have an html page and a view for each link in the navbar like this: Product Details - product_form.html - views.ProductUpdateView.as_view() Colours - productcolours_list.html - views.ProductColourListView.as_view() my nav bar The idea of the navbar is that once I'm looking at Product A for example, I can click through between the product details page, the product colours, and then the bill of materials. This is what the navbar code looks like: <li class="nav-item"> <a class="nav-link" href="{% url 'ProductUpdateView' pk=product.pk %}">Product Details</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'ProductColourListView' pk=product.pk %}">Colours</a> </li> The problem is that this works only when I'm on the Product Details page because the base template can interpret what product.pk is. But as soon as I click to go to the Colours link in the navbar, it tries to render the base template and all of the sudden it has no idea what product.pk is. This is because the Product Details page uses … -
Putting username of logged in user as label in django form field
I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context. But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label. Need help guys. My code goes here .... views.py from django.shortcuts import render , redirect , get_object_or_404 from .models import Article , members from django.views.generic import ListView , DetailView , TemplateView from .forms import create_form from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User class article_view(ListView): model = Article template_name = "article.html" context_object_name = "articles" @login_required def post_creator(request): form = create_form() if request.method == "POST": form = create_form(request.POST) if form.is_valid(): form.save() return redirect("/blog/home/") else: form = create_form() return render(request , "post_create.html" , {"form":form}) def registration(request): if request.method == "POST": form = members(request.POST) if form.is_valid(): form.save() return redirect("/blog/home/") else: form = members() return render(request , … -
Django SlugField "This field is required" error
In my django project there's a Blog model which I'm willing to create a slug for it's title: class Blog(models.Model): title = models.CharField(default='', max_length=100, verbose_name=u'عنوان') slug = models.SlugField(max_length=100, allow_unicode=True) # other stuffs def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) super(Blog, self).save(*args, **kwargs) def __str__(self): return self.slug In django admin I don't fill slug field and when I hit the save button it says: This field is required. Isn't my code suppose to create slug automatically? Is there something else I should do? -
NoReverseMatch at /polls/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/<int:pk>/']
Attempting to start the server and getting error line like """NoReverseMatch at /polls/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls//']"""" my views.py class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' Views for index,results and detail my urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url('', views.IndexView.as_view(), name='index'), url(r'^<int:pk>/', views.DetailView.as_view(),name='detail'), url(r'^<int:pk>/results/', views.ResultsView.as_view(), name='results'), url(r'^<int:question_id>/vote/', views.vote, name='vote'), ] my index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} I have tried many time but i didn't got a solution please help me out. -
Django not serving static files in deployment server
I know this has been discussed before but nothing worked for me, I deployed my first Django app yesterday with Nginx and gunicorn but sadly it is not serving the static files. I have gone through every answer to the same problem but I couldn't find the way out. Probably I am doing something wrong. I am on django 2.1 all my static files are under project/static Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I haven't mentioned any static dir because all the files are in static only. urls.py ( is it necessary in deployment? ) static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) nginx.confg location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /root/project/projectname/static; } my project is in root/project I don't know if it is a good practice or not I am quite a novice in this. -
KeyError ("socketio" not in request environment)
I am using django-socketio to add realtime feature to django, but i end up with a KeyError ("socketio" not in request environment), anyone who knows a way to do it please assist. -
Why do people use translation placeholders instead of plain English?
Yes, this is the exact opposite question than: Why do people use plain english as translation placeholders? I used the standard gettext way for translation all the time but now that I'm doing frontend I realized that not only most libraries are using keys/placeholders but this is sometimes recommended (see i18next) over using plain English. I haven't work much with placeholders but I find it difficult because: you have to invent unique placeholder names all the time, you need conventions maybe you want to reuse the same placeholder name so you have to find an existing one that matches what you are translating is it better to have all translations scoped per module or to have shared translations? I'm not sure According to the doc of i18-next, it is recommended to use placeholders because: While this works and might reduce files to load it makes the management of translations a lot harder as you will need to update changes to fallback values in code and json files. I wouldn't use plain English to reduce the number of files to be loaded. This seems obviously wrong. JSON? What's wrong with PO/POT? There are so many tools for translators already. If a … -
django rest framework list update api view
I am trying to add update options to the list items. So that if anyone perform 'PATCH' request to it I will get the details and update them. This is my code for the implementation class SwitchListView(UpdateModelMixin, ListAPIView): serializer_class = serializers.SwitchSerializer lookup_field = 'home_id' def get_queryset(self): home_id = self.kwargs.get('home_id', None) if home_id is None or int(home_id) < 0 or \ self.request.user.pk != models.Home.objects.filter(pk=home_id)[0].user.pk: return models.Switch.objects.none() query = models.Switch.objects.filter(home=models.Home.objects.filter(pk=home_id)) return query def get(self, request, *args, **kwargs): return super(SwitchListView, self).get(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): print("Came here") data = request.data['data'] for i in data: query = self.get_queryset().filter(i['pk']) if query.exists(): query.switch_status = i['switch_status'] query.save() return Response({'message': 'successfully updated switch!'}) But here the request to the api is only accepting GET, HEAD and OPTIONS. I even tried adding http_method_names = ('get', 'patch') but even this is not working!! Is there any way to put the patch request to the view ? Thanks -
Creating Json from list of lists
I have a dynamic amount of user into to pass to the backend of my Django project. I create a list of [account,username,password]. I then try to pass that too my backend through an ajax post. I can't seem to figure out how to do it correctly. Here is my list of [account,username,password] creation code: function get_all_usernames_and_password(){ var account_list = []; $('.card').each(function(e){ var account = []; account.push($(this).find('.name').val()); account.push($(this).find('.username').val()); account.push($(this).find('.password').val()); if(account[0] != null){ account_list.push(account); } }) return account_list; } Then I try to make a post list so: $('#submit').on("click",function(e){ var ready_to_submit = true; if(!tag_count_check()){ ready_to_submit = false; } if(!agreed_to_terms()){ ready_to_submit = false; } if(ready_to_submit){ e.preventDefault(); var account_info_json = JSON.stringify(get_all_usernames_and_password()); $.ajax({ type:'POST', url:'/create_new_group/create_group/', data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), account_info: account_info_json, } , success:function(data){ if(data.status == 1){ //success! console.log('Success!') } else if(data.status == 2){ //failed console.log('Failed!') } } }); } }); The backend then prints(json.dumps(request.POST)) and this is what I get: {"csrfmiddlewaretoken": "11vuGHM52Fyag8qBrv6nJdCRR92uCLPuwP7M8qE1vLeaA5gVVOSCc2G0tE3MZsiD", "account_info": "[[\"1111\",\"1111\",\"11111\"],[\"2222\",\"2222\",\"2222\"]]"} It wont let me access it like a json object. What am I doing wrong? -
How can I list data from a model form in django,
I'm new to Django, and have hit a road block. How would you list data in a template that is connected to a model ( Product ), then attach a form (OrderForm) too each item, rendered out as a single view? I'd like to have the product_name, along with the par_amount displayed, and send a POST too order_amount. Can I do it with a listview and run a forloop in the template? If so how would you make one submit button process all froms? Again i'm new, Thank you in advance. model.py class Product(models.Model): product_name = models.CharField(max_length=100) par_amount = models.IntegerField() def __str__(self): return self.product_name class Order(models.Model): product_name = models.ForeignKey('Product', on_delete=models.CASCADE) order_amount = models.IntegerField() forms.py class OrderForm(ModelForm): class Meta: model = Order fields = ['product_name', 'order_amount', ] views.py class OrderFormView(FormView): form_class = OrderForm template_name = 'items/order_form.html' def from_valid(self,form): return super().form_valid(form) -
google youtube api on Django
I'm working on a website to get videos via key words using google api on Django. The function for calling api works well individually, but once I called the function in view.py and run the server, it returns server error. why? def youtube_search(options): DEVELOPER_KEY = "AIzaSyBQG9ozouzPofCHE4J-BHdUeSjqqtemnc0" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) parser = argparse.ArgumentParser() parser.add_argument("--q", help="Search term", default=options) parser.add_argument("--max-results", help="Max results", default=1) # the number of default is the number of output videos options= parser.parse_args() search_response = youtube.search().list( q=options.q, part="id,snippet", maxResults=options.max_results ).execute() videos = [] videoid = [] channels = [] playlists = [] result = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append( search_result["snippet"]["title"]) videoid.append( search_result["id"]["videoId"]) for line in videos: result.append(line) for line1 in videoid: line1 = "http://www.youtube.com/watch?v="+line1 result.append(line1) return result and here are the view.py calling the function: def index2(request): if request.method == "POST": search=request.POST.get("search:",None) class1 = predict.predict(search) #list =[search, 'other corresponding tags'] api = YTapi.youtube_search(search) video = api[0] videoid = api[1] return render(request, "index2.html",{"video":video,"videoid":videoid}) -
PGPool II + Django w/ psycopg2 load balancing
I've a pool of applications running django 1.6 with psycopg2 on top of a PGPool II with two backends PostgreSQL servers. But all queries (read and/or write) are going to master PostgreSQL even SELECT. As we can see on PGPool II documentation, if we have read queries into transactions we need to hit some conditions to load balancing os send to master. I know that we have some points of the code that we have SELECT into a transaction but we also have simple SELECT queries which is going to master too. I'm not sure if, and what, conditions we are hitting to send all queries to master. Here the table with conditions for load balancing: -
Unable to login to admin page in Heroku production postgres
This app works locally with sqlite. When I push it to production with Heroku, I'm not about to login to the admin page. This is the error I'm getting from debug: ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... I think I added the correct DATABASE connection string in settings.py (commented out) but that produced the same error. I've run python manage.py makemigrations and migrate. Migrate gave the same error. I found related issues on stack and GitHub but none of them worked. Most of them just said to migrate. Any idea what might be causing the error? TIA log (last bit) 2018-11-10T02:04:25.402553+00:00 app[web.1]: django.db.utils.ProgrammingError: relation "auth_user" does not exist 2018-11-10T02:04:25.402555+00:00 app[web.1]: LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... 2018-11-10T02:04:25.402556+00:00 app[web.1]: ^ 2018-11-10T02:04:25.402557+00:00 app[web.1]: 2018-11-10T02:04:25.403555+00:00 app[web.1]: 10.99.134.157 - - [10/Nov/2018:02:04:25 +0000] "POST /admin/login/?next=/admin/ HTTP/1.1" 500 212013 settings.py import os import warnings from django.utils.translation import ugettext_lazy as _ from os.path import dirname import django_heroku import dj_database_url BASE_DIR = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) CONTENT_DIR = os.path.join(BASE_DIR, 'content') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Vendor apps 'bootstrap4', # Application apps 'main', 'accounts', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF … -
Django GET request download from Dropbox
class FileDropboxDownloadView(LoginRequiredMixin, View): login_url = global_login_url def get(self, request, pk): # return self.head(self) # use the path to find the filename db_query_file = self.request.path # remove the trailing slash db_query_file = db_query_file[:-1] # regular expressions to remove the beginning db_query_file = re.sub('^(/)[\w]+(/)[\w]+', '', db_query_file) dbx = dropbox.Dropbox(dropbox_token) return dbx.files_download(db_query_file, rev=None) When I try this it only gives me the meta-data of the file, not the file itself. Is there a way to make it return the file? Thanks! -
I want to read data from text file and save it to database in Django
I am new to Django and Python. I want to read data from text file and save it to database. Input file example: E Alan Marshall 121 55.26 E Bob Marley 122 66.78 M Ted Smith 123 Marketing 76.78 M Ron Barly 124 Production 86.78 I have described models as follows: class Employee(models.Model): first = models.CharField(max_length=20) last = models.CharField(max_length=20) id = models.IntegerField() pay = models.DecimalField(max_digits=12, decimal_places=2) class Manager(models.Model): first = models.CharField(max_length=20) last = models.CharField(max_length=20) department = models.CharField(max_length=20) id = models.IntegerField() pay = models.DecimalField(max_digits=12, decimal_places=2) I receive data in the form of a text file and I read the data by parsing the string. The first character tells me the type of class data to expect (e.g. E means Employee class object data, M means manager class object data) Once we know the type of data, the sequence in which the variables occur are fixed. Means if I tokenize string with 'space' as delimiter, for Employee class, first element is first Name, next is last name, next is employee id, next is pay I want to write code in python which will parse the input file and will create objects of the respective class. I should maintain the type of class … -
how to find if string is in a result of a query set in Django
I have the following object result from query set on a model as follow : ddd = Post_Sub_Category.objects.filter(category_name__category_name__iexact=dd).values_list('sub_category_name', flat=True) the query set I obtained: <QuerySet ['car', 'spare parts', 'truck', 'motor cycle']> then tried: print(ddd.values('sub_category_name')) I obtained the following result: <QuerySet [<Post_Sub_Category: car>, <Post_Sub_Category: spare parts>, <Post_Sub_Category: truck>, <Post_Sub_Category: motor cycle>] How to access the values only and make list of them as string : ['car','spare parts','truck','motor cycle']. the first query set seems that it gave me what I want. However, When I use following if statement. it does not executed: if 'car' in ddd: # do some thing as you can see 'car' should be in the list. so, I could not understand why the if statement has not been executed. any help or suggestion? -
Using model method in form validation
I have a ModelForm and I want to use my Model method for form validation process, I have tried form.save(commit=False) but it return a None object. The period model have two attributes which are start and end time fields. models.py class Booking(models.Model): CATEGORY_CHOICES = ( ('Web', 'Web Application'), ('Emb', 'Embedded Application') ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookings') room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='bookings') category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, default='Web') date = models.DateField('Booking Date', db_index=True) start = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='start_at', null=True) end = models.ForeignKey(Period, on_delete=models.SET_NULL, related_name='end_at', null=True) used = models.BooleanField(default=False) objects = BookingManager() class Meta: ordering = ['-date'] def get_start_time(self): return datetime.datetime.combine(self.date, self.start.start, tzinfo=timezone.get_current_timezone()) def get_end_time(self): return datetime.datetime.combine(self.date, self.end.end, tzinfo=timezone.get_current_timezone()) def is_occurring(self): now = timezone.localtime(timezone.now()) return (now >= self.get_start_time()) and (now <= self.get_end_time()) def extend_booking_time(self): next_end = self.end.next_period() if next_end is None: raise ValidationError("Invalid extending period") if not next_end.is_available(self.date, next_end): raise ValidationError("Overlapped extension") else: self.end = next_end self.save() def check_in(self): # Create record ''' Log.objects.create(user=self.user.username, room=self.room, booking= self.id) ''' self.used = True self.save() def check_out(self, time): # Record Log #log = Log.objects.get(booking=self.id) #log.check_out = time #log.save() self.delete() def check_periods(self): return self.start.start < self.end.end def check_time(self): now = timezone.localtime(timezone.now()) if now >= self.get_end_time(): return False else: return True def check_overlap(self): start = self.get_start_time() end … -
Having trouble URL mapping using Django for Python
I am having a trouble mapping urls correctly. I've included my code below. I am able to run the code just fine, but when I click the "about" hyperlink, I get an error saying The current URL, rango/about/, didn't match any of these. When I put in the URL just "rango/", removing the "about", I get the following error: The current URL, rango/, didn't match any of these. I am a complete beginner with Django and have been going through the Tango with Django book, but currently stuck with the exercises on Ch3. Any help is much appreciated. Thank you! tango_with_django_project.urls.py from django.conf.urls import url from django.contrib import admin from django.conf.urls import include from rango import views, urls urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^rango/',include('rango.urls')), # above maps any URLs starting with rango/ to # be handled by the rango application url(r'^admin/', admin.site.urls), ] rango.urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^rango/', views.index, name='index'), url(r'$^rango/about/',views.about,name='about'), ] rango.views.py from django.http import HttpResponse def index(request): return HttpResponse("Rango says hey there partner! \ <br/> <a href='/rango/about/'>about</a>") def about(request): return HttpResponse("Rango says here is the about page. \ <br/> <a href='/rango/'>index</a>") -
Is there ever any difference between using just a `foreign_key=` vs `foreign_key_id=` in Django's ORM?
There does not appear to be a difference between the following: ModelA.objects.filter(modelb_id=a_model_id) ModelA.objects.filter(modelb=a_model_id) Printing out the SQL that Django generates for both cases shows that it is the same. However, I haven't been able to find this officially documented anywhere, and I'm therefore concerned that there may be some case where using just modelb might result in something different from modelb_id. I'm especially interested in someone pointing me to an official source that confirms these things are equivalent.