Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sort CommaSeparatedIntegerField in Django Admin
I'm working on a model witch has an CommaSeparatedIntegerField in wich i store the order of some Images witch I'm getting from filers FolderField. class Gallery(models.Model) […] folder = FilerFolderField(blank=False) order = models.CommaSeparatedIntegerField(max_length=300, blank=True) Now I'm looking for a way to be able to change this order easily (e.g. by drag and drop) in the Django admin P.S. I know that FilerFolderField is not documented yet and could be removed, and also that CommaSeparatedIntegerField is deprecated. -
Convert Django QuerySet to Pandas Dataframe and Maintain Column Order
Given a Django queryset like the following: qs = A.objects.all().values_list('A', 'B', 'C', 'D', 'E', 'F') I can convert my qs to a pandas dataframe easily: df = pd.DataFrame.from_records(qs.values('A', 'B', 'C', 'D', 'E', 'F')) However, the column order is not maintained. Immediately after conversion I need to specify the new order of columns and I'm not clear why: df = df.columns['B', 'F', 'C', 'E', 'D', 'A'] Why is this happening and what can I do differently to avoid having to set the dataframe columns explicitly? -
why is my data not being updated?
this is model for the database, the user changes the importance, and according to the level the user chooses, a score/point is to assigned but all it shows is 300 for my_points and 0 for their_points no matter what is chosen. from django.db import models from django.conf import settings from django.db.models.signals import post_save # Create your models here. class Question(models.Model): text = models.TextField() active = models.BooleanField(default = True) draft = models.BooleanField(default = False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) #answers = models.ManyToManyField('Answer') def __unicode__(self): return self.text[:10] class Answer(models.Model): question = models.ForeignKey(Question) text = models.CharField(max_length=120) active = models.BooleanField(default=True) draft = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __unicode__(self): #def __str__(self): return self.text[:10] LEVELS = ( ('Mandatory', 'Mandatory'), ('Very Important', 'Very Important'), ('Somewhat Important', 'Somewhat Important'), ('Not Important', 'Not Important'), ) class UserAnswer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) question = models.ForeignKey(Question) my_answer = models.ForeignKey(Answer, related_name = 'user_answer') my_answer_importance = models.CharField(max_length=50, choices= LEVELS) my_points = models.IntegerField(default=-1) their_answer = models.ForeignKey(Answer, null=True, blank=True, related_name = 'match_answer') their_importance = models.CharField(max_length=50, choices= LEVELS) their_points = models.IntegerField(default=-1) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __unicode__(self): return self.my_answer.text[:10] def score_importance(importance_level): if importance_level == "Mandatory": points = 300 elif importance_level == "Very Important": points = 200 elif importance_level == "Somewhat Important": points = 50 elif importance_level == … -
Directory structure for large django rest framework apps
We've been developing an application using django and django rest framework for a while now and we're reaching a point where our viewsets.py and serializers.py files are getting too large. Our current structure is very similar to what many posts describe (eg. Large Django application layout) but they only seem to suggest creating new applications as the best route to maintaining manageable directories. Our current set up is as follows: project app1 models.py serializers.py viewsets.py ... app2 models.py serializers.py viewsets.py ... For our use case, our models.py are small and discrete enough that I don't think we need to separate them out into separate applications, but I'm not sure what else we can do. -
how to wait function call return value befor go to the next line in anguler js
I have two functions is_exist() and save() functions. In save function I calls is_exist() function before performing a save.it return boolean value. but my problem is save() function is not wait until is_exist() function to return the value.after is_exist() function called it just jump into next line and continue execute bellow lines, after save() finished is_exist() function return the value var app = angular.module('my_app', []) app.controller('my_con', ['$scope', '$http', function($scope, $http) { $scope.save = function(sector) { var del_status = $scope.is_exsis(sector); console.log(del_status); // is_exsis return value if(!del_status) { // save } } $scope.is_exist = function(sector) { $http({ method : 'POST', url : '/is_data_exist', contentType : 'application/json; charset=utf-8', data : angular.toJson({ 'sector': sector }), dataType: 'json', }).then(function successCallback(response) { console.log(response.data); //http respond if(response.data == 'False') { return false; } else { return true; } }) } }]) is there any way to wait until is_exsis() function to return value and then go to next line -
Why do django channels produce unexpected results sometimes?
I am developing a web socket based Django API which has 2 different API endpoints. For this, I am using Django channels with Redis as the backend channel layer. The first endpoint, /request will allow a user to start a request running on the server. It receives 2 parameters which are ConnID and Request Timeout. The second endpoint, /status will return a dictionary of all the running jobs with their remaining time. ex {'1':5, '2':34} Below is the consumer.py file from django.http import HttpResponse import json import time CONN_TIMEOUT = {} KILL_LIST = {} def _execute(message, connId, timeToSleep): global CONN_TIMEOUT, KILL_LIST CONN_TIMEOUT[connId] = timeToSleep KILL_LIST[connId] = 0 isKilled = False for i in range(0, timeToSleep): if KILL_LIST[connId] == 0: time.sleep(1) CONN_TIMEOUT[connId] -= 1 else: isKilled = True break CONN_TIMEOUT.pop(connId) KILL_LIST.pop(connId) if isKilled: message.reply_channel.send({'text':str('{\'status\':\'Killed\'}')}) else: message.reply_channel.send({'text':str('{\'status\':\'Ok\'}')}) def ws_message(message): global CONN_TIMEOUT print 'MSG' jsonObj = json.loads(message['text']) timeToSleep = int(jsonObj['time']) connId = jsonObj['connid'] print 'ConnID ' + connId + ' time: ' + str(timeToSleep) if CONN_TIMEOUT.get(connId) > 0: print 'Passing' pass else: print 'Starting new thread' _execute(message, connId, timeToSleep) def ws_kill(message): global KILL_LIST print 'KILL' print KILL_LIST jsonObj = json.loads(message['text']) connId = jsonObj['connid'] if KILL_LIST.get(connId) == 0: KILL_LIST[connId] = 1 message.reply_channel.send({'text':str('{\'status\':\'Ok\'}')}) else: message.reply_channel.send({'text':str('{\'status\':\'Invalid … -
Django Integrity Error while saving form
I extended the Django User Model and added my own fields, and am currently working on filling out these fields during registration. The form seems to be working correctly, with everything apart from the saving. I used this to help me. Here is the extension of the User Model: class StudentProfile(models.Model): user = models.OneToOneField(User, null = True, related_name='user', on_delete=models.CASCADE) teacher = models.BooleanField(default = False) school = models.CharField(max_length = 50) def create_StudentProfile(sender, **kwargs): if kwargs['created']: user_profile = StudentProfile.objects.create(user = kwargs['instance']) post_save.connect(create_StudentProfile, sender = User) Here is my Form: class StudentRegistrationForm(UserCreationForm): email = forms.EmailField(required = True) school = forms.CharField(required = True) def __init__(self, *args, **kwargs): super(StudentRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = '' self.fields['password2'].help_text = '' class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'school', 'password1', 'password2' ) def save(self, commit = True): user = super(StudentRegistrationForm, self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] student_profile = StudentProfile(user = user, school = self.cleaned_data['school']) if commit: user.save() student_profile.save() return user, student_profile Here is my view: def registration(request): if request.method == 'POST': form = StudentRegistrationForm(request.POST) if form.is_valid(): user, user_profile = form.save(commit = False) form.save() return render(request, 'accounts/home.html') else: args = {'form': form} return render(request, 'accounts/reg_form.html', args) else: form = … -
How to Configure Django on Oracle Http Server
I am new to Django and want to Configure Django on Oracle Http Server. Please help me in configuring Django over Oracle Http Server. I have installed python 3.4.6 and django 1.11 Oracle Http Server is also installed. I need to configure Django on one instance of Oracle Http Server. -
"Django_celery_beat" executes task only once
I am trying to integrate django_celery_beat in project. When I setup task using django admin panel entries in database are reflected correctly and when I start project task gets executed successfully. Whereas on every successive attempt of sending task is rather failed or either message is not sent to broker. My setup : django_celery_beat : 1.0.1 celery: 4.0.1 Setting in celeryconfig: CELERY_ENABLE_UTC = True BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' When I start celery I do get exception of : Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/celery/worker/pidbox.py", line 42, in on_message self.node.handle_message(body, message) File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 129, in handle_message return self.dispatch(**body) File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 112, in dispatch ticket=ticket) File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 135, in reply serializer=self.mailbox.serializer) File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 265, in _publish_reply **opts File "/usr/local/lib/python3.4/dist-packages/kombu/messaging.py", line 181, in publish exchange_name, declare, File "/usr/local/lib/python3.4/dist-packages/kombu/messaging.py", line 203, in _publish mandatory=mandatory, immediate=immediate, File "/usr/local/lib/python3.4/dist-packages/amqp/channel.py", line 1748, in _basic_publish (0, exchange, routing_key, mandatory, immediate), msg File "/usr/local/lib/python3.4/dist-packages/amqp/abstract_channel.py", line 64, in send_method conn.frame_writer(1, self.channel_id, sig, args, content) File "/usr/local/lib/python3.4/dist-packages/amqp/method_framing.py", line 174, in write_frame write(view[:offset]) File "/usr/local/lib/python3.4/dist-packages/amqp/transport.py", line 269, in write self._write(s) BrokenPipeError: [Errno 32] Broken pipe Logs in beat.stderr.log: [2017-06-12 05:40:00,002: INFO/MainProcess] Scheduler: Sending due task pooja_task (app.tasks.send_test_mail) [2017-06-12 05:41:00,002: INFO/MainProcess] Scheduler: Sending due task pooja_task … -
How do I set up a PostgreSQL database for use with PostGIS and GeoDjango?
The Django docs say to use createdb -T template_postgis geodjango but I already have a database set up. While trying to find out what this actually does and a way to apply it to an existing database, I found this on postgis.net: -- Enable PostGIS (includes raster) CREATE EXTENSION postgis; -- Enable Topology CREATE EXTENSION postgis_topology; -- fuzzy matching needed for Tiger CREATE EXTENSION fuzzystrmatch; -- Enable US Tiger Geocoder CREATE EXTENSION postgis_tiger_geocoder; In trying to figure out what Tiger is, I found this in the postgis docs: psql -d [yourdatabase] -c "CREATE EXTENSION postgis;" Topology is packaged as a separate extension and installable with command: psql -d [yourdatabase] -c "CREATE EXTENSION postgis_topology;" How do I ready my current Django database for use with PostGIS and GeoDjango? I'm using Django 1.8 and PostgreSQL 9.4. -
Django: Getting date conversion error while there is no datetime field.
Below is my dynamic sql generated by django. exec sp_executesql N'SET NOCOUNT ON; DECLARE @sqlserver_ado_return_id table ([Id] int); INSERT INTO [TaskHistory] ([TaskId], [Title], [Location], [Instructions], [Findings], [Suggestions], [Color], [ComplianceGroupId], [ClassificationId], [Priority], [Icon], [Comments], [UpdateSource], [Status], [TaskStatus], [ModifySource], [Action]) OUTPUT INSERTED.[Id] INTO @sqlserver_ado_return_id VALUES (@P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11, @P12, @P13, @P14, @P15, @P16, @P17); SELECT * FROM @sqlserver_ado_return_id',N'@P15 INT,@P2 NVARCHAR(MAX),@P9 INT,@P13 INT,@P17 NVARCHAR(MAX),@P8 INT,@P1 INT,@P4 NVARCHAR(MAX),@P14 INT,@P16 INT,@P5 NVARCHAR(MAX),@P6 NVARCHAR(MAX),@P11 INT,@P7 NVARCHAR(MAX),@P12 NVARCHAR(MAX),@P3 NVARCHAR(MAX),@P10 INT',@P15=2,@P2=N'some text title2',@P9=1,@P13=523,@P17=N'Created new Task',@P8=1,@P1=8,@P4=N'some instructions',@P14=2,@P16=523,@P5=N'some text based finding',@P6=N'some text based Suggestions',@P11=1,@P7=N'#ffffff',@P12=N'',@P3=N'event location',@P10=1 go but I am getting below error Conversion failed when converting date and/or time from character string. while there is no column in TaskHistory table -
Textblob logic help. NaiveBayesClassifier
I am building a simple classifier that determines sentences whether they are positive. this is how i train the classifier using textblob. train = [ 'i love your website', 'pos', 'i really like your site', 'pos', 'i dont like your website', 'neg', 'i dislike your site', 'neg ] cl.NaiveBayesClassifier(train) #im clasifying text from twitter using tweepy and it goes like this and stored into the databse and using the django to save me doing all the hassle of the backend class StdOutListener(StreamListener) def __init__(self) self.raw_tweets = [] self.raw_teets.append(jsin.loads(data) def on_data(self, data): tweets = Htweets() # connection to the database for x in self.raw_data: tweets.tweet_text = x['text'] cl.classify(x['text']) if classify(x['text]) == 'pos' tweets.verdict = 'pos' elif classify(x['text]) == 'neg': tweets.verdict = 'neg' else: tweets.verdict = 'normal' the logic seem pretty straightforward but when i trained the classifier which one is positive or negative it should saved the verdict along with the tweet into the database. But this doesnt seem the case and i have been altering the logic in many ways and still unsuccesful. The problem is if the tweet is positive or negative yes the algorithm does recognise that they are. However i want it to save 'normal' if they … -
how can i include my user id in email templates in django using MERGE TAGS?
href="http://beta.justrokket.com/profile/{{ request.user.profile.id }}/#tab2" I want to add a merge tag for the user id. How should i do this? -
Can I lookup a related field using a Q object in the Django ORM?
In Django, can I re-use an existing Q object on a related field, without writing the same filters twice? I was thinking about something along the lines of the pseudo-Django code below, but did not find anything relevant in the documentation : class Author(Model): name = TextField() company_name = TextField() class Book(Model): author = ForeignKey(Author) # Create a Q object for the Author model q_author = Q(company_name="Books & co.") # Use it to retrieve Book objects qs = Book.objects.filter(author__matches=q_author) If that is not possible, can I extend an existing Q object to work on a related field? Example : # q_book == Q(author__company_name="Books & co.") q_book = q_author.extend("author") # Use it to retrieve Book objects qs = Book.objects.filter(q_book) The only thing I've found that comes close is using a subquery, which is a bit unwieldy : qs = Book.objects.filter(author__in=Author.objects.filter(q_author)) -
Convert datetime printed by Django, to a different datetime format
My web application works with datetime(s) as timestamps, which according to Django's error messages need to be in the following format: YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]. I display these timestimes on multiple occasions on the web application, where they're displayed in the following format: 12. June 2017 10:17. Now, the user is able to choose and submit the displayed timezones, which are then processed by the server. The server then error's because the format isn't correct. How do I convert the format printed by Django on the web app (12. Juni 2017 10:17) to the format, required by Django for further processing (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ])? -
Disable data migrations in Django when creating test database
I have an app with a fair number of migrations including data migrations to set foreign keys on some models. When I try to run tests.py, it fails because the data migration is querying the database for data that doesn't exist in the test database. Is there a way to disable the data migrations? (I want to keep schema migrations). Or alternatively to load data from fixtures before running the data migrations? -
Serve a XLSX file django
I am creating a xlsx file in memory using openpyxl and i need to serve it to the user. This is what i'm using now in my views.py and it's working but it's serving me a xls file and that's not completely correct, i need it to be XLSX and i would also like to be able to set the name of the downloaded file. return HttpResponse(save_virtual_workbook(export_file), content_type='application/vnd.ms-excel') I did check out this question and this question but they don't help me too much. -
Error during template rendering in Django 1.11
Django Version: 1.11 Python Version: 3.6.1 I am trying to follow a Django tutorial on Openclassroom (Tuto), I have a problem that I can not solve, I can not remove this error Here is the traceback: File "C:\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\crepes\blog\views.py" in accueil 15. return render(request, 'blog/accueil.html', {'articles': articles}) File "C:\Python36\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py" in render_to_string 68. return template.render(context, request) File "C:\Python36\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Python36\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Python36\lib\site-packages\django\template\loader_tags.py" in render 72. result = block.nodelist.render(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Python36\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Python36\lib\site-packages\django\template\defaulttags.py" in render 216. nodelist.append(node.render_annotated(context)) File "C:\Python36\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Python36\lib\site-packages\django\template\defaulttags.py" in render 458. url = … -
How to insert emoji into MYSQL 5.5 and higher using Django ORM
I am trying to insert emoji's into a certain filed in my mysql table. I ran alter command and changed the collation to "utf8mb4_general_ci" ALTER TABLE XYZ MODIFY description VARCHAR(250) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; Table details after above query: +-------------+--------------+---------------+--------------------+ | Column | Type | Character Set | Collation | +-------------+--------------+---------------+--------------------+ | description | varchar(250) | utf8mb4 | utf8mb4_general_ci | +-------------+--------------+---------------+--------------------+ After this I ran the query to update description column with emoji's, every time I ran below query, the emoji is replaced by '?'. update XYZ set description='a test with : 😄😄' where id = 1; But when i print the result from a select query for the same id, it displays' '?' in place of emoji. The result was: "a test with : ??" Carried out necessary changes into model file. Please accept my Apologies for not making it clear, would appreciate any lead in this matter. -
ValueError: (Django1.11.1 python3.6.1 pycharm)
When I am trying to log in with the username and password set in the index.html, the error appeared as follow: ValueError at /login_action/ The view sign.views.login_action didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:8000/login_action/ Django Version: 1.11.1 Exception Type: ValueError Exception Value: The view sign.views.login_action didn't return an HttpResponse object. It returned None instead. Exception Location: D:\python3.6.1\lib\site- packages\django\core\handlers\base.py in _get_response, line 198 Python Executable: D:\python3.6.1\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\Administrator\\guest', 'D:\\python3.6.1\\python36.zip', 'D:\\python3.6.1\\DLLs', 'D:\\python3.6.1\\lib', 'D:\\python3.6.1', 'D:\\python3.6.1\\lib\\site-packages'] Server time: Mon, 12 Jun 2017 08:29:35 +0000 from the hint it said that the valut of HttpResponse object is none urls.py as follow from django.conf.urls import url from django.contrib import admin from sign import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$',views.index), url(r'^login_action/$',views.login_action), ] views.py as follow from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request,"index.html") # 登录函数定义 def login_action(request): if request.method == 'post': username = request.POST.get('username','') password = request.POST.get('password','') if username == 'admin'and password == 'admin123': return HttpResponse( '恭喜您,登录成功!') else: return render(request,'index.html',{'error':'用户名或者登录密码错误!'}) index.html as follow <html> <head> <title>欢迎登陆点米年会发布会系统</title> </head> <body> <h1>年会签名系统登陆<br> WELCOM TO DIAN MI</h1> <form method="post" action="/login_action/"> <input name="username" type="text" placeholder="用户名"><br> <input name="password" type="password" placeholder="登录密码"><br> <button … -
django upload files (models and forms)
I work on a group project with django. I have a problem with file upload. It is an web app to create, share forms with some additional options (graphs, charts,....). I should mention that i am new to django (total beginner) 1.models.py: class Form(TimeStampedModel, TitleSlugDescriptionModel): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=512) is_final = models.BooleanField(default=False) is_public = models.BooleanField(default=False) is_result_public = models.BooleanField(default=False) image = models.ImageField(upload_to="upload_location", null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) file = models.FileField(upload_to="upload location", null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('form-detail', kwargs={'slug': self.slug}) 2. forms.py: class DocumentUpload(forms.ModelForm): class Meta: model = Form field = ["image", "file"] 3. Certainly, i made a migration, changed main settings (urls, MEDIA_ROOT etc) 4. views.py THIS IS MY PROBLEM I try to modified existing "create_form(request)" function. In any tutorials we use "form = form from forms.py", In my project we use "form = model from models.py". How should I modify this this function to complete this upload files. def create_form(request): if request.method == 'POST': user = request.user data = ParseRequest(request.POST) parsed_form = data.form() parsed_questions = data.questions() form = Form(request.FILES, author=user, title=parsed_form['title'], is_final=parsed_form['is_final'], is_public=parsed_form['is_public'], is_result_public=parsed_form['is_result_public'], description=parsed_form['description']) form.save() for d in parsed_questions: question = Question(request.FILES, form=form, question=d['question']) question.save() for opt … -
Django ORM select_related AttributeError
In my project im trying to use an external .py file for manage data using my django app style like this: In my django project i create a model: class temp_test_keywords(models.Model): main_id = models.ForeignKey(temp_main) test_id = models.ForeignKey(temp_case) key_id = models.ForeignKey(temp_keywords) variable_id = models.ForeignKey(temp_variables, null=True, blank=True) def __str__(self): return '%s -> %s' % (str(self.main_id), str(self.test_id)) Well, now in my external rst.py file i start django env like this: import sys import os import django sys.path.append('core') os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings' django.setup() ok, at this point i import table and create class for do some thinks with it: from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation from django.contrib.contenttypes.models import ContentType from django.db.models import Count from frontend.models import temp_test_keywords class PrepareRst: def __init__(self,test_id,t_type,log=False): self.rst = self.mainprep(test_id,t_type) def mainprep(self,test_id,t_type): return self.tc_prep(test_id) #TestCase rst prep method def tc_prep(self,test_id): maxpar = temp_test_keywords.objects.filter(main_id = test_id).values('key_id').annotate(total=Count('variable_id')).order_by('-total').first() totpar = maxpar['total'] #Part1 list creation count = 0 ltouple = () l1 = ["Test Case"] while (count < totpar): l1.append("") count += 1 ltouple += (l1,) #Query for extract keywords, values kv = temp_test_keywords.select_related() but when i run an AttributeError: type object 'temp_test_keywords' has no attribute 'select_related' error raise if i start python manage.py shell from terminal the "kv = temp_test_keywords.select_related()" command works … -
MultiValueDictKeyError: "'password'"
My url is shown below like: url(r'^register/$', views.register, name='register') The function in my views.py is like: def register(request): """register""" if request.method != 'POST': #we present a blank form form = UserCreationForm() else: #the post the data the users have just filled form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # we use the date to redirect our user to the page of login authenticated_user = authenticate(username=new_user.username, password=request.POST['password']) login(request, authenticated_user) return HttpResponseRedirect(reverse('learning_logs:index')) context = {'form': form} return render(request, 'users/register.html', context) And my register.html: {% extends "learning_logs/base.html" %} {% block content %} <form action="{% url 'users:register' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button name="submmit">Register</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/> </form> {% endblock content %} when I do the register, it goes wrong like, MultiValueDictKeyError: "'password'" Can some one have a look and give me a hand? Thanks a lot! -
View not receiving POST data from image upload page
I've seen similar questions but can't figure this out, I have a program that upload pictures on a model: views.py: def upload_pic(request): if request.method == "POST": image_form = ImageUploadForm(request.POST, request.FILES) if image_form.is_valid(): image_form.save() return HttpResponse('success') else: return HttpResponse('fail') return render(request, 'tracker/upload_pic.html', {"image_form": image_form}) template: {% load staticfiles %} <!DOCTYPE html> <html> <body> <form method="POST" enctype="multipart/form-data">{% csrf_token %} {{ image_form.img }} <input type="submit" value="submit" /> </form> </body> </html> urls.py: urlpatterns = [ url(r'^upload_pic', views.upload_pic, name='upload_pic') ] Just trying to save to the user model so I can retrieve it later, but I can't access any POST data, I've also tried add action = "{% url upload_pic %}" to my form in the HTML template, but I get the NoReverseMatch error -
Customizing Rosetta Django interface.
I am working on a project that has extended the Django Admin Site and has included different styling for the templates. The project requires a translation extension, and I downloaded the Rosetta Django app, but now i want to also extend the Rosetta Django user interface to use the same styling that we have made for the customized admin site. Is there a way to do this?