Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
name 'context' is not defined
I try to use a view to create a table (which I later want to populate with data). But if I open the respective url the view creates a "name 'context' is not defined" error. Can anybody explain? def room_overview(request, year, month): rooms = Room.objects.all() long_month = ['01', '03', '05', '07', '08', '10', '12'] short_month = ['04','06','09','11'] if month in long_month: month_max = 31 elif month in short_month: month_max = 30 elif year % 4 == 0 and year %100 != 0 or year % 400 == 0: month_max = 29 else: month_max = 28 days = [] for i in range(1, month_max + 1): days.append(str(i)) context['rooms'] = rooms context['days'] = days context['month'] = month context['year'] = year return render(request, 'hotel/overview.html', context) the template for the view looks like this: <h2>Overview {{month}}/{{year}}:</h2> <div class="overview"> <table class="table table-condensed"> <tr> {% for day in days %} <th>day</th> {% endfor %} </tr> {% for room in rooms %} <tr> <td>{{ room.name }}</td> {% for day in days %} <td> 1 </td> {% endfor %} </tr> {% endfor %} </table> </div> this is the url entry: url(r'^room/overview/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',views.room_overview, name='room_overview'), -
OrderingFilter has no attribute 'filter_queryset'
I have been trying to get OrderingFilter to work. From the example in django-rest-framework's page, it seems it should be fairly straightforward: class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.OrderingFilter,) ordering_fields = ('username', 'email') However, when I try to do that, I get: from django_filters.rest_framework import DjangoFilterBackend, FilterSet, OrderingFilter ... class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all() serializer_class = ListingSerializer filter_backends = (DjangoFilterBackend, OrderingFilter,) filter_class = ListFilter ordering_fields = ('price', 'views') ordering = ('price',) I get an error about OrderingFilter not having a filter_queryset attribute: ERROR 2016-11-13 03:14:57,304 log 25913 123145338523648 (<class 'AttributeError'>, AttributeError("'OrderingFilter' object has no attribute 'filter_queryset'",), <traceback object at 0x106ef48c8>) Traceback (most recent call last): File "/.../lib/python3.5/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/.../lib/python3.5/site-packages/rest_framework/mixins.py", line 40, in list queryset = self.filter_queryset(self.get_queryset()) File "/.../lib/python3.5/site-packages/rest_framework/generics.py", line 151, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) AttributeError: 'OrderingFilter' object has no attribute 'filter_queryset' Going into OrderingFilter, it indeed does not have a filter_queryset method, but the view expects it: # in GenericAPIView(views.APIView) def filter_queryset(self, queryset): """ Given a queryset, filter it with whichever filter backend is in use. You are unlikely to want to override this method, although you may need to call it either from … -
How to synchronously create model instances using a loop in Django?
I have a function that takes a list of objects and via a loop passes each object to a function that creates a model instance. def runScrape(): for source in getFeeds(): print('source',source) assembledFeed= buildFromFeed(getParsedFeed(source)) for item in assembledFeed: addItem(item) the function that adds to db : def addItem(item): try: instance,created= Article.objects.get_or_create(**item) return created except IntegrityError as e: print('integrity',item) return Question is, how can I ensure the order that I pass the items to the addItem function is the order they are inserted into the db ie. when I query these items and sort by created, it comes back in the order I sent it ? -
Do Django backward relations add overhead?
In Django, you create models and can optionally specify a foreign key on a field class Man: ... class Dog: ... owner = models.ForeignKey(Man, on_delete=models.SET_NULL) You can then query each Dog for its respective owner or get all dogs for a Man owner = some_dog.owner all_dogs = some_man.dog_set.all() If you want to not create a backward relation as specified by the docs, you can do class Man: ... class Dog: ... owner = models.ForeignKey(Man, on_delete=models.SET_NULL, related_name='+') Now you no longer have access to all_dogs = some_man.dog_set.all(). However, does this additional "building" of a backward relation add overhead? If I just never ever used all_dogs = some_man.dog_set.all() would it matter whether or not I had specified related_name='+' in Dog? Would it slow things down potentially? And is this functionality purely implemented in application side Django, or would related_name='+' also change the database schema itself? -
Ordered lists of generic foreign keys in Django
I have an app with hierarchical Course, Note and Task models. That is, each Course has a bunch of Note instances pointing to it by ForeignKey, and each Note has a bunch of Task instances pointing to it. I want all the content in a specific order, so I added a sequence attribute to Course and Note via a parent model. This allows them to hold an ordered list of pk's of the linked instances (e.g. [1, 4, 6, 2, 3]), which I can then edit the order of. I also added a global_sequence for Course, which holds a list of ('class_name', pk) tuples as strings E.g. ["('Note', 1)", "('Task', 19)", "('Task', 31)", "('Note', 2)", "('Task', 22)",]. class Sequence(models.Model): sequence = django.contrib.postgres.fields.ArrayField(models.IntegerField()) class Course(Sequence): title = models.CharField(max_len=80) global_sequence = django.contrib.postgres.fields.ArrayField( models.CharField(max_len=30) ) class Note(Sequence): body = models.TextField() course = models.ForeignKey(Course, related_name='content') class Task(models.Model): q = models.CharField(max_len=100) a = models.CharField(max_len=100) note = models.ForeignKey(Note, related_name='content') I feel that my approaches to building sequence and global_sequence may be naive since the sequences have to be manually updated whenever a linked instance is created or deleted (I am using signals for this). Also, strings in global_sequence are probably error-prone and I have to use … -
change css property of placeholder
I have navigation horizontal bar. I placed my placeholder inside navigation bar. In admin panel i clicked + and added few plugins(links). The problem is there is no space between plugins in my case links. How can i set space between plugin texts in same placeholder. In Css i can only manipulate whole division "a" but i want to force white spaces between links. <div class="a"> {% block navibar_1 %}{% placeholder nav_item1 %}{% endblock %}</div> structure admin site: Navbar1 links1 links2 links3 links4 Thanks for help -
Django debug toolbar crashes when deployed on AWS Elastic Beanstalk
I am running a Django app on AWS Elastic Beanstalk but Django debug toolbar is causing the following error: Traceback (most recent call last): File "/opt/python/run/venv/lib/python3.4/site-packages/django/core/handlers/base.py", line 235, in get_response response = middleware_method(request, response) File "/opt/python/run/venv/lib/python3.4/site-packages/debug_toolbar/middleware.py", line 123, in process_response response.content = insert_before.join(bits) File "/opt/python/run/venv/lib/python3.4/site-packages/django/http/response.py", line 315, in content value = self.make_bytes(value) File "/opt/python/run/venv/lib/python3.4/site-packages/django/http/response.py", line 235, in make_bytes return bytes(value.encode(self.charset)) UnicodeEncodeError: 'utf-8' codec can't encode character '\\udcc3' in position 142917: surrogates not allowed I did not have this problem locally or when running my django app on an AWS EC2 instance where I setup nginx and gunicorn myself. Something about Elastic Beanstalk? Maybe that it's apache? Or Python 3.4? Any ideas? Thanks! -
Default image avatar depending on gender
I would like to create kind of profiles with default avatars. GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Someone(models.Model): name = models.CharField(max_length=120) gender = models.Charfield(max_length=1, choices=GENDER_CHOICES) image = models.ImageField(upload_to='avatars', default=someone_avatar) I'm trying to write a function which returns path to my folder with jpg. def someone_avatar(instance): gender = instance.gender if gender == 'Male': avatar = 'avatars/m.jpg' else: avatar = 'avatars/f.jpg' return avatar Obviously it doesn't work, so could you give me some advise how to solve it? Maybe I should overwrite save method? Thx. -
Sometimes method 'connect' of '_socket.socket' objects very slow in Django app
I'm profiling some django app on CentOS and can't figure out why the same requests executed with ~20sec runtime difference. I use silk tool for debugging. There are part of cPython profiler dump for normal request: 1 0.000 0.000 0.049 0.049 /var/www/medbot/www/env/lib/python3.5/site-packages/requests/packages/urllib3/connection.py:128(_new_conn) 1 0.000 0.000 0.049 0.049 /var/www/medbot/www/env/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py:51(create_connection) 1 0.043 0.043 0.043 0.043 {method 'connect' of '_socket.socket' objects} 1 0.000 0.000 0.020 0.020 /var/www/medbot/www/env/lib/python3.5/site-packages/pymystem3/mystem.py:202(close) 1 0.000 0.000 0.020 0.020 /usr/local/lib/python3.5/subprocess.py:1607(wait) And another one for slow request: 1 0.000 0.000 30.086 30.086 /var/www/medbot/www/env/lib/python3.5/site-packages/requests/packages/urllib3/connection.py:128(_new_conn) 1 0.000 0.000 30.086 30.086 /var/www/medbot/www/env/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py:51(create_connection) 4 30.078 7.519 30.078 7.519 {method 'connect' of '_socket.socket' objects} 2 0.002 0.001 4.045 2.022 /var/www/medbot/www/medbot/core/coordinator.py:15(process_message) 1 0.025 0.025 4.006 4.006 /var/www/medbot/www/medbot/core/coordinator.py:30(get_responses) What is {method 'connect' of '_socket.socket' objects} and why is so slow sometimes? -
AWS Elastic Beanstalk configuration commands don't have access to environment variables set in console
I am running a django app on elastic beanstalk and I added the secret key as an environment variable through the elastic beanstalk console Configuration > Software Configuration. In my app's settings module I just set it using `os.environ.get('DJANGO_SECRET_KEY'). App runs fine, no problem. Moreover, if I ssh into the instance and run sudo grep -R DJANGO_SECRET_KEY * I see it show up in the JSON file at /opt/deploy/configuration/containerconfiguration Great, right? No :( Locally I develop and run my app using django's server so it serves my static files itself and no need to collect them. In deployment I need to run python manage.py collectstatic. I don't want to do this every time before I commit and deploy so I added the following command to my .ebextensions/my_stuff.config based on this reference (it's actually shown in several examples): commands: 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/current/app/website/manage.py collectstatic --noinput" When I try to deploy I get this error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. When I ssh into the instance and call echo $DJANGO_SECRET_KEY I get None and I also tried doing the same but from the configuration file and writing to a file but it's also empty. My thinking … -
django - how to add additional parameters to queryset in forms
i want to add additional parameters to the queryset in forms class Reserve(forms.ModelForm): food_name = forms.ModelChoiceField(queryset=Food.objects.all()) def __init__(self, year=None, month=None, day=None, *args, **kwargs): super(Reserve, self).__init__(*args, **kwargs) self.year = kwargs.pop('year') self.month = kwargs.pop('month') self.day = kwargs.pop('day') self.fields['food_name'].queryset = Food.objects.filter( serve_date__year = year, serve_date__month = month, serve_date__day = day) class Meta: model = Reservation fields = ('food_count', 'food_name') but its return KeyError: 'year' -
POST http://127.0.0.1:8080/test.py 405 (Method Not Allowed) when calling a python function from javascript
I have a simple python code: import csv from numpy import genfromtxt from numpy import matrix def main(): x=1 return x; main() and I also have a javascript in my html file : <script type="text/javascript"> function runPyScript(input){ var jqXHR = $.ajax({ type: "POST", url: "./test.py", async: false, data: { param: input } }); return jqXHR.responseText; } // do something with the response response= runPyScript('data to process'); console.log(response); </script> I am using nodejs http-server to run this code on a local web server. However, I always get the error message POST http://127.0.0.1:8080/test.py 405 (Method Not Allowed) Note: My file path is correct and I did run them on a local server I am wondering is there anyway to run a python script from javascript without using any sort of framework such as Django or Flask other than jQuery. Thank you very much! -
Issue with Django Re-rendering template.
I have a view function that is as follows: @never_cache def index(request): clothes = Clothes_Item.objects.all() filter_category = request.GET.get("filter_category") if filter_category: clothes = Clothes_Item.objects.filter(gender=filter_category) return render(request, 'index.html', {'clothes': clothes}) Initially, I want this view to render index.html and display all clothes items. I have added a button to this page that I want to act as a filter, so that only specific objects are displayed when it is in the clicked state. Once the user clicks the button, I use ajax to trigger a call to the same view function (index), and filter the items based on the data of the button that was clicked. I have traced through some of my code and I am positive that this logic works within the view function (tested by printing value of "clothes" to terminal before and after button clicks). However, my webpage does not reflect these changes. I read some of the django documentation for render and looked at some other stackoverflow posts and I'm still confused as to why my changes aren't visible. -
How to use template tag to iterate through manytomany model?
I'm trying to learn Django but I need help because I'm having trouble understanding. how can I iterate through all of my models without having to write for loops for each level of tasks that I have? Example but like infinite sub tasks: Task #1 1.1 Subtask #1 1.2 Subtask #2 1.2.1 Subsubtask #3 Task #2 2.1 Subtask #4 . . . . My model many to many field on itself class task(models.Model): name = models.CharField(max_length=100) notes = models.TextField() created = models.DateTimeField() created_by = models.ForeignKey(User) subtask = models.ManyToManyField('self') My template {% for task in items %} <li>{{ task.name }} <ul> {% for subtask in task.subtask.all %} <li>{{ subtask.name }}</li> {% endfor %} </ul> </li> {% endfor %} How can I use a template tag to infinite for loop down tasks -
Adding <style> makes PyCharm stop autocomplete css
I have a problem with PyCharm autocomplete in my Django project. I've added a <style> ... </style> tag into the head of the page. When I did this, PyCharm stopped autocompleting css in this file - for example col-lg... from Bootstrap etc. If I comment the tag or move it at the bottom of a bootstrap.css, autocomplete works correctly. Is there a reason for that or it is a bug? This is the head: {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block head %} <script src="{% static "js/scripts/newOrder.js" %}"></script> <script src="{% static "chosen_v1.6.2/chosen.jquery.min.js" %}"></script> <script src="{% static "js/scripts/newOrder.js" %}"></script> <link href="{% static "chosen_v1.6.2/chosen.min.css" %}" rel="stylesheet"> <link href="{% static "popselect/css/jquery.popSelect.css" %}" rel="stylesheet"> <script src="{% static "popselect/jquery.popSelect.min.js" %}"></script> <style> {# THIS IS THE TAG #} /* required to avoid jumping */ .scrollfollowwrapper { position: absolute; width: 350px; } .scrollfollow { position: absolute; top: 0; } .scrollfollow.fixed { position: fixed; top: 12%; width: 332px; } </style> <script> $(document).ready(function () { $("#id_target_languages").popSelect({ showTitle: false, placeholderText: 'Click to Add More', position: "bottom", width: 500 }); }) </script> <script> var acc = document.getElementsByClassName("accordion"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function () { this.classList.toggle("active"); … -
Using email field for authentification in Django 1.10.2 in custom user and result error
I try to extend user model, using AbstractUser and a new application named custom_user. In CustomUser class I override email field with: email = models.EmailField('email address', unique=True, db_index=True) and I set USERNAME_FIELD = email but when I try to make migrations using python manage.py makemigrations I occurred the error: ERRORS: custom_user.CustomUser.email: (models.E006) The field 'email' clashes with the field 'email' from model 'custom_user.customuser'. -
Django - django-autocomplete-light setup how to
I am following the tutorial on how to setup django-autocomplete fields and Im struggling to get it working. Here's the tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html settings Installed Apps INSTALLED_APPS = ( 'dal', 'dal_select2', 'django.contrib.admin', project urls.py from textchange.views import TextbookAutoComplete urlpatterns = [ url(r'^textbook-autocomplete$', TextbookAutoComplete.as_view(), name='textbook-autocomplete'), HTML <form method="POST"> {% csrf_token %} {% for field in form3 %} {{ field }} {% endfor %} <input id="search" class="button" type="submit" value="Search Textbooks" name="Search"></input> </form> Forms.py class Search(forms.ModelForm): longschool = forms.ModelChoiceField( queryset=Textbook.objects.all(), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) class_name = forms.ModelChoiceField( queryset=Textbook.objects.all(), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) isbn = forms.ModelChoiceField( queryset=Textbook.objects.all(), widget=autocomplete.ModelSelect2(url='textbook-autocomplete') ) class Meta: model = Textbook fields = ('longschool', 'class_name', 'isbn') Views.py class TextbookAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Textbook.objects.none() qs = Textbook.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs Jquery added <script type="text/javascript" src="{% static "admin/js/jquery.js" %}"></script> When the form shows up in my html it's just three dropdowns without input fields (as in without anywhere to type). Can anyone see what I am missing? Any help would be greatly appreciated. -
Django 1.10 self reference foreign key does not accept nulls
I have this model in Django: class Unit(models.Model): Name = models.CharField(max_length=512) type = models.CharField(max_length=512) Hull_Number = models.CharField(max_length=100) email = models.CharField(max_length=512) Commander = models.ForeignKey(User) ParentUnit = models.ForeignKey('Unit', blank=True) Address1 = models.CharField(max_length=512) Address2 = models.CharField(max_length=512, blank=True) City = models.CharField(max_length=255) Province = models.CharField(max_length=255) Country = models.CharField(max_length=255) PostalCode = models.CharField(max_length=10) Avatar = models.FileField(upload_to='UnitAvatar/%Y/%m/%d', blank=True) Cover = models.FileField(upload_to='UnitCover/%Y/%m/%d', blank=True) Facebook = models.URLField(default='', blank=True) GooglePlus = models.URLField(default='', blank=True) Twitter = models.URLField(default='', blank=True) Website = models.URLField(default='', blank=True) The Sixth field is called ParentUnit. It is a self-reference parent/child reference. My problem is the first record. While attempting to insert a first record, the response I get is: null value in column "ParentUnit_id" violates not-null constraint DETAIL: Failing row contains (3, USS Enterprise, Heavy Cruiser, NCC-1701, arcee123@gmail.com, 123 Anywhere Street, , Anytown, AnyProvince, USA, 12345, , , , , , , 1, null). Because ParentUnit_id is a FK, it is expecting a non-null response when migrate is ensued. How do I add children with no parent records if this is the case? Thanks. -
Unable to test my first Django code
I've just started to learn Django and git using win10. I created a python file called functional_tests.py with the following code : from selenium import webdriver browser = webdriver.Firefox() browser.get('http://localhost:8000') assert 'Django' in browser.title Of course, I got a firefox window popping up with an error message when I try to run this pyhton file alone Then, in git bash I do : $django-admin.py startproject superlists $cd superlists $python manage.py runserver In another command shell, I do : $python functional_tests.py I'm supposed to have a Firefox window popping up with a message congratulating me. Instead, no firefox window pop up and I have this error : Traceback (most recent call last): File "functional_tests.py", line 3, in browser = webdriver.Firefox() File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 134, in init self.service = Service(executable_path, log_path=log_path) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\service.py", li ne 45, in init log_file = open(log_path, "a+") PermissionError: [Errno 13] Permission denied: 'geckodriver.log' Exception ignored in: > Traceback (most recent call last): File "C:\Python34\lib\site-packages\selenium\webdriver\common\service.py", lin e 163, in del self.stop() File "C:\Python34\lib\site-packages\selenium\webdriver\common\service.py", lin e 129, in stop if self.log_file != PIPE: AttributeError: 'Service' object has no attribute 'log_file' I have already added Firefox and geckodriver in PATH Any idea ? thanks -
quick web page with visualization using python
Sorry if this is a very simple question and there is no specific answer and depends on different people's opinion. But this would be helpful for people who are starting. Kindly help me in this regard. I want to use Python. (Please don't give me alternatives to python as my organization doesn't want to use other languages) I want to create a web page, that shows the status of a the status of the GIT repository like size, number of branches, the HEAD commitID etc. In short i want to show graphically (even a simple red,yellow,green block representing a directory/repository is enough) the status of GIT repository in different remote locations. The webpage should be able to update the status every few minutes. Am very new to web development, so what all tools would be easier to learn and start along with PYTHON for such a website? Please suggest me if any frameworks can be simple to learn and to use. I need suggestion for quick starts. Again, i want to use Python, so please don't suggest me any node.js or php or ruby on rails etc. -
Django summernote CSFR token missing or incorrect summernote/upload_attachment
Forbidden : summernote/upload_attachment Thats the error that I get when I try to upload an image using django-summernote, with SummernoteInplaceWidget(). When I use SummernoteWidget it works all fine, the image is uploaded. What could be the problem? Here is my code: views.py: @login_required(login_url='account_login') def create_post(request): if request.method == 'POST': post_form = CreatePostForm(data=request.POST, files=request.FILES) if post_form.is_valid(): new_post = post_form.save(commit=False) new_post.author = request.user new_post.slug = slugify(new_post.title) new_post.save() messages.success(request, 'Post created successfully') # redirect to new created item detail view return redirect(new_post.get_absolute_url()) else: post_form = CreatePostForm() context = {'post_form': post_form} return render(request, 'blog/post/create_post.html', context) models.py: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='blog_posts') body = models.CharField(max_length=5000, blank=True, unique=False, null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager published = PublishedManager() # Our custom manager tags = TaggableManager() header_photo = models.ImageField(upload_to = 'users/%Y/%m/%d', null = True, blank = True, width_field="width_field", height_field="height_field" ) width_field = models.IntegerField(default = 0, null = True) height_field = models.IntegerField(default=0, null = True) class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blogs:post_detail', args=[self.id, self.slug]) @property def header_photo_url(self): if self.header_photo and hasattr(self.header_photo, … -
Django DisallowedHost error
I'm running django with apache and I'm getting the following error in my apache error.log: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS., referer: http://example.com/ In my settings.py I have: ALLOWED_HOSTS = ['*'] This should allow any host shouldn't it? -
Coloring series in django-graphos google Chart
How can I set a color for each series in django-graphos google Column Chart? To do this google chart has this in documentation (https://developers.google.com/chart/interactive/docs/gallery/columnchart#coloring-columns) var data = google.visualization.arrayToDataTable([ ['Element', 'Density', { role: 'style' }], ['Copper', 8.94, '#b87333'], // RGB value ['Silver', 10.49, 'silver'], // English color name ['Gold', 19.30, 'gold'], ]); but when I use that to in my data array in django-graphos data = [ ['Element', 'Density', { role: 'style' }], ['Copper', 8.94, '#b87333'], // RGB value ['Silver', 10.49, 'silver'], // English color name ['Gold', 19.30, 'gold'], ] I got this error: All series on a given axis must be of the same data type. What should I do to set a different color in each series for a google column chart in django-graphos? Thanks -
Django 1.10 - url ending with ? can't be retrieved at view
I have an url like - ...poll/3/what's-up? In urlpatterns, I am checking for any kind of string for question text with following code - url(r'^poll/(?P<question_id>[0-9])/(?P<question_text>.+)', views.question_details), After debugging i see it returns in view - question_text = what's-up but not question_text = what's-up? I think this is my regex implementation issue. -
Name error: Can not import [model name]
I am trying to link the model Post to the model Topic via a foreign key. When I run the makemigrations command, it raises an import error, and says that the name 'Topic' is not defined. What could be the cause of this? It certainly seems to be defined. I've pretty much ruled out that it is not a problem within the db. class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) title = models.CharField(max_length=100) summary = models.TextField(blank=True, null=True) content = models.TextField() draft = models.BooleanField(default=False) details = models.CharField(blank=True, null=True, max_length=250) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) topic = models.ForeignKey(Topic, blank=True, null=True) thumbnail = models.ImageField(upload_to='media', blank=True, null=True) def get_absolute_url(self): return reverse('posts:detail', kwargs={'pk': self.pk}) def __str__(self): return self.title class Topic(models.Model): name = models.CharField(max_length=50) description = models.TextField() picture = models.ImageField(upload_to='media', blank=True, null=True) isperson = models.BooleanField(default=False) ispolicy = models.BooleanField(default=False) positive = models.BooleanField(default=True) percent = models.CharField(max_length=5) def __str__(self): return self.name Any ideas? I don't see any problems in this code, and neither did my IDE, which recognized the model Topic