Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache SetEnv Veriables Not Accessable by Django 1.11 mode_wsgi
I am trying to Pass a variable from Apache virtual host to django application. I want to access same application by different virtual hosts with single variable passed by apache to django. Here is my virtual host: <VirtualHost *:80> ServerName xyz.com ServerAlias www.xyz.com ServerAdmin admin@xyz.com ErrorLog /var/www/xyz.com/error.log CustomLog /var/www/xyz.com/access.log combined Alias /static /var/www/xyz.com/static SetEnv CAMPUS_ID '15' <Directory /var/www/xyz.com/static> Require all granted </Directory> <Directory /var/www/xyz.com/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess piscs processes=1 threads=15 python-path=/var/www/xyz.com display-name=%{GROUP} WSGIProcessGroup piscs WSGIScriptAlias / /var/www/xyz.com/project/wsgi.py </VirtualHost> And Here is My wsgi file. import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ['DJANGO_SETTINGS_MODULE'] = 'schoex.settings' from django.core.wsgi import get_wsgi_application _application = get_wsgi_application() def application(environ, start_response): os.environ['CAMPUS_ID'] = environ['CAMPUS_ID'] return _application(environ, start_response) And Here is Setting File CAMPUS_ID = os.environ['CAMPUS_ID'] Application is fully working with this wsgi file but without veriable: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "schoex.settings") application = get_wsgi_application() import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -
Intercooler.js - ic-target reloads intercooler-code and then is not working anymore
I am using intercooler.js in a django project. http://intercoolerjs.org <div id=right-side> <form ic-post-to="{% url 'update-task-ajax' %}" ic-target="#right_side"> [...] </form> </div> The form itself gets reloaded in the div #right-side after the first use and intercooler is not working anymore. How to fix this? Update: Looks like i have to use Intercooler.ready(func(elt)) http://intercoolerjs.org/reference.html But i'm stuck how to use it properly. -
ValidationError : [u'ManagementForm data is missing or has been tampered with'] on Django template page when I try to view my formset
Django version 1.8.7 I'm creating a pages where the user has to add a list of invitees to his weeding so I needed to use the same form many times on the same page to create mnay model instances of the invitees; In order to do that I used model formsets using modelformset_factory function . So in my forms.py class InviteesForm(ModelForm): class Meta: model = Invitees fields = ['user', 'invitee_name' , 'invitee_address', 'invitee_count', 'invitee_email'] exclude = ('user',) #creating a formset InviteesFormSet = modelformset_factory(Invitees, form = InviteesForm ) Above you can see my model form for the invitees model and my InviteesFormSet which uses modelformser_factory fucntion. In my views.py def preview(request): formset = forms.InviteesFormSet(queryset=Invitees.objects.all()) if request.method == 'POST': formset = forms.InviteesFormSet(request.POST) if formset.is_valid(): formset.save(commit = False) return redirect('/invitees/') else: formset = forms.InviteesFormSet(request.POST) return render(request, 'preview.html', {'formset': formset} ) In my Preview.html <form action="/preview/" method='POST'> {% csrf_token %} {{ formset }} <button type="submit">Add an Invitee</button> </form> The formset is not rendering in my html, am not sure what I'm doing wrong here, it's basic code! but I get this error [u'ManagementForm data is missing or has been tampered with'] Can you please help me figure out the issue? Thanks -
Foregin key field name is followed by _id
In a model, when a foreign key field is created then Django apparently create another field with the same field name followed by _id. for example if I have class Post(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default=None) dated = models.DateTimeField(auto_now=True) ... then I will have the following fields available: id,user,user_id,dated I am not sure why this field (user_id) was added? later I wanted to override my queryset in a class view so I was confused which one to use (user field or user_id field) : def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) and def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user=self.request.user.id) I tried both and both worked just fine My question is: 1) what is the purpose of creating this additional field ? 2) what is the difference between the original foreign key field (user in my case) and user_id field? 3) will this added field (user_id) only be visible to the database or user field also? 4) is the content identical in user and user_id for each record? if so ,then what the purpose of this additional field that was created automatically by django? Thanks a lot -
Why my edit form not updating data, but able to create new instance. I try every thing on google but still not working
I have a form for creating the object, and it works fine. When I use that form for editing the object, it doesn't work. I did debugging the post method,and it also works fine, the form is valid, the redirect work, the success message appear, but not update the object. The form instance is also work correctly. It just don't update *> #modals.py class Item(models.Model): status_choices = ( ('rent','Rent'), ('give', 'Give'), ('share','Share'), ) item_types = ( ('book','Book'), ('movie','Movie',), ('data','Data'), ('other','Other'), ) title = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, blank=True,unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL) cover = models.ImageField(upload_to='items/%Y/%m/%d',blank=True) link = models.URLField(blank=True) description = models.TextField(max_length=500, blank=True) status = models.CharField(max_length=10,choices=status_choices,default='Share') item = models.CharField(max_length=10, choices=item_types,default='Data', verbose_name='Item Type') publish = models.DateTimeField(auto_now=True,null=True) class Meta: ordering = ('-publish',) index_together = (('id', 'slug'),) def __str__(self): return '{} : <{}> for {}'.format(self.title,self.item,self.status) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Item, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('item_edit', kwargs={'slug':self.slug}) #forms.py class ItemShareForm(forms.ModelForm): class Meta: model = Item fields = ('title', 'cover', 'link', 'description', 'status', 'item') widgets = { 'description' : forms.Textarea(), } #views.py @login_required def item_edit(request,slug): instance = get_object_or_404(Item,slug=slug) if request.method == 'POST': #check the request method edit_form = ItemShareForm(request.POST ,instance=instance) if edit_form.is_valid(): # check the form validation update_item … -
TypeError: context must be a dict rather than HttpResponseRedirect
I'm using Django 2.0 and have been trying to redirect user to other view from get_context_data my url pattern is mainapp.urls urlpatterns = [ path('learn/', include('learn.urls', namespace='learn')), path('admin/', admin.site.urls), ] app.url app_name = 'learn' urlpatterns = [ path('success/<course_learn_id>/<session>', LearnSuccess.as_view(), name='success'), ] and LearnSuccess view class LearnQuestion(FormView): form_class = SessionForm template_name = 'learn/learn_question.html' def get_context_data(self, **kwargs): context = super(LearnQuestion, self).get_context_data(**kwargs) course_learn = CourseLearn.objects.get(pk=self.kwargs['course_learn_id']) session = self.request.GET['session'] question, question_type, options, complete = CourseLearn.objects.get_next_question(course_learn, session) if complete: return redirect('learn:success', course_learn_id=course_learn.pk, session=session) return context @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) I'm using Ajax to render this view and want to redirect user when complete is True But this is giving error as TypeError: context must be a dict rather than HttpResponseRedirect. I even tried return reverse() but it is also giving error. Trying return redirect('learn:success', kwargs={'course_learn_id':course_learn.pk, 'session':session}) gives error django.urls.exceptions.NoReverseMatch: Reverse for 'success' with keyword arguments '{'kwargs': {'course_learn_id': UUID('374ccfcd-37b5-40d3-8673-01ca111f42bc'), 'session': '1524972935'}}' not found. 1 pattern(s) tried: ['learn\\/success\\/(?P<course_learn_id>[^/]+)\\/(?P<session>[^/]+)$'] -
DjangoForm class meta override
i want to override the class Meta in the django forms. class MemberForm(forms.ModelForm): class Meta: model = Member fields = ["full_name"] .......... .......... here i want another form class with same functionality of above MemberForm with an addition field age . how can i achieve this. class EditMemberForm(MemberForm): class Meta: fields = super.Meta.fields fields = fields.append("age") -
How to receive celery tasks from another module
I can successfully receive celery tasks from my main app - however, my system cannot receive tasks from another module. I'm on a remote Ubuntu server using supervisor for for celery. draft1 is my main app and post is another module (the one that I can't receive tasks from). draft1/__init__.py #This will make sure the app is always imported when #Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] draft1/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'draft1.settings') app = Celery("draft1", broker=CELERY_BROKER_URL, include=['post']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) #post is in my installed apps draft1/tasks.py @periodic_task(run_every=timedelta(minutes=1)) def test_job(): from polls.models import Question for i in Question.objects.all(): if i.question_text == "test": i.question_text = "not_test" i.save() return HttpResponseRedirect('/') @periodic_task(name='run_scheduled_jobs', run_every=timedelta(seconds=30)) def run_scheduled_jobs(): return True post/tasks.py @periodic_task(name='test_post', run_every=timedelta(seconds=30)) def test_post(): from .models import Post for i in Post.objects.all(): if i.entered_category == "test": i.entered_category = "not_test" i.save() return HttpResponseRedirect('/') @periodic_task(name='post_jobs', run_every=timedelta(seconds=30)) # task name found! celery will do its job def post_jobs(): # do whatever stuff you do return True settings.py CELERYBEAT_SCHEDULE = { 'run_scheduled_jobs': { 'task': 'run_scheduled_jobs', # the same goes in the task name 'schedule': timedelta(seconds=45), }, 'test_job': { 'task': 'tasks.test_job', 'schedule': timedelta(minutes=3), }, 'post_jobs': { 'task': 'post.tasks.post_jobs', #i've also … -
Jinja: Could not parse the remainder
I've had a look and I can't find the answer to this. I'm trying to do a basic Jinja for loop in Django like this: {% for n in range(5) %} {{ n }} {% endfor %} But I get the error message: Could not parse the remainder: '(5)' from 'range(5)' I've followed the Jinja instructions so I don't know why it's doing this. This is my error page. -
Connect django+mongoengine to remote mongodb
I have a web app written in Django with mongoengine in a Digital Ocean droplet. During the developing step I used a sample of the main database that is located in a remote enviroment. But now I want to connect the Django web app to the main MongoDB database. How can I do this? With an ssh tunnel (I already use it between both environments)? If so, how do I do such connection? I know how to establish an ssh tunnel with pymongo: from sshtunnel import SSHTunnelForwarder import pymongo server = SSHTunnelForwarder( (remote_ip_address, 22), ssh_private_key="/home/username/.ssh/id_rsa", ssh_username="username", remote_bind_address=('127.0.0.1', 27017), ) server.start() client = pymongo.MongoClient('127.0.0.1', server.local_bind_port) But how do I do the equivalent connection with the Django web app? At the present moment I have the following definitions in the settings.py file. # MongoDB settings MONGODB_DATABASES = {'default': {'name':'dbname'} } DATABASES = {'default': {'ENGINE': 'django.db.backends.dummy'} } -
How do you unit test Django RawQuerySets
I'm using raw() and annotate() on a Django query and need some way to test it. Here's what my code looks like (this is simplified significantly) query = """SELECT table1.id, table1.column1, table1.column2, table2.other_column1, table2.other_column2 FROM myapp_mymodel as table1 JOIN otherapp_othermodel as table2 ON table1.othermodel_id = table2.id""" return MyModel.objects.annotate( other_column1=models.Value('other_column1', models.IntegerField()), other_column2=models.Value('other_column2', models.DateField()) ).raw(query) It's relatively straightforward to fill the database with sample data, but what's the best way to check that the data is returned by this code? There are a lot of options when dealing with standard querysets that seem to go out the window when dealing with RawQuerySets. -
Deleting an item in django after clicking a button in a pop up
I want to create a pop up which opens up clicking the button 'Dissolve'. The pop up should say: 'Are you sure you want to delete this field?' and have two buttons: Okay and Cancel. If Cancel is chosen it should simply close the pop up. If Okay is clicked, it should redirect to the previous page and delete that job on the previous page's table. My current code for the button is: <button type="button" class="btn btn-primary">Dissolve</button> My current code for the job in module.py is: class Job(models.Model): def __unicode__(self): return self.name name = models.CharField('Job Name',max_length=128) # when the job was created date_created = models.DateTimeField('Date Created', auto_now=True) # what entity/organization needs this job? client_organization = models.CharField('What organization do you represent?', max_length=64) # short description description = models.TextField('Job Description', max_length=256) # end product to be delivered deliverable = models.TextField('Deliverable', max_length=256) # when Job is due for completion duedate = models.DateTimeField('Date Due') # all persons who may be affected by project #stakeholders = models.TextField('Stakeholders') # important technical requirements #additional_information = models.TextField('Additional Information', blank = True) # budget estimate #budget = models.CharField('Budget', max_length=64) # file attachments #attachments = models.FileField(upload_to='job', blank = True) creator = models.ForeignKey(User,related_name = 'jobs') organizations = models.ManyToManyField(Organization, through = 'JobRequest', … -
Django serializer field not working
I did not reach a solution although I looked at the questions asked... When I add class MessageSerializer(ModelSerializer): sender = UserMobileSerializer(read_only=True) class Meta: model = Messages fields = '__all__' its working like this { "id": 62, "sender": { "pk": 12, "email": "john@gmail.com", "full_name": "John", "profile_photo": null }, "created_at": "2018-04-29T00:54:50.437662", "message": "sdkjnasljdhkajsjdlasdasda", "read_at": false, "target": 18 } My problem api results shows only target id when ı add this line target = UserMobileSerializer() I want to show UserMobileSerializer data like sender I also tried target = UserMobileSerializer(read_only= True) but nothing change? -
Inserting text using if else statement in HTML and Javascript
I am trying to insert the text 'Active'/'Deactive' depending on whether the value of jobs.active is True or False. My code gives no output though. Please help: <b> Status</b>: <script type="text/javascript"> if ({{job.active}}) { document.write("<b>Active</b>") } else { document.write("<b>Deactive</b>") } </script> -
Next page button not working same page is reloading
I have 6 posts in my database and I want to show 3 posts per page. Everything is working without any error but when I click 'next page' link, same posts are reloading. Here the steps, http://127.0.0.1:8000/blog/ is loading succesfully and there are 3 posts in page. Also, 'next page' link is also on the bottom of the page as expected. When I click nextpage, URL is changing into: http://127.0.0.1:8000/blog/?page=2 But as I said, first page's posts are reloading. url.py: path('',views.getPosts,name="bloghome"), path('/<int:selected_page>/',views.getPosts,name="bloghome"), view.py function about pagination: def getPosts(request,selected_page=1): posts = Posts.objects.all() pages = Paginator(posts,3) #Show 3 post per page try: returned_page = pages.get_page(selected_page) except EmptyPage: returned_page = pages.page(pages.num_pages) return render(request,'blog.html',{'page':returned_page, 'posts':returned_page.object_list }) Post listing page's template: {% extends 'blog_mainpage_assets.html' %} {%load static%} {% block document_body%} <div class="container" style="margin-top:40px;"> {%for post in posts%} <div class="post"> <div class="baslikveyazi"> <div class="baslik_2"> <h2><a href="{% url 'post_detail' post.slug %}">{{post.post_title}}</a></h2> </div> <div class="yazi_2"> <div style="word-wrap: break-word;"><p style="font-size:20px;line-height:2;">{{post.post_body|truncatechars:100}}</p></div> </div> </div> </div> {%endfor%} {% if page.has_previous %} <a href="{% url 'bloghome' %}?page={{page.previous_page_number}}">Back</a> {% endif %} {% if page.has_next %} <a href="{% url 'bloghome' %}?page={{page.next_page_number}}">Next</a> {% endif %} </div> {% endblock document_body%} -
Django-Filter: ModelChoiceFilter using queryset related to the current user
I have 2 models, Listing and ListingReview. I would like to be able to create a filter for the ListingReview model, so that people can select which Listing they want to see reviews for. # models.py: class Listing(models.Model): posted_by = models.ForeignKey('auth.User', related_name='listings', on_delete=models.CASCADE) class ListingReview(models.Model) listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name='listing_reviews') # filters.py def listings(request): # if request is None: # return Listing.objects.none() return Listing.objects.filter(posted_by=request.user) class ListingReviewFilter(django_filters.FilterSet): listing = django_filters.ModelChoiceFilter( name='listing', lookup_expr='isnull', empty_label='All listings', queryset=listings, ) class Meta: model = ListingReview fields = ['listing'] However, I don't understand why request is None, I get: 'NoneType' object has no attribute 'user' What I need: For a given user, find the associated Listings using: Listing.objects.filter(posted_by=user) and pass it to the queryset parameter in the filter. -
Object id is missing in Django framework when posted from AngularJS MongoDB
I am posting the following object { skillName : "Professional Skills" _id : {$oid: "5adf23946ab671bf6cb36aff"} } to the DjangoService given below: @csrf_exempt @api_view(['GET','POST']) def saveSubjectView(request): #this service will add & update Subject if request.method == 'POST': try: stream = StringIO(request.body) subject = JSONParser().parse(stream) print("The subejct is ") pp.pprint(subject) serializedsubject = json.loads(json_util.dumps(subject)) print("serializedsubject") pp.pprint(serializedsubject) The output that I am getting is 'skillType': { u'_id': { }, u'skillName': u'Professional Skills'} The ObjectId posted from the front end (AngularJS) is not printed in the service. I know that I can fix it by removing the $oid while posting from the AngularJS application. But I would like to know why this is not happening. I have searched the documents and I couldn't get a proper reply. May be the keywords I used are wrong. Keywords used are : "JSON serialisation of ObjectId", "$oid json serialization using Django". -
Passing JSON object for POST request Django REST Framework
I'm trying to make a POST request to one of my endpoints but it doesn't seem to be working. I used the same method with a similar endpoint and it worked but I keep getting a 404 request with these two: serialisers.py class GradesSerializer(serializers.ModelSerializer): cwk_id = serializers.CharField(source='Courseowork.id', read_only=True) cwk_title = serializers.CharField(source='Coursework.title') cwk_number = serializers.CharField(source='Coursework.number') student_id = serializers.CharField(source='Student.id', read_only=True) student_email = serializers.CharField(source='Student.email') student_username = serializers.CharField(source='Student.username') class Meta: model = Grades fields = ("id", "grade", "gradeMax", "gradePercentage", "Coursework", "Student", "cwk_id", "cwk_title", "cwk_number", "student_id", "student_email", "student_username") class ModuleSerializer(serializers.ModelSerializer): module_manager = serializers.CharField(source='ModuleManager.username') coursework = CourseworkSerializer(many=True) class Meta: model = Module fields = ("id", "title", "description", "credits", "code", "level", "Programme", "ModuleManager", "students", "coursework", "module_manager") views.py def post(self, request): serializer = ModuleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) models.py class Grades(models.Model): grade = models.IntegerField() gradeMax = models.IntegerField() gradePercentage = models.IntegerField() Coursework = models.ForeignKey(Coursework, null=True, on_delete=models.SET_NULL, related_name='coursework') Student = models.ForeignKey(Student, null=True, on_delete=models.SET_NULL, related_name='student') def __str__(self): return str(self.grade) class Module(models.Model): title = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000) credits = models.IntegerField(default=10) code = models.CharField(max_length=10) level = models.IntegerField(default=1) Programme = models.ManyToManyField(Programme, related_name="modules") ModuleManager = models.ForeignKey(Staff, null=True, on_delete=models.SET_NULL, related_name="module_manager") def __str__(self): return self.title + ' - ' + self.description + ' - ' + str(self.credits) I'm using APIView … -
How do I call my dict parameters from the view.py render in my template?
I have been working on this for two day, and have read almost every example on stackoverflow and consulted the django documentation. I am trying to pass my dict from the views.py to my template, but I keep getting the stupid "Could not parse the remainder" error. I'm not doing anything fancy. Just Href buttons passing in a parameter to represent what that button is. Then a template page opens using that parameter as a string to make the new page and url unique. pass in with: <a href="{% url 'site:call' 1 %}" class="btn">Call</a> urls.py urlpatterns = [ url(r'^call=(\d+)/$', views.call, name='call') ] views.py def call(request, callID): call_id = { 'id':callID } return render(request, 'site/call.html', call_id) Call template {% extends 'site/layout.html' %} {% block content %} {% with call_id.get('id') as view_id %} <h3 class="center-align blue lighten-3">Site # Room {{ view_id }}</h3> <a href="/site/cancel.html" class="btn">Cancel</a> {% endwith %} {% endblock %} I have tried request.GET.get('id') and a bizillion other things. Can someone show me how I can actually parse those dict values I passed in? -
CSRF tokens from Angular 4 to Django
This is a follow-up question to a question I asked yesterday: CSRF token in Angular 4 CLI from Django I have a backend Django server and a frontend Angular app. I am trying to submit a form in Angular to the Django backend with a POST. The problem is with CSRF tokens. This is the Django view: #@csrf_exempt def empty_form(request): if request.method=="POST": message = "Post" else: message = "Get" return JsonResponse({'message': message}) And this is the Angular component: send_sample_form() { let d = new Date(); d.setTime(d.getTime() + 1 * 24 * 60 * 60 * 1000); let expires:string = "expires=" + d.toUTCString(); let cpath:string = '/'; // this.cookieService.set('csrftoken', this.server_token, d, cpath, '127.0.0.1', false); this.cookieService.set('csrftoken', this.server_token); let my_headers = new HttpHeaders( { 'X-CSRFToken': this.server_token } ); this.http.post('http://127.0.0.1:8000/emptyform/', {'my_form': this.sample_form.value}, {headers: this.server_token, withCredentials: true}) .subscribe( (response) => { console.log(response); } ); } When the Angular and Django are separate servers (localhost:4200 and 127.0.0.1:8000), the angular code does not get the CSRF token. When I run it in production mode and so there is only the Django server at 127.0.0.1:8000, now the Angular component is able to extract the CSRF token with: ngOnInit() { this.http.get('http://127.0.0.1:8000/generate_token/', { observe: 'response' }) .subscribe( (response) => { … -
Django - how do I use Jinja to extend different headers to an html file?
I'm trying to extend different headers to an html page depending on whether a condition is true or not. The Jinja logic in the opening lines of my html file is: {% if user.active == 1 %} {% extends "dash/header.html" %} {% else %} {% extends "dash/limited_header.html" %} {% endif %} The above Jinja code returns a TemplateSyntaxError for the html page: Exception Value: Invalid block tag: 'else' What am I doing wrong? What is the most effective way to achieve what I am trying to do? -
Django-Python list saved in DB how to access in template?
I am getting data from an API and saved in models.py as part of learning Django. I got data and it is saved in db as it is. [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] Now when I try to access this data in template I getting this list only and not able to show it in a user friendly manner. I have tried: {% for data in datalist.items %} {{data}} {% endfor %} But result output in template html will be [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] I need something like RASH ERYTHEMATOUS, PAIN ,FEELING HOT ..... -
TypeError: 'User' object is not subscriptable
I am doing basic message app for users can send message other user... here my models.py class Messages(Model): created_at = DateTimeField(null=True, blank=True, auto_now_add=True, editable=False, verbose_name='Yaratılma Tarihi') message = TextField(max_length=500, verbose_name='Mesaj', null=True, blank=True, ) sender = ForeignKey('dentis.User', verbose_name='Gönderen', related_name='User') target = ForeignKey('dentis.User', verbose_name='Alıcı', related_name='target') read_at = BooleanField(default=False, verbose_name='Okundu', blank=True, ) class Meta: verbose_name = 'Mesaj' verbose_name_plural = 'Mesajlar' def __str__(self): return u'%s / %s/' % (self.sender.email, self.message[:15]) def get_type(self): return 'message' here my rest api views class MessageAPIView(ModelViewSet): serializer_class = MessageSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = MessageUserFilter permission_classes = (AuthenticatedUserOnly,) def get_user(self): if self.request.user.is_authenticated(): return self.request.user else: raise Http404 def get_queryset(self): messages = Messages.objects.filter( Q(sender=self.get_user()) | Q(target=self.get_user())).order_by('-created_at').distinct() return messages def perform_create(self, serializer): if self.request.user.is_authenticated(): try: target_email = serializer.validated_data['target']['email'] target = User.objects.get(email=target_email) except User.DoesNotExist: raise ValidationError('Hedef Kullanıcı bulunamadı') except KeyError: raise ValidationError('Hedef kullanıcı belirtilmedi') sender = self.request.user serializer.save(sender=sender, target=target) else: raise Http404 And my Serializers class MessageSerializer(ModelSerializer): sender = UserMobileSerializer(read_only=True) target = UserMobileSerializer() class Meta: model = Messages fields = '__all__' When I send a message then return this error: line 163, in perform_create target_email = serializer.validated_data['target']['email'] TypeError: 'User' object is not subscriptable [28/Apr/2018 18:56:04] "POST /api/v1/message/ HTTP/1.1" 500 15742 My usermodel use USERNAME_FIELD = 'email' not use username field -
update .po file in django without losing current translations
I use: django-admin makemessages -l fa_IR to update translation file. the process is going well without any issue. but when I run the command after translating .po file, all translations which have been done before will be erased and replaced with a fresh .po file. the .mo file is still available. -
Javascript doesn't work in the Django Template
I am trying to create a CSS modal for multiple images. The Javascript doesn't seem to be working, though. Where am I going wrong in the following code?: sometemplate.html: {% extends 'base.html' %} {% load staticfiles %} {% block styles %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="{% static 'photo.js' %}"></script> <link rel="stylesheet" href="{% static '/css/photos.css' %}" type="text/css"> {% endblock %} {% block content %} <div id="myModal" class="modal"> <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span> <img class="modal-content" id="img01"> <div id="caption"></div> </div> <img class="myImg" src="{% static 'images/angy1.jpeg' %}" alt="Normandy, France" width="300" height="200"> <img class="myImg" src="{% static 'images/angy2.jpeg' %}" alt="Delft, Holland" width="300" height="200"> {% endblock %} photo.js var modal = document.getElementById('myModal'); var img = $('.myImg'); var modalImg = $("#img01"); var captionText = document.getElementById("caption"); $('.myImg').click(function(){ modal.style.display = "block"; var newSrc = this.src; modalImg.attr('src', newSrc); captionText.innerHTML = this.alt; }); var span = document.getElementsByClassName("close")[0]; span.onclick = function() { modal.style.display = "none"; }