Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - username already taken
I'm new to python and django and following tutorials online here and there I was trying to develop an app. But when doing the register function I encountered an error. Django says that the user name already exist when I'm trying to create an user, but the user doesn't exist and I'm stuck. Can you help? models.py from django.contrib.auth.models import User from django.db import models class Hobby(models.Model): hobby = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.hobby class Member(User): gender = models.CharField(max_length=6) date_of_birth = models.DateField() picture = models.ImageField(upload_to='profile_images') hobby = models.ManyToManyField(to=Hobby, blank=True, symmetrical=False) urls.py urlpatterns = [ # /matchings/ path('', views.home, name='home'), # /matchings/login path('login/', views.login, name='login'), # /matchings/login path('signup/', views.signup, name='signup'), # /matchings/login path('register/', views.register, name='register'), ] singup.html {% extends 'base.html' %} {% block head %} <title>Sing Up</title> {% endblock %} {% block body %} <div class='main'> <h3>Please enter your details to sign up</h3> <form method='POST' action="{% url 'register' %}"> {% csrf_token %} <span class='fieldname'>Username</span> <input type='text' maxlength='16' id='regusername' name='username'> <span id='info'></span> <br> <span class='fieldname'>Password</span> <input type='password' maxlength='16' name='password'><br> <span class='fieldname'>&nbsp;</span> <input type='submit' value='Sign up'> </form> </div> {% endblock %} views.py from django.shortcuts import render from django.utils import timezone from django.http import HttpResponse, Http404 from django.template import RequestContext, loader from matchings.models … -
Updating audio.currentTime resets to 0 - unintended behavior (Django?)
I'm attempting to update the currentTime of an html audio element, however, it keeps resetting to 0 no matter what value I give it. I've confirmed that the values I'm passing are less than the audio file's duration, and greater that 0. The following code works as-intended locally in an html file, but exhibits this strange behavior in my Django app. HTML: <audio id="my-audio" preload="true" src="path/to/file.mp3" type="audio/mp3"></audio> JavaScript: var audio = document.getElementById('my-audio') audio.play() console.log(audio.currentTime) // result: 0.997171 or similar console.log(audio.duration) // result 3596.06855 audio.currentTime = 500 console.log(audio.currentTime) // result: 0 All my other audio-related functions are working. This strange behavior occurs with multiple different audio files. I've searched SO for a solution, but nothing seems relevant to my particular case. I'm thinking that is has something to do with Django's server per the following comment from another thread. But I can't find any more information about this. I am facing the same issue. It's working on a piece of code, but when i integrate it in a Django application, it fails. It works on Firefox but not on Google Chrome. Video / Audio file doesn't matter, it happens with any file i try on the code. The time i am … -
how to set foreign key in function based view in django?
This is the error - Cannot assign "'question2'": "Answers.question" must be a "Question" instance. model.py def main(request, pk): ques = get_object_or_404(Question, pk=pk) if request.method == "POST": answerForm = AnswerForm(request.POST) if answerForm.is_valid(): ans = answerForm.save(commit=False) ans.user = request.user ans.question = Answers(question=ques.question) # here assigning foreign key ans.answer = answerForm.cleaned_data.get['question_sel'] print(answerForm.cleaned_data.get['question_sel']) ans.save() return redirect('main', pk=ques.pk) else: answerForm = AnswerForm(request.POST) return render(request, 'quiz/main.html', {'ques': ques,'answerForm':answerForm}) -
AngularJS Error Controller with this name is not registered
im having a headache with this one, im not very skilled in Angular but was the only way to check 'today dolar value'. This is my dolar.js var app = angular.module("app", []); app.controller("DolarCtrl", function($scope, $http) { $scope.dailyIndicators = ''; $http.get('https://mindicador.cl/api/dolar').then(function(res) { //.success was changed for .then // $scope.dailyIndicators = res.data.serie[0].valor; }) }); base.html <body ng-app> <p ng-controller="DolarCtrl"> Dolar acutal: $ {{DolarCtrl.dailyIndicators}}</p> </body> but at soon as i refresh the page, i got this error: error: [$controller:ctrlreg] http://errors.angularjs.org/1.7.5/$controller/ctrlreg?p0=DolarCtrl at angular.js:99 at angular.js:11646 at ga (angular.js:10677) at q (angular.js:10462) at g (angular.js:9801) at g (angular.js:9804) at angular.js:9666 at angular.js:1947 at m.$eval (angular.js:19356) at m.$apply (angular.js:19455) any ideas? i dont know if you guys needs more info. thanks! -
Deploying django site to elasticbeanstalk: NotAuthorizedError: Operation Denied. The security token included in the request is invalid
I am getting this error when trying to deploy to elastic beanstalk using CLI. The deploy was working before I added the code to a remote git repository (theplay.team) vagrant@debian-7:/vagrant/Devel/theplay.team/theplayteam$ eb deploy --verbose INFO: Deploying code to playground-env in region us-east-1 INFO: Getting version label from git with git-describe /vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings SNIMissingWarning INFO: Traceback (most recent call last): File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/core/ebrun.py", line 41, in run_app app.run() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/foundation.py", line 797, in run return_val = self.controller._dispatch() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/controller.py", line 472, in _dispatch return func() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/cement/core/controller.py", line 478, in _dispatch return func() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/core/abstractcontroller.py", line 85, in default self.do_command() File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/controllers/deploy.py", line 83, in do_command staged=self.staged, timeout=self.timeout, source=self.source) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/deployops.py", line 50, in deploy app_name, process=process_app_versions, label=label, message=message, staged=staged, build_config=build_config) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/commonops.py", line 507, in create_app_version s3_bucket, s3_key = get_app_version_s3_location(app_name, version_label) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/operations/commonops.py", line 347, in get_app_version_s3_location app_version = elasticbeanstalk.application_version_exists(app_name, version_label) File "/vagrant/.virtualenvs/theplay.team/local/lib/python2.7/site-packages/ebcli/lib/elasticbeanstalk.py", line 408, in application_version_exists app_versions … -
Reverse for 'random_obj' with keyword arguments '{'ran': ''}' not found. 1 pattern(s) tried: ['detail\\/(?P<ran>[0-9]+)\\/$']
I want to create a view that generates a random number for me between 1 and the amount of objects inside the model. I then want to pass it as context to the template. However i keep getting the following error: Reverse for 'random_obj' with keyword arguments '{'ran': ''}' not found. 1 pattern(s) tried: ['detail\/(?P[0-9]+)\/$'] def random_page(request): object_count = MODEL.objects.count() ran = random.randint(1, object_count) return render(request, 'app/detail.html', {'ran': ran}) urlpatterns = [ path('', views.home, name='home_page'), path('detail/<int:pk>/', views.detail_page, name='detail_page'), path('detail/<int:ran>/', views.random_page, name='random_page'), ] This results in above error: <a class="anchor_boot" href="{% url 'app:random_page' ran=ran %}">random obj</a> </div> This works: <a class="anchor_boot" href="{% url 'app:random_page' 8 %}">random obj</a> </div> What am I doing wrong? -
How to accomplish full record update on Django REST serializer update() method
I have a model based serializer called RecipeSerializer(). In it I have a create method that looks like so: class RecipeSerializer(serializers.ModelSerializer): hops = HopAdditionSerializer(many=True) fermentables = FermentableAdditionSerializer(many=True) style = StyleSerializer() yeast = YeastSerializer() class Meta: model = Recipe exclude = () def create(self, validated_data): recipe = Recipe.objects.create(**validated_data) recipe.save(); return recipe What I'm trying to do is something similar with my update() method. In the documentation they show going through each field one by one and setting the values: def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.save() My model has many fields though. What I'd like to do is pass the validated data to the update method similar to the create method: instance.update(**validated_data) However, I get an error: 'Recipe' object has no attribute 'update' Is it possible to update all properties of the instance using the validated dataset without setting each property individually? -
Python MySQLdb works from Python on Command Line but not Django Views.py
I have a Django views.py function named getpos that gets served by apache2 and wsgi.py. If I run the exact same code from my views.py in a normal Python session from the Ubuntu command line, the MySQLdb connection works fine: >>> import MySQLdb >>> db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps") >>> >>> cursor = db.cursor() If I run it from the django debug server, it fails with: ERROR: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") The code that runs is this: def getpos(request): query = "SELECT * FROM..." # connect to the DB and return nearby deals db = MySQLdb.connect(host="localhost",port=22,user="root",passwd="mypassword",db="gps") cursor = db.cursor() # Query the gps Data database results = cursor.execute(query) db.commit() Howcome I can connect from Python on the command line but not in the views.py file with Django? Thanks. I've tried using "127.0.0.1" instead of "localhost", but nothing seems to work. I appreciate any help thanks! -
Dynamic url pattern in django
I don't fully understand how to make the dynamic menu in Django. I have this in models.py class Menu(models.Model): menu_title = models.CharField(verbose_name=_('Menu title'), max_length=70) is_active = models.BooleanField(verbose_name=_('Is active'), default=False) slug = models.SlugField(max_length=70, null=True) class Meta: verbose_name = _('Menu') verbose_name_plural = _('Menus') def get_absolute_url(self): return reverse("main:menu", kwargs={'slug':self.slug}) in template: {% for item in menu %} {% if item.is_active %} <li class="navigation-panel__item"><a href="{{ item.get_absolute_url }}" class="navigation-panel__link">{{ item.menu_title }}</a></li> {% endif %} {% endfor %} in admin.py class MenuAdmin(TabbedTranslationAdmin): list_display = ('menu_title', 'is_active') prepopulated_fields = {"slug": ("menu_title_en",)} in urls.py urlpatterns = [ path('<slug>', ArticleListView.as_view(), name='menu'), ] Now all buttons in menu refer to article list view page. But I should render various views for various slugs. Is it possible to select a view based on the slug field? Thanks. -
Heroku/Django deploy: why am I getting an error 500 with successful deploy and static collection?
Here is my repo in full. I've been struggling to deploy my first Django site on Heroku for months. I'm getting successful builds with git push heroku master and successfully collecting the static files using heroku run python manage.py collectstatic --noinput, but I can't get the site to serve without an error 500 when DEBUG = config('DEBUG', default=False, cast=bool). The site does work when DEBUG is set to True (though I'm going to have to figure out making the database work). I think my allowed hosts are set correctly. All of the answers I can find on SO don't quite solve my issue. I added the logging from this answer which gives me a little more information in the logs, but I'm not understanding why the staticfiles aren't available when I've been able to successfully collect them? 2018-12-09T16:24:38.181428+00:00 heroku[web.1]: State changed from starting to up 2018-12-09T16:24:39.173376+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/ 2018-12-09T16:24:39.173419+00:00 app[web.1]: warnings.warn(u'No directory at: {}'.format(root)) 2018-12-09T16:24:39.173421+00:00 app[web.1]: /app/.heroku/python/lib/python2.7/site-packages/whitenoise/base.py:104: UserWarning: No directory at: /app/staticfiles/ 2018-12-09T16:24:39.173423+00:00 app[web.1]: warnings.warn(u'No directory at: {}'.format(root)) I'm obviously missing a lot, any guidance would be most appreciated. -
iterate trough a forms in dictionaly passed from view to html in python with jinja
I would appreciate your help in the below problem: I need to use 3 different models in a python app which I want the user to populate from a HTML form. I want to use model forms and I pass all the three different form in one dictionary (see my views.py): def new_sales_trip(request): if request.method == "POST": Restaurant_Form = RestaurantForm(request.POST) SalesEvent_Form = SalesEventForm(request.POST) NextAction_Form = NextActionForm(request.POST) if Restaurant_Form.is_valid() and SalesEvent_Form.is_valid() and NextAction_Form.is_valid(): Restaurants = Restaurant_Form.save() SalesEvents = SalesEvent_Form.save(False) NextActions = NextAction_Form.save(False) SalesEvents.restaurants = Restaurants SalesEvents.save() NextActions.restaurants = Restaurants NextActions.save() return redirect('/') else: allforms = { 'Restaurant_Form': Restaurant_Form, 'SalesEvent_Form': SalesEvent_Form, 'NextAction_Form': NextAction_Form, } return render(request, 'sales/SalesTrip_form.html', allforms) else: Restaurant_Form = RestaurantForm() SalesEvent_Form = SalesEventForm() NextAction_Form = NextActionForm() c = {} c.update(csrf(request)) allforms = { 'Restaurant_Form': Restaurant_Form, 'SalesEvent_Form': SalesEvent_Form, 'NextAction_Form': NextAction_Form, } return render(request, 'sales/SalesTrip_form.html', allforms) So far it works - however I don't know how to use this dictionary to iterate trough in my template so I shouldn't reference all the form by name separatelly. I try to to do something like this: {% for key, value in allforms.items %} {% for field in value %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <!--this gonna be only displayed if there is an error … -
Django QuerySet last added from a specific category
Probably an extremely easy solution, but cant really come up with one. The end-goal is to create a gallery showing at first the categories. Each category should display the last added image with the respective category name. My models.py class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() objects = models.Manager() class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=200) description = models.TextField(blank=False, null=True) date = models.DateTimeField(blank=False, null=True) image = models.ImageField(blank=True, null=True) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL) objects = models.Manager() class Meta: app_label = 'home' get_latest_by = 'date' My views.py def index(request): cat = Category.objects.all() latest = Item.objects.latest('date') context = { 'categories': cat, 'last_added': latest, } return render(request, 'gallery/index.html', context) My index.html {% block content %} <h4 class="gallery">Gallery</h4> {% for category in categories %} <p class="category">{{ category.name }}</p> <p> <img class="images" src="{{ last_added.image.url }}"> </p> {% endfor %} {% endblock %} I cannot figure out how to display the latest image for their respective category. I know i have to somehow create a dynamic query that would use the 'category.name' as variable, but i cannot figure out how to do this. Any input would be very valuable, at least indicating the direction in which i … -
Create proxy web server in Django
I need to create a web server that proxies the request to the SWAPI api, finds the context provide(for example a character) and returns the result. I've done this many times but never had to create a proxy web server. So how do I implement a proxy web server??? I don't even know where to start. Any help? -
Generating gifs based on a user input
I would like to generate gifs based on a user input. I can generate a single gif using the following code: ` def getGif(request): import time import giphy_client from giphy_client.rest import ApiException from pprint import pprint # create an instance of the API class api_instance = giphy_client.DefaultApi() api_key = 'dc6zaTOxFJmzC' # str | Giphy API Key. q = 'rainbow' # str | Search query term or prhase. limit = 25 # int | The maximum number of records to return. (optional) (default to 25) offset = 0 # int | An optional results offset. Defaults to 0. (optional) (default to 0) rating = 'g' # str | Filters results by specified rating. (optional) lang = 'en' # str | Specify default country for regional content; use a 2-letter ISO 639-1 country code. See list of supported languages <a href = \"../language-support\">here</a>. (optional) fmt = 'json' # str | Used to indicate the expected response format. Default is Json. (optional) (default to json) try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) # pprint img = requests.get(api_response.data[0].images.fixed_height_downsampled.url) return HttpResponse(img,content_type='image/gif') #return HttpResponse(api_response.data[0].images.fixed_height_downsampled.url, content_type="application/json") except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)` -
Optimize Django Queryset for loop
How can I optimize the following queryset? [link.goal for link in self.child_links.all()] I want to get rid of the for loop and hit the database only once. I've got the following code: class Goal(models.Model): name = models.CharField(max_length=300) progress = models.SmallIntegerField(default=0) def __str__(self): return self.name def calc_progress(self): progress = 0 subgoals = [link.goal for link in self.child_links.all()] self.progress = int(progress) class Link(models.Model): parent_goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="child_links") goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="parent_links") weight = models.SmallIntegerField(default=1) def __str__(self): return str(self.parent_goal) + "-->" + str(self.goal) -
django-admin.py doens't work on Windows Server 2012
I'm not an expert on Python, however, I've been trying to setup a project on Windows Server 2012 on IIS. When I've tryed to run 'django-admin.py startproject teste' I always got an error like this: I've tryed the command in the following ways: django-admin.py startproject teste python django-admin.py startproject teste C:\Python37\Scripts\django-admin.py startproject teste My environment variables are like this: Can someone help me on this, please? -
Is there any HTML editor like CK editor where HTML block drag and drop features are present like in wordpress that can be used in django project
Is there any HTML editor like CK editor where HTML block drag and drop features are present like in wordpress that can be used in django project. I have a campaign mailing system where I want to user HTML editor to make campaigns using the likes of CK Editor etc. Is there any Drag and Drop HTML Editors out there. E.g. The ability to drag a heading into the editor, or a heading and an image and it fixes into a specific layout. I am only after the editor capabilities. -
attribute error when try to define url for index view
I keep getting a strange error when I define urls: AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://localhost:51942/ Django Version: 2.1.3 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' here is my urls: from django.contrib import admin from django.urls import path from saeed import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), ] and here is my views: from django.shortcuts import render def index(request): return render,"index.html" Please inform me. thanks, Saeed -
django rest action got unexpected positional argument
I have an viewset with action, which has defined for adding friends to user. But I got a problem with url, send post query on http://localhost:8000/accounts/users/mercer/add_friend/ and got this message: add_friend() got an unexpected keyword argument 'username' My ViewSet: class UserViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = UserSerializer lookup_field = 'username' http_method_names = ['get', 'patch', 'post'] @action(detail=True, methods=['post']) def add_friend(self, request): return Response('ok') -
How to avoid duplication of records in the database?
There are following models: class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) #not FK par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.AutoField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE, null=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE, null=True) I write down as follows: def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) recipe, created = Recipe.objects.get_or_create(par_recipe=ws["B2"].value) line, created = Line.objects.get_or_create(par_machine=ws["C2"].value) order, created = Order.objects.get_or_create(par_fa=ws["D2"].value) data = [] data_par = [] _id = 1 for row in ws.iter_rows(row_offset=1): parameter = Parameter() parameter.id_parameter = _id _id += 1 parameter.par_rollennr = row[5].value parameter.par_definition_id = row[6].value parameter.par_name = row[7].value data_par.append(parameter) measurements = Measurements() measurements.par_value = row[8].value measurements.line = line measurements.order = order measurements.parameter = parameter measurements.recipe = recipe data.append(measurements) # Bulk create data Measurements.objects.all().delete() Parameter.objects.all().delete() Parameter.objects.bulk_create(data_par) Measurements.objects.bulk_create(data) return True How to avoid duplication of records in the Parameter table and not to lose dependencies by Id. The parameter is 3 fields in the file, each next line has its own, but there are no more than 1052 in total and they are repeated, respectively, every 1052 entries. It looks like this: rollennr | deffinitionid | name | value … -
Comparing instance of different models - Django REST Framework
I'am just looking for answer for my (seems to be stupid) question. I've already watched few stackoverflow posts but any of them was helpful :( My question is how to compare two instance of different models with different? Here is my case: I've got two models: Product and Connector. First include id(pk), name, ect. Another include id(pk), productId(fk), userId(fk), ect. My goal is to prepare view that list only product which are in Connector db-table as product(fk). def list(self, request, *args, **kwargs): # return only product user's watching userId = self.request.user.id connectorData = ConnectorModel.objects.filter(userId=userId) allProducts = self.get_queryset() productListToDisplay = [] for product in allProducts: for connector in connectorData: if product.id == connector.productId: # HERE IS A PROBLEM productListToDisplay.append(product) serializer = ProductSerializer(productListToDisplay, many=True) return Response(serializer.data) Problem is that Django consider "product.id" and "connector.productId" as totally different types. Firs is "core.models.ProductModel" and second is "core.models.ConnectorModel". I was trying to parse it using int() but it generate errors. How I can compare this two values to add object to productListToDisplay array? (I saw django doc - Comparing objects but there is no helpful information for this case) -
pip3 install django on ubuntu
Trying to install djnago on my Ubuntu but I fail to do that. I guess this is due to the fact I have python 2/7 and python 3 on my Ubunutu: pip3 install django Traceback (most recent call last): File "/usr/local/bin/pip3", line 5, in <module> from pkg_resources import load_entry_point File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3126, in <module> @_call_aside File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3110, in _call_aside f(*args, **kwargs) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 3139, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 583, in _build_master return cls._build_from_requirements(__requires__) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 596, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/itaybz/.local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 784, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'pip==9.0.1' distribution was not found and is required by the application The following is installed on the ubunuto: itaybz@itaybz-ub-pc:/usr/local/bin$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> itaybz@itaybz-ub-pc:/usr/local/bin$ python3 Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. -
How can i check if model field was changed in post_save?
I have to do some extra logic in post_save if one of model fields was updated, but can't check if it was updated. Tried to override init method like this def __init__(self, *args, **kwargs): super(Profile, self).__init__(*args, **kwargs) self.__old_city = self.city and in post_save check if instance.city != instance.__old_city: #extra logic but got an exception AttributeError: 'Profile' object has no attribute '__old_city' What i'm doing wrong(except of using signals :D )? -
NoReverseMatch at /polls/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
NoReverseMatch at /polls/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/vote/$'] index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <!-- # the 'name' value as called by the url template tag --> <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> <!-- or: <li><a href=" url 'detail' question.id "> question.question_text </a></li> How does one make it so that Django knows which app view to create for a url when using the url template tag? So we use polls:detail --> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <input type="submit" value="Vote"> </form> enter image description hereenter image description here Below it's console error. Other relative questions in stackoverflow have answer like: not question_id! It's question.id! Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P[0-9]+)/vote/$']: 113 {% endfor %} 114 </ul> 115 {% else %} 116 <p>No polls are available.</p> 117 … -
Django/Database models automatic categorization
I am just starting with the Django framework and I have not too many background in databases as I am not a professional programmer. I am looking for the most elegant way to model the following: one item in the model , e.g. CharField could be: house, bridge, church I want to add a field that automatically uses "building" for these items. Or, I have car, truck, etc. it uses "automatically" (acc. to my definition) the category "vehicle". Ideally, I would just add data to the word lists, which are stored in a database and classification would be done accordingly. Is there something like enumeration/classification type? Hope it is clear, otherwise, please let me know. Thanks in advance for your help!