Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
run scrapy from bash and implement it in django
I have a bash script to run a scrapy crawler and that crawler it passes some raw_inputs it asks me the url and the domain and i type them in the command line. now i want to implement that bash script and crawler in a django template. I want that template to collect the url and the domain and send it to the crawler. How can i do it? this is part of my bash script #!/bin/bash cd /.../seo/ PATH=$PATH:/usr/local/bin:/home/omega/.local/bin/ export PATH scrapy crawl test -
Django messages not showing after redirect
I have this piece of code in my view: if _user.objects.user_exists(_email): auth.logout(request) messages.success(request, 'You already hold a verified account with us. Please login.') return redirect('accounts:login') and this in my template: {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} This sadly wouldn't work. But if I change return redirect('accounts:login') to return render(request, 'accounts/login.html'), the message would display. So what is it that's preventing the messages from showing up during a redirect? And for the message storage, I am using: MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' Thanks for the help. -
Task IndexError('string index out of range',) in celery
I have created an asynchronous email sending to the job poster when job seeker applies for the job using celery and rabbitmq. I have used smtp(gmail) for email service.However I am getting an error which I could not figure out where exactly is the error coming from and how do i resolve it. The error is something like this Task job.tasks.send_resume_to_job_poster[a1d2f76e-5e38-4560-8576-0c43accff696] raised unexpected: IndexError('string index out of range',) Here is my code In a nutshell what I am doing is, I am generating the pdf from the html template and sending an email to the job poster but for testing I am using seeker email @shared_task def send_resume_to_job_poster(poster, seeker): resume = User.objects.get(email=seeker).resume html = render_to_string('resume/resume.html', {'resume': resume}) out = BytesIO() response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'filename="resume_{}.pdf"'.format(resume.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + '/css/pdf.css')]) # create resume email subject = "{} has applied for the job".format(resume.name) from_email = settings.EMAIL_HOST_USER to_email = [seeker] job_message = "if you don't want to recieve such message please we can't do anything for you." email = EmailMessage( subject, job_message, from_email, [to_email] ) email.attach("resume_{}.pdf".format(resume.id), out.getvalue(), 'application/pdf') return email.send() Error log in detail [2017-09-27 11:48:23,301: WARNING/ForkPoolWorker-1] html [2017-09-27 11:48:23,302: WARNING/ForkPoolWorker-1] <html> <head> <title>Tushant Khatiwada</title> </head> <body> <h1>Tushant Khatiwada</h1> <h3>Django … -
Use list(map(model_to_dict, queryset_list)) do not map the createtime and updatetime fields
I have a Test04 Model, and I give ctime and uptime fields. class Test04(models.Model): testTime = models.DateTimeField(null=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) But when I use the list(map(model_to_dict, queryset_list)) method to convert the queryset to dictionary, I find the ctime and uptime do not convert: from django.forms.models import model_to_dict print (models.Test04.objects.all()) all =models.Test04.objects.all() print (all[0].ctime) # 2017-09-26 07:49:02.012489+00:00 print (list(map(model_to_dict, all))) # [{u'id': 1, 'testTime': datetime.datetime(2017, 9, 26, 7, 49, 1, 973016, tzinfo=<UTC>)}, {u'id': 2, 'testTime': datetime.datetime(2017, 9, 26, 8, 3, 24, 665944, tzinfo=<UTC>)}, {u'id': 3, 'testTime': datetime.datetime(2017, 9, 26, 0, 12, 12, 683801, tzinfo=<UTC>)}, {u'id': 4, 'testTime': datetime.datetime(2017, 9, 26, 0, 12, 43, 2169, tzinfo=<UTC>)}, {u'id': 5, 'testTime': datetime.datetime(2017, 9, 26, 8, 13, 16, 164395, tzinfo=<UTC>)}, {u'id': 6, 'testTime': datetime.datetime(2017, 9, 26, 0, 14, 8, 812063, tzinfo=<UTC>)}, {u'id': 7, 'testTime': datetime.datetime(2017, 9, 26, 0, 15, 32, 945493, tzinfo=<UTC>)}] In the last line's output, you see there is no ctime and uptime in every dictionary. -
Django save base64 string to filesystem using models.ImageField
I am trying to upload image to file system using python django. I dont have any idea on how to proceed further. in my model.py: Class Test(object): mission = models.TextField(blank=True) image = models.ImageField(upload_to='documents/images/',blank=True) account = models.OneToOneField(Account, related_name='account') in my view.py def add_image(request, account): req = get_request_json(request) data = Test.objects.add_image(account, req) in my manager.py Class TestManager(models.Manager): def add_image(self, account, input): acc = self.get(account=account) acc.save() return acc; But I am not sure how to proceed from here. I would like to know how to save the base64 image string to the specified location and store the path/file name in database? I have worked with python where I write the files to a directory and get the path and store in db. Here I want to use the django options. I have to repeat the same process with other file formats too. -
Timestamp TruncHour aggregation in Django
I have a data with peoplecount and timestamp which I want to show aggregated in an hour wise format.The model for peoplecount object is like below: class PeopleCount(models.Model): """ A webapp model classs to store People Count Details. """ timestamp = models.DateTimeField(auto_now=True) people_count_entry = models.IntegerField(blank=True, null=True) people_count_exit = models.IntegerField(blank=True, null=True) store = models.ForeignKey(Store, blank=True, null=True) profile = models.ForeignKey(Profile) camera = models.ForeignKey(Camera) recorded_time = models.DateTimeField(null=True, blank=True) def str(self): return "People Count {}".format(self.timestamp) class Meta: verbose_name = "People Count" verbose_name_plural = "People Count" ordering = ['-timestamp'] and I am using below query to get data on hour basis: queryset = PeopleCount.objects.filter( **json.loads( self.request.query_params['filter'])['object_params'] ).annotate( time_series=TruncHour('recorded_time')).values( 'time_series').annotate( people_count_entry=Sum('people_count_entry')).values( 'time_series', 'people_count_entry').annotate( people_count_exit=Sum('people_count_exit')).values( 'time_series', 'people_count_entry', 'people_count_exit') The problem with above query is that it actually doesn't aggregate on hour basis and instead keep individual values for each timestamp which I have to manipulate at client side. The approach on client side works but it takes a lot of time for larger queryset. Hope my problem statement is clear. Thanks. -
Not able to create a plan using dj-stripe from django admin
I am using dj-stripe==1.0.0.post1. I have followed the installation steps as mentioned here. When I go to the django admin and try to create a plan, I get this error KeyError at /admin/djstripe/plan/add/ 'stripe_id' here is the full stack trace: ERROR 2017-09-27 11:07:57,600 django.request Internal Server Error: /admin/djstripe/plan/add/ Traceback (most recent call last): File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/contrib/admin/options.py", line 551, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/contrib/admin/sites.py", line 224, in inner return view(request, *args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/contrib/admin/options.py", line 1508, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/contrib/admin/options.py", line 1408, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/Users/swapnil/Work/li-django/venv/lib/python3.6/site- packages/django/contrib/admin/options.py", line 1448, in _changeform_view self.save_model(request, new_object, form, not add) … -
Dynamic table and model generate in django
I want to create some database tables and models.Model on api call in django. I created on demand Model model = type(str(project_slug + "_tbl_name"), (models.Model,), attrs) and I want to create table like this db.create_table(table_name, fields) create_table was from south but south is not available in Django 1.11 what I am using How can I generate Model and database tables programmatically? -
django removing user table
I'm new to Django and creating my first app. I created a user model not understanding that there was one inbuilt. I have removed the user table. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. # class User(models.Model): # firstname = models.CharField(max_length=250) # lastname = models.CharField(max_length=250) # email = models.CharField(max_length=250) # password = models.CharField(max_length=250) # newsletter = models.BooleanField(default=0) # accountlevel = models.BigIntegerField(default=1) # reportsCreated = models.BigIntegerField(default=0) # # def __str__(self): # return self.firstname +" "+ self.lastname +" - "+self.email class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reports = models.IntegerField(default=3) accounttype = models.CharField(default='Free') monthlycost = models.FloatField(default=0.0) def __str__(self): return self.user.username + " - " + self.accounttype I now need to like the ForeignKey from Account and report tables to the inbuilt user model. when I run: python manage.py makemigrations I get the following error django.contrib.admin.sites.AlreadyRegistered: The model User is already registered -
Django django-autocomplete-light search not complete
I am using django-autocomplete-light plugin in my project. Plugin works just fine, but if the company name is made from more than one word it doesn't search by the second or third word, e.g. Bayerische Motoren Werke(BMW) if I search for Baye... it fill find it, but searching Mo... or Wer... it won't. I know it's an autocomplete plugin, but I am wondering if there is a workaround. views.py class CompanyAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Company.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) | qs.filter(comNumber__istartswith=self.q) return qs urls.py urlpatterns += [ url( r'^autocomplete/$', views.CompanyAutoComplete.as_view(model=Company), name='company-autocomplete', ), ] models.py class Company(models.Model): name = models.CharField(max_length=255) comNumber = models.CharField(max_length=255) law = models.CharField(max_length=255) country = models.CharField(max_length=255, null=True, blank=True) city = models.CharField(max_length=255, null=True, blank=True) street = models.CharField(max_length=255, null=True, blank=True) house_number = models.CharField(max_length=255, null=True, blank=True) email = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name.encode("utf-8") def get_absolute_url(self): return reverse('company-detail', args=[str(self.id)]) def __unicode__(self): return '%s' % (self.name,) -
Is there a way to update a ListView in Django, without refreshing the HTML page?
I need to update a ListView in Django, based on a certain time. I tried to do with JavaScript but as a newbie in Django, I could not figure out how to do it. -
Django rest framework how to serialize a list of strings?
I want to give a list of strings in postman, for example: ['string1', 'string2', 'string3', 'string4', 'string5'] But when it reaches serializer.is_valid() it gives me: "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] How can I make the serializer to except a list of strings? -
How can I map the integer to corresponding text?
In the templates, there is a data.grade which is integer. If the data.grade == 1, I want to the place shows VIP, if equals to 2, I want to shows Normal {{ data.grade }} # there only shows 1 or 2, but I want to shows VIP or Normal -
What can be the filename of uploading location for ImageField?
Whenever I create Cloth Model with cloth_image, the image uploads to upload_location. My problem is instance.id returns None because the instance is not yet created. What can be the best upload_location for ImageField? def upload_location(instance, filename): new_id = instance.id ext = filename.split('.')[-1] return "clothes/%s/%s.%s" % (instance.user.id, new_id, ext) <- Right Here! class Cloth(models.Model): cloth_image = models.ImageField(upload_to=upload_location, null=True, blank=True) I'm using AWS S3. -
How it should be done properly to send and receive message with user ID using websockets in Django and Angular?
I am going to create chatbot using websockets. Each user can have their own account. I have Django backend and frontend written in Angular. At the moment I have a problem with message object. To wit I get this in backend: django_1 | django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint django_1 | DETAIL: Failing row contains (212, {"message":"Hello"}, null). It looks as I wouldn't send user ID from frontend. I wonder how can I solve it and how it should be done properly? My Django message model looks in this way: class Message(models.Model): user = models.ForeignKey('auth.User') message = models.CharField(max_length=200) This is my backend consumer: @channel_session_user_from_http def msg_consumer(message): text = message.content.get('text') Message.objects.create( message=text, ) Group("chat").send({'text': text}) @channel_session_user def ws_connect(message): # Accept the connection message.reply_channel.send({"accept": True}) # Add to the chat group Group("chat").add(message.reply_channel) message.reply_channel.send({ "text": json.dumps({ 'message': 'Welcome' }) }) @channel_session_user def ws_receive(message): message.reply_channel.send({"accept": True}) print("Backend received message: " + message.content['text']) Message.objects.create( message = message.content['text'], ) Channel("chat").send({ "text": json.dumps({ 'message': 'Can we start?' }) }) @channel_session_user def ws_disconnect(message): Group("chat").discard(message.reply_channel) This is part of my Angular component: export class HomeComponent { response: string; response2: string; constructor( private chatService: ChatService, private router: Router, private http: Http, ) { chatService.messages.subscribe(msg => { this.response … -
Create an integer field with a drop down box. Django Custom Widget?
I am trying to create an integer field connected with a drop down box to collect a time period from a user. From there i would like to store it in a table in some sort of readable format for the machine e.g 12W from that i can split the object and add 12 weeks on to todays date and fill a Due Date field. For example [12][Days] [weeks] [Months] Would this be a customer widget? or is there a better way of completed it? -
Parse Django JsonResponse with Angular 4
I'm using Django for send JsonResponse. If I map response.json() Angular return me an error that I can't handle. Furthermore, if I use response.text() for visualizing data it return something like that: Response: {u'foo': u'bar', u'title': u'hello world'} In Angular 4 I've this code: return this._http.post(this.serverUrl, JSON.stringify(data), {headers: headers}) .map((response:Response) => response.json()) .catch(this.handleError); In Django Python I've this code: response= {'foo': 'bar', 'title': 'hello world'} return JsonResponse(response, safe=False); I've also tryed this: return HttpResponse(json.dumps(response), content_type='application/json; charset=utf-8',) return HttpResponse(json.dumps(response)) return json.dumps(response) return response -
css is not working in firefox, but with chrome and safari it does
I am trying to adapt my website to firefox, but never made it. But nothing is working, totally nothing with firefox. I made a research on firefox standards, but nothing of them is helping. I believe theres something wrong with the structure. PS: I am going to implement all this in Django and Pywebview, but I have to make it running on firefox first, because the Pywebview is using the Mozilla's core. body { height: 100%; width: 100%; margin: 0; display: flex; display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */ display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */ display: -ms-flexbox; /* TWEENER - IE 10 */ display: -webkit-flex; /* NEW - Chrome */ flex-direction: column; overflow-y: hidden; } #info p { margin: 4; } #svg { width: calc(77% - 2px); height: 100%; margin: 0 auto 0 auto; border-left: 1px solid #000; left: 0; right: 0; cursor: crosshair; /* disable text selection on svg */ -webkit-touch-callout: none; /* iOS Safari */ -webkit-user-select: none; /* Chrome/Safari/Opera */ -khtml-user-select: none; /* Konqueror */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* Internet Explorer/Edge */ user-select: none; /* Non-prefixed version, currently not supported by any browser */ } … -
L10N Support for Bootstrap Datetimepicker in Django
When using the datetimepicker of Bootstrap in a Django form, the language and date format can be set like this $(function () { $('#datetimepicker1').datetimepicker({ locale: 'de', format: 'DD.MM.YYYY HH:mm' }); }); Is there an elegant way to automatically fill in these two parameters so that changing the language code in Django will change the locale and format for the datetimepicker accordingly? -
How to import models from one app to another app in Django?
I am trying to reference a model (Person) from one app, in the views-file of another app. Unfortunately, I get an "unresolved reference"-error. Is it possible to reference models from other apps in Django? If so, what am I doing wrong? Let me demonstrate with an example: The image below shows my project. I am currently in the views.py (marked in green), in the app called "autocomplete". I want to reference a person-model in the file "models.py" (marked in red), that belongs to the app "resultregistration". However, I get the error "Unresolved reference Person", even though the class Person does exist in models.py Any help would be strongly appreciated! Thank you for your time! -
How to use slice in forloop django?
right now I am trying to use slice in my template but it is showing the this error:- TemplateSyntaxError at /post/ 'for' statements should use the format 'for x in y': for item in user_basic_info |slice:"2" what I am doing is: {%for item in user_basic_info |slice:"2"%} <li> <div class="userimg_sec"> <div class="userimg"> <img src="{{ item.profileImage }}"> </div> </div> <div class="userdetails"> <p class="username">{{ item.name }}</p> <p class="usernickname">@{{ item.username }}, <span>teacher</span></p> </div> </li> {% endfor %} -
what is the best alternative for django's formfield_for_foreignkey
I need an alternative to wagtail for djangos formfield_for_foreignkey in admin. How can I do this? -
How to add more attributes with json data
I have implemented code like this. message_body = "message body" message_title = "message title" badge = 1 data_message = { "type":"1100", "class_id":"10", } if(condition): # add more attributes with already existing attributes data_message = { "message_body" : message_body, "message_title" : message_title, "badge" : badge, } return data_message else: # without any changes in data_message return data_message If pass the if condition I got only message_body, message_title, badge. I could not receive type and class_id. i want to get all of these if pass the IF conditon. could anyone suggest anyway to do this? -
How to get rest-auth and reactJS to work together?
My rest-auth urls are working properly individual. But, i want to integrate both. I mean django views.py and UI is in ReactJS. My js file is below: import React, { Component } from "react"; import ReactDOM from 'react-dom'; import DjangoCSRFToken from 'django-react-csrftoken'; import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap"; var formStyle={ margin: '0 auto', maxWidth: '320px'} var loginStyle={ padding: '60px 0'} class Login extends React.Component { constructor(props) { super(props); this.state = { username : "", email: "", password: "" }; } render() { return ( <div className="Login" style={loginStyle}> <form style={formStyle} method="post" onSubmit> <DjangoCSRFToken/> <FormGroup controlId="username" bsSize="large"> <ControlLabel>Username</ControlLabel> <FormControl autoFocus type="text" name="username" /> </FormGroup> <FormGroup controlId="email" bsSize="large"> <ControlLabel>Email</ControlLabel> <FormControl type="email" name="email" /> </FormGroup> <FormGroup controlId="password" bsSize="large"> <ControlLabel>Password</ControlLabel> <FormControl type="password" name="password" /> </FormGroup> <Button block bsSize="large" type="submit" > Login </Button> </form> </div> ); } } ReactDOM.render(<Login/> , document.getElementById("login")); And i have added all settings for rest-auth in settings.py and its working fine individual. Please Guide me. I am very new in ReactJS. -
List models according to ContentType and object_id. (How to List Generic ForeignKey objects)
This is Star ListAPIView so far I have. [ { "user": 1, "content_type": 26, "object_id": 7 }, { "user": 1, "content_type": 26, "object_id": 8 }, { "user": 1, "content_type": 15, "object_id": 5 }, { "user": 1, "content_type": 15, "object_id": 6 } ] Since content_type of the very first object in the array is 26, its referring object is 'Outfit'. For better understanding, I'm providing Star Model. It contains ContentType and object_id field. It uses two fields to refer Generic foreignKey. class Star(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') objects = StarManager() And here is Serializer and View serializers.py class ListStarSerializer(serializers.ModelSerializer): class Meta: model = Star fields = ('user', 'content_type', 'object_id') views.py class StarListAPIView(generics.ListAPIView): serializer_class = ListStarSerializer def get_queryset(self): qs = Star.objects.filter(user=self.request.user) return qs Both content_type 26 and 15 have each image fields (called outfit_img and cloth_img) for each. To Achieve this, I want to use different Serializer depending on the content_type For example, if content_type is 26, call OutfitListSerializer. If content_type is 15, call ClothListSerializer. I'm building this Star app having help from this link (def create_comment_serializer). (https://github.com/codingforentrepreneurs/Blog-API-with-Django-Rest-Framework/blob/master/src/comments/api/serializers.py). Thank you so much!