Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms with tiny mce
I created a form to send comments in Django, and I tried using tinymce to integrate it, I'll like to customize the editor to add more plugins,but whenever I add Javascript to my plain tinymce editor. The form vanishes. The javascript I tried to add: custom.js tinymce.init({ selector: 'textarea', height: 500, theme: 'modern', plugins: [ 'advlist autolink lists link image charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen', 'insertdatetime media nonbreaking save table contextmenu directionality', 'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc help' ], toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', toolbar2: 'print preview media | forecolor backcolor emoticons | codesample help', image_advtab: true, templates: [ { title: 'Test template 1', content: 'Test 1' }, { title: 'Test template 2', content: 'Test 2' } ], content_css: [ '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i', '//www.tinymce.com/css/codepen.min.css' ] }); my forms.py class CommentForm(forms.ModelForm): text = forms.CharField(help_text='Enter a Comment',widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) name = forms.CharField(widget=forms.HiddenInput(), initial="User") created_on = forms.DateTimeField(widget=forms.HiddenInput(), initial=timezone.now()) email = forms.CharField(widget=forms.HiddenInput(), initial="default@gmail.com") post = forms.CharField(widget=forms.HiddenInput(),initial="Post") class Meta: model = Comment fields = ('text',) html to render form <div class="content-form"> <h3>Leave a comment</h3> {% if user.is_authenticated … -
Get objects ManyToManyField
I have this models: class A(models.Model): afield1 = models.CharField(max_length=100) afield2 = models.ManyToManyField(B) class B(models.Model): bfield1 = models.CharField(max_length=100) bfield2 = models.CharField(max_length=100) And I want get the all objects afield2 related with B from B, something like this but fine elementa = comm_models.A.objects.filter(bfield1 ="example") all = comm_models.B.objects.filter(a__afield2=elementa) Any ideas? thanks in advance. -
Nginx, gunicorn, ubuntu 16.06 - uploaded images not displaying
fellow humans I have been on this issue for a couple days and would really appreciate some help. So I successfully deployed my app and everything works fine including css and the javascript except for this little thing which Im sure is just a little fix i am missing, resulting to my uploaded images not displaying even tho i see the "upload successful" page. My image model class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=2000) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='/home/kingiyk/stylplus/media/') description = models.TextField(blank=True, null=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) tags = TaggableManager() class Meta: ordering = ('-created',) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('images:detail', args=[self.id, self.slug]) my nginx conf server { listen 80; server_name 67.207.87.22; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/kingiyk/stylplus/static; } location /media/ { alias /home/kingiyk/stylplus/media; } location / { include proxy_params; proxy_pass http://unix:/home/kingiyk/stylplus/stylplus.sock; } } my uploaded images are located in /home/kingiyk/stylplus/media/ so atleast i know they were saved. here is my settings file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False ALLOWED_HOSTS = ['67.207.87.22', 'styllplus.com', 'www.styllplus.com'] ROOT_URLCONF … -
Filtering ModelForm in django shows empty choice in web form
I know that this topic was covered here already, but please bare with me. I am trying to filter some choices by Djangos stock Groups, but when I do so in web form is empty. If I put Group number directly when filtering, it works. Maybe I have something wrong with arguments? in views.py I have: class AddSupplier(generic.View): form_class = CreateOrder template_name = 'order/order_form.html' #blank, ce je get metoda def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): group = self.request.user.groups.values_list('id', flat=True).first() # I tried: # group = self.request.user.groups.all() # same result form = self.form_class(group, request.POST) if form.is_valid(): createS = form.save(commit=False) supplier = form.cleaned_data['supplier'] createS.save() return render(request, self.template_name, {'form': form}) forms.py class CreateOrder(forms.ModelForm): def __init__(self, group,*args,**kwargs): super (CreateOrder, self ).__init__(*args,**kwargs) self.fields['supplier'].queryset = Supplier.objects.filter(group_s=group) # if I put group = 1 it works class Meta: model = Order fields = [ 'supplier', ] and how thinks are connected in models.py: class Supplier(models.Model): #... group_s = models.ManyToManyField(Group, help_text="kateri dobavitelji imajo katere stranke") #... class Order(models.Model): #... supplier = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True) #... -
I want to make a chatbot for website using python and Django
I want to make chatbot for the website like a chatbot in the Microsoft's official website.. I want to do this using Django and python. Please guide and tell me that can i use my fb bot in the website? if yes then how? Your comments will be very precious for me... Thanx in advance.. -
pycharm Community edition
PyCharm Community edition I wanna use Python coding in HTML file. {% for album in all_album %} it treated as normally only. I want it to treat as python code. if and for is not treated as Python code -
install django in virtualenv python3.4 with linux os in virtualenv
I am getting this error when importing django inside python : ImportError: No module named 'django' I've got a problem when installing django in my web server aws, I made an alias python = python3 so when I am working with python it is python 3.4 which is executing. I made a virtual env with it, but when I install django even inside the virtual env, it is installing in the python 2.7 version, not in my virtualenv, and not with the python3 version. does anyone knows how to make really my python3 as default or how I can install django in the correct folder (python3) -
Unusual request activity log found in django server
Following is the screenshot of the server activity log.I can see that many requests are automatically raised in the server.How can I avoid this.? -
Python Social Auth - User is authenticated with facebook but cannot access pages
I have an issue with Facebook authentication with Python Social Auth. I have login with Facebook, Google and Twitter. After login, I redirect the user to my dashboard at /user/dashboard with the use of login_redirect decorator. While it works fine with Google and Twitter, I am not able to redirect the user authenticated with Facebook. @login_required def home(request): user = "" if '_auth_user_id' in request.session: user = AuthUser.objects.get(id=request.session['_auth_user_id']) template = 'user/index.html' return render(request, template, context) In Settings.py SOCIAL_AUTH_FACEBOOK_KEY = '******' SOCIAL_AUTH_FACEBOOK_SECRET = '*******' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'public_profile', 'user_location'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'locale': 'en_US', 'fields': 'id, name, email, age_range, about, picture, location' } SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.10' When I remove the login_required decorator, the user is redirected to the dashboard. But when the user tries to go to another page, there django says user is not authenticated. Is this an issue with the Facebook API or the application? Thanks for any replies. -
Integrity error when adding manytomany relationship through intermediary table
class Operation(models.Model): Operation_Name = models.CharField(max_length = 100) class Doctor(models.Model): Name = models.CharField(max_length = 100) Related_Operations = models.ManyToManyField(Operation,through='Unique_Operation_Doctor_Patient_Relation') def __str__(self): return self.Name class Unique_Operation_Doctor_Patient_Relation(models.Model): # the doctor and the operation Concerned_Doctor = models.ForeignKey(Doctor) Concerned_Operation = models.ForeignKey(Operation) # Attributes of the operation Date = models.DateTimeField(db_index = True) Tooth_Surface = models.IntegerField(db_index = True) Amount = models.IntegerField(db_index = True) Concerned_Patient = models.ForeignKey(Patient,db_index = True) Idtag = models.AutoField(primary_key = True,default = 200000,db_index = True) The following is a many to many relationship between two models Doctor and Operation through an intermediary model . I have also added a foreign key field to link it to a patient so that i can access a patient records. I created a form for the intermediary model. In this model i save the doctor and patient relationships, but i only add the relation to the patient in the view function. class Try_Form(forms.ModelForm): class Meta: model = Unique_Operation_Doctor_Patient_Relation fields = ['Concerned_Doctor','Concerned_Operation','Concerned_Patient','Date','Tooth_Surface','Amount',] help_texts ={ 'Date': ' (YYYY-MM-DD)', } New_Operation_Name = forms.CharField(max_length = 100) New_Doctor_Name = forms.CharField(max_length = 100) field_order = ['Date','Tooth_Surface','Amount','Concerned_Operation','New_Operation_Name','Concerned_Doctor','New_Doctor_Name','Concerned_Patient'] def __init__(self,*args,**kwargs): super(Try_Form,self).__init__(*args,**kwargs) self.fields['Concerned_Doctor'].required = False self.fields['Concerned_Operation'].required = False self.fields['Concerned_Patient'].required = False def clean(self): # The connected doctors. Creating new Doctors if they don't exist and connecting them. The same … -
How to spell correctly Django's for statement in pug.js' template?
When I try to compile this: doctype html html(lang="en") head meta(http-equiv = "Content-Type " content ="text/html ;charset=utf-8") title = category.name body h1 Сьпiс таварау h2 Катэгорыi: ul for cat in cats li: a(href='/goods/{{cat.id}}/') {{cat.name}} endfor h2 Тавары table tr th Назва th Есьць у наяунасьцi for good in goods tr td a(href = '/goods/good/{{good.id}}/'){{good.name}} endfor I get this error: Error: index.pug:10:7 8| h2 Катэгорыi: 9| ul > 10| {% for cat in cats %} --------------^ 11| li: a(href='/goods/{{cat.id}}/') {{cat.name}} 12| endfor 13| h2 Тавары unexpected text "{% fo" at makeError (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-error/index.js:32:13) at Lexer.error (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:58:15) at Lexer.fail (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:1304:10) at Lexer.advance (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:1364:15) at Lexer.callLexerFunction (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:1319:23) at Lexer.getTokens (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:1375:12) at lex (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-lexer/index.js:12:42) at Object.lex (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug/lib/index.js:99:27) at Function.loadString [as string] (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug-load/index.js:44:24) at compileBody (/home/ivan/Documents/node-v6.11.0-linux-x64/lib/node_modules/pug-cli/node_modules/pug/lib/index.js:86:18) Initially I thought that this for cat in cats will normally compile into {% for cat in cats %} , like it does with if statement, but it seems like pug.js requires some more special syntax, which I couldn't find on pugjs.org, though here the syntax presented on Pugjs official website is similar to mine: for a in b = a -
How can I make different panel of users in Django?
I have to design a webapp where there types of user are available, firstly being a normal user(customer), second being a dietician(to whom customer can interact) and third being the docters (whom dieticians will contact for any reference but user cannot contact them) . Further doctors can see all the dieticians and users but can interact with only dietician. User module (UM) a. to be accessed by user b. all changes should be possible from AM c. all pages should be <100 KB to ensure that they can open on 2G First of all, dietician will be single point of contact for client at all times. This means that client will only interact with dietician and dietician will get all help that is required from either doctor or naturopath at back end. Panel Module (PM) a. to be used by panel members to send / receive clients notifications b. to be used by panel members to upload and send content for clients Dietician, Doctor and Naturopaths will all have separate logins and access capability. While all can view what a particular client has communicated, the client's doctors and naturopaths can communicate to dieticians and only dietician can communicate to client. … -
.objects.all() query not working in Django
I am developing a website which is based on information about books and i want to display all the authors present in the 'Authors' table in an HTML page. When i click on the link "authors", the page is not rendered and it gives an error "User matching query does not exist." (Not letting me post the image here). This is the traceback from the terminal. Internal Server Error: /books/authors/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Pallav\PycharmProjects\onlineBookStore\onlineBookStore\books\views.py", line 35, in follow_user user_to_be_followed = User.objects.get(username=user_id) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name DoesNotExist: User matching query does not exist. I tried running the query in python manage.py shell and it yields a proper query set. My url is: url(r'authors/$', views.authors, name='authors'), My View function is: def authors(request): all_authors = Authors.objects.all() return render(request, 'books/authors.html', {'all_authors': all_authors}) My Html page is: {% extends 'books/base.html' %} {% block title %}All authors{% endblock %} {% block body %} <div class="users-container container-fluid"> <!-- Books --> <div … -
Django test runner with multi threaded live server and custom sql_flush function
I am trying to use this snippet to implement threaded server for my django test runner. We have custom sql_flush function which we want to call after each test-case execution. It works fine when I am not using above snippet(no multi threaded approach), but when i put above snippet to my settings file, the default sql_flush is called from django library. Below is the code snippet. Can you help me fixing this? from django.core.servers.basehttp import WSGIServer from django.test import testcases from django.utils.six.moves import socketserver testcases.WSGIServer = type(str('WSGIServer'), (socketserver.ThreadingMixIn, WSGIServer), {}) from django.core.management import sql sql.sql_flush = sql_flush_without_cms #this is custom flush function -
Django, channel layer reloads after exception
I use django channels and get this exception when receive message: 2017-07-27 08:34:56,241 - DEBUG - worker - Got message on websocket.receive (reply daphne.response.key) 2017-07-27 08:34:56,242 - DEBUG - runworker - websocket.receive 2017-07-27 08:34:56,242 - DEBUG - worker - Dispatching message on websocket.receive to project.consumers.ws_message Traceback (most recent call last): File "/project/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/channels/management/commands/runworker.py", line 83, in handle worker.run() File "/usr/local/lib/python2.7/dist-packages/channels/worker.py", line 151, in run consumer_finished.send(sender=self.__class__) File "/usr/local/lib/python2.7/dist-packages/django/dispatch/dispatcher.py", line 193, in send for receiver in self._live_receivers(sender) File "/usr/local/lib/python2.7/dist-packages/channels/message.py", line 105, in send_and_flush sender.send(message, immediately=True) File "/usr/local/lib/python2.7/dist-packages/channels/channel.py", line 88, in send self.channel_layer.send_group(self.name, content) File "/usr/local/lib/python2.7/dist-packages/asgi_ipc/core.py", line 130, in send_group for channel in self.group_channels(group): File "/usr/local/lib/python2.7/dist-packages/asgi_ipc/core.py", line 137, in group_channels return self.group_store.flush_expired(group) File "/usr/local/lib/python2.7/dist-packages/asgi_ipc/store.py", line 188, in flush_expired for item, expiry in value[name].items() KeyError: u'None' 2017-07-27 08:34:57,719 - INFO - runworker - Using single-threaded worker. 2017-07-27 08:34:57,719 - INFO - runworker - Running worker against channel layer default (asgi_ipc.core.IPCChannelLayer) 2017-07-27 08:34:57,719 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive ws_message code: … -
How to update instances synchronously in Django models?
I have 2 models: class TranslatedLesson(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) amount_steps = models.IntegerField(default=0) class TranslationStep(models.Model): lesson = models.ForeignKey(TranslatedLesson, on_delete=models.CASCADE, related_name="steps") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) @receiver(post_save, sender=TranslationStep, dispatch_uid="update_lesson_date") def update_lesson_date(sender, instance, **kwargs): lesson = instance.lesson lesson.update_date = instance.updated_at lesson.save() Every time I update TranslationStep model, I wanna update updated_at time, which TranslatedLesson has. But the code above gives me different results, as lesson is saved futher a little bit. Even if I delete auto_now=True and override .save method it doesn't give desired result. >>> step.updated_at datetime.datetime(2017, 7, 27, 7, 59, 24, 912420, tzinfo=<UTC>) >>> lesson.updated_at datetime.datetime(2017, 7, 27, 7, 59, 24, 919461, tzinfo=<UTC>) How to perform update synchronously? -
Pulling data from MySQL to display on dashboard using python django-dashing
I was trying to implement a dashboard by following the instructions of https://github.com/talpor/django-dashing/ using django-dashing. So far I have successfully customised my widget and displayed with some random data on my own web-server, while I have no clue where to start if I'd like to pull some real data from db(MySQL) and display. (like where to do the db connecting,..etc) Could anyone show me steps I should follow to implement it? -
How to use djando-table2 with class based view to display data from multiple table?
models.py class DailyRecordManager(models.Manager): def get_query_set(self): qs = super(DailyRecordManager, self).get_query_set().order_by('date_organised') return qs class DailyRecord(models.Model): date_organised = models.DateField('Ogransied Date', help_text=('Enter Date when the program is organised: CCYY-MM-DD')) program_name = models.TextField('program name',) venue = models.CharField('venue', max_length = 255, blank=True) organiser = models.ForeignKey(Organiser, verbose_name = 'Organiser', related_name = 'organisers') objects = models.Manager() public = DailyRecordManager() class Meta: verbose_name = 'dailyrecord' verbose_name_plural = 'dailyrecords' ordering = ['-date_organised'] def __str__(self): return self.program_name class Participant(models.Model): participant = models.CharField(max_length= 50, unique = True) daily_record = models.ForeignKey(DailyRecord, verbose_name = 'program_name') class Meta: verbose_name = 'participant' verbose_name_plural = 'participants' def __str__(self): return self.participant views.py class DailyActivityPageView(SingleTableView): table_class = DailyRecordTable queryset = DailyRecord.public.all() # queryset = Participant(DailyRecord.public.all()) is not working template_name = 'dailyrecord/daily-activity-record.html' tables.py class DailyRecordTable(tables.Table): date_organised = tables.Column('Date') program_name = tables.Column( 'Program Name') venue = tables.Column( 'Venue') organiser = tables.Column( 'Organiser') participant = tables.Column( 'dailyrecord.participant') # daily = tables.RelatedLinkColumn() class Meta: model = DailyRecord Now I need is that I want to display the data from participant table too corresponding to the daily_record foreign key. Click this link to view the snapshot. see the last column of the table. I need the data of Participant.partcipant column here Sorry for poor English. Thank You -
ValueError: invalid literal for int() with base 10 Foreign Key Django
I'm learning Django. I have two models as follows: class IdentificationAddress(models.Model): id_ident_address = models.AutoField(primary_key=True) ident = models.ForeignKey('Ident', models.DO_NOTHING, db_column='ident') address = models.TextField() time = models.DateTimeField() class Meta: managed = False db_table = 'identification_address' class Ident(models.Model): id_ident = models.AutoField(primary_key=True) ident = models.TextField(unique=True) name = models.TextField() class Meta: managed = False db_table = 'ident' I am using the Django debugger: python manage.py shell and import the model from invent.models import Ident as identity from invent.models import IdentificationAddress as ident_Address I can access the name of a specific identity indentity.objects.filter(ident='00LD').values('name') it returns <QuerySet [{'name': u'Joss'}]> Then I can access information of a specific address: ident_Address.objects.filter(address='LOC23').values().last() it returns {'times': u'{"2017-07-16"}', u'ident_id': u'00LD', 'address': u'LOC23', 'id_ident_address': 217} but I get an error when I try to use any identity ident_Address.objects.filter(ident='00LD').values() or ident_Address.objects.filter(ident_id='00LD').values() error: ValueError: invalid literal for int() with base 10: '00LD' If I try this in postgres SELECT * FROM identification_address WHERE ident= '00LD' I don't have any problem. I appreciate any help. Thank you in advance -
How to assign dropdown data to a field after importing data from view
I am creating a dropdown in forms.py and to filter data I am getting a variable named layer_id . And getting in view like this layer_id = kwargs['layer_id'] . All things are good but when I assign on end to filed like this self.fields['apn'].queryset= Field.objects.filter(layer=layer) . Call goes to fields table of database rather then assigning these fields I declared in forms.py. So who can I assign to fields in forms.py class labelModelForm(forms.ModelForm): model = Labels_tool_ fields = ['apn', 'owner_name', 'situs_addr_One', 'situs_addr_Two', 'mailing_addr_One', 'mailing_addr_Two'] apn = forms.ModelChoiceField(queryset=Field.objects.values_list('name', flat=True), empty_label="(Choose field)") def __init__(self, *args, **kwargs): //getting layer_id from views layer_id = kwargs['layer_id'] print layer_id layer=Layer.objects.filter(id=layer_id).first() x=Field.objects.filter(layer=layer) //On this step when modify queryset I get error self.fields['apn'].queryset= Field.objects.filter(layer=layer) -
Django Rest_Framework: call delete method in a template
I'm trying to convert the example app from the Rest Framework tutorial to the an app with templates. The problem is that I cannot create a delete button in a detail view of a single record. My views.py are as follows: class SnippetViewSet(viewsets.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) renderer_classes = [renderers.TemplateHTMLRenderer] template_name = 'list.html' def list(self, request, **kwargs): print(request.method, request.user) queryset = Snippet.objects.all() serializer = SnippetSerializer(context={'request': request}) return Response({'queryset': queryset, 'serializer': serializer}, template_name='list.html') def retrieve(self, request, *args, **kwargs): print(request.method, 'retrieve') queryset = self.get_object() serializer_class = SnippetSerializer(queryset, context={'request': request}) return Response({'queryset': queryset, 'serializer': serializer_class}, template_name='retrieve.html') def create(self, request, *args, **kwargs): print(request.method, 'create') serializer = SnippetSerializer(instance=None, context={'request': request}, data=request.data) if serializer.is_valid(): serializer.save(owner=self.request.user) return redirect('snippet-list') def post(self, request, *args, **kwargs): print(request.method, 'post') queryset = self.get_object() serializer = SnippetSerializer(queryset, data=request.data, context={'request': request}) if not serializer.is_valid(): return Response({'serializer': serializer, 'queryset': queryset}) serializer.save() return redirect('snippet-list') def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete() urls.py remained unchanged: snippet_list = SnippetViewSet.as_view({ 'get': 'list', 'post': 'create', }) snippet_detail = SnippetViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy', }) user_list = UserViewSet.as_view({ 'get': 'list'}) user_detail = UserViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns … -
comparing forloop counter in django with a variable
I want to divide a queryset into two sections on the left and right by comparing length of queryset. I am doing something like : {% widthratio questions|length 2 1 as half_list %} % for question in questions %} {% if forloop.counter < half_list %} -- body -- Here the if condition works when static integer is given like : {% if forloop.counter < 4 %} how to compare it with variable half_list? -
Azurewebsite django URL rewrite for another application
I've installed wordpress in Azurewebsites which is primarily running Django. I've set up an application as /blog to /site/wwwroot/blog in application setting. But web.config is not serving the url www.example.com/blog instead it's throwing 404 error. Here's the web.config, could you suggest how to disable rewrite for www.example.com/blog <?xml version="1.0"?> <configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> </listeners> </trace> </system.diagnostics> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_venv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <!-- <add key="WSGI_PTVSD_SECRET" value="" /> --> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> <!-- Required for websockets. --> <httpRuntime targetFramework="4.5"/> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="Python340_via_FastCGI" /> <add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule" scriptProcessor="D:\Python34\python.exe|D:\Python34\Scripts\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> <!-- Uncomment the following handler to enable remote debugging. --> <!-- <add name="ptvsd" path="ptvsd" verb="*" resourceType="Unspecified" type="Microsoft.PythonTools.Debugger.WebSocketProxy, Microsoft.PythonTools.WebRole"/> --> <!-- <clear/> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="File" requireAccess="Read" /> --> </handlers> <rewrite> <rules> <!-- Uncomment the following rule to enable remote debugging. --> <!-- <rule name="ptvsd" enabled="true" stopProcessing="true"> <match url="^ptvsd(/.*)?$"/> </rule> --> <rule name="Static Files" stopProcessing="true"> <conditions> <add input="true" pattern="false" /> </conditions> </rule> <rule name="Configure Python" stopProcessing="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{REQUEST_URI}" pattern="^/static/.*" ignoreCase="true" negate="true" /> … -
" 'str' object has no attribute 'utcoffset' " django admin
In my django admin, getting this error "'str' object has no attribute 'utcoffset'" when i open an exsisting entry from the django admin list view screen. My model has a datetimefield, if I saved the form without filling this datetimefield I am able to open it from the list view screen but if I gave value for this datetimefield this error is coming. Models.py class JVEmployee(models.Model): CoCode = models.CharField(max_length=10, null=True, blank=True) Entity = models.CharField(max_length=50, null=True, blank=True) FirstName = models.CharField(max_length=50, null=True, blank=True) LastName = models.CharField(max_length=50, null=True, blank=True) EmpID = models.CharField(max_length=10, null=True, blank=True) FirstName1 = models.CharField(max_length=50, null=True, blank=True) LastName1 = models.CharField(max_length=50, null=True, blank=True) EmpID1 = models.CharField(max_length=10, null=True, blank=True) WBSElement = models.CharField(max_length=30, null=True, blank=True) Comments = models.CharField(max_length=250, null=True, blank=True) ValidFrom = models.DateTimeField(null=True, blank=True) MaterialityLimitMin = models.CharField( max_length=10, null=True, blank=True) MaterialityLimitMax = models.CharField( max_length=10, null=True, blank=True) admin.py @admin.register(JVEmployee) class JVEmployeeAdmin(admin.ModelAdmin): list_display = ( 'id', 'EmpID', 'CoCode', 'FirstName', 'WBSElement', 'Comments') search_fields = ('EmpID', 'FirstName', 'CoCode') -
compare forloop.counter with division operation django
I want to divide a queryset into two sections by comparing length of queryset. I am doing something like : {% widthratio questions|length 2 1 as half_list %} % for question in questions %} {% if forloop.counter < half_list %} -- body -- Here the if condition works when static integer is given like : {% if forloop.counter < 4 %} how to compare it with variable half_list?