Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send sms using python
I'm trying to integrate SMS feature in my django project, and gone through the kannel but I found difficulties kannel configurations. IS any easiest way to send SMS using python ? After googling,I found serial AT Command link , suggest me some good documents on serial command or other approach to send Sms -
How to build my models correctly?
I am using django to wirte a program now, my problem is i am confused with building models. I have made two models in seperate apps, which is user and device. The relationship is user can borrow 1 to n devices, but each device can be hold by only one user. Then, in the user class, i need to have a attribute borrowed_device that can store the device classes(all the devices he borrowed), and in Device class, i need a attribute that can help me track who borrowed this device. The following is my code, and i don't how to write then, any advice would be appreciated. user/models from django.db import models from device.models import Device class User(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) borrowed_device = models.ForeignKey('Device', on_delete=models.CASCADE(), related_name='borrowed_device') # id = models.IntegerField() class Meta: ordering = ('username', ) device/models from django.db import models from user.models import User class Device(models.Model): DEVICE_TYPE = {('chemistry', 'chemistry'), ('physics', 'physics'), ('computer', 'computer'), ('biology', 'biology')} device_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20) type = models.CharField(max_length=20, choices=DEVICE_TYPE) bought_in_time = models.DateTimeField(auto_now_add=True) last_used_time = models.DateTimeField(auto_now=True) # number = models.IntegerField(default=1) status = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE(), related_name='user') class Meta: ordering = ('type', '-bought_in_time') def __str__(self): return self.name # def … -
Unable to upload image using shell in django
I am newbie on dJango/python. I am trying python shell to save data using model. I have done as: Model class Author(models.Model): salutation = models.CharField(max_length=10) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() headshot = models.ImageField(upload_to='/tmp') def __str__(self): return '%s %s' % (self.first_name, self.last_name) Now I have tried the command in shell: >>> from books.models import Author >>> a = Author(salutation='Mr.', ... first_name='First Name', ... last_name='Last Name', ... email='myemail@myemail.com') Then I have put an image in the project's tmp directory and run following the command: a.headshot.save('/abc.jpg', Author(open('/tmp/pic.jpg', 'r'))) It gives me error: Traceback (most recent call last): File "<console>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: '/pyproject/mysite/tmp/pic.jpg' Please help me someone. -
How do I render a html page from a view returning JSON data in django?
I have function in my views.py which returns JSON data, what I have in mind is rendering a HTML page from that data. The same question can also be associated with data returned from rest API generic views returning JSON data. -
django admin - matching query does not exist
So I have these two models defined in separate file under models folder in django First I defined only Medical model and everything was working fine class Medical(BaseModel): general_detail = models.ForeignKey( GeneralDetail, help_text='General Detail' ) state = FSMField( blank=True, protected=not settings.DEBUG, default=STATE.SUBMITTED, state_choices=STATE_CHOICES, ) def __str__(self): return str(self.general_detail.employee.user.first_name) + ' ' \ + str(self.general_detail.employee.user.last_name) def __unicode__(self): return str(self.general_detail.employee.user.first_name) + ' ' \ + str(self.general_detail.employee.user.last_name) But just after adding this below model it gives error in django-admin when saving a field in transition history using django-admin. class TransitionHistory(BaseModel): state_from = FSMField( blank=True, protected=not settings.DEBUG, default=STATE.SUBMITTED, state_choices=STATE_CHOICES, ) state_to = FSMField( blank=True, protected=not settings.DEBUG, default=STATE.SUBMITTED, state_choices=STATE_CHOICES, ) def __str__(self): return str(self.state_from) + str(self.state_to) def __unicode__(self): return str(self.state_from) + str(self.state_to) Error Exception Type: DoesNotExist Exception Value: Medical matching query does not exist Line 379 C:\Python27\lib\site-packages\django\db\models\query.py in get self.model._meta.object_name -
Django: retrieve single object from ManyToMany relation effectively
I have a database structure which can be simplified as following (Version and AdditionalInfo not shown since not directly related to my question): class Image(models.Model): file = models.ImageField(blank=False, null=False, upload_to='images') version = models.ForeignKey(Version, blank=False, null=False) class ExampleImage(models.Model): example = models.ForeignKey('Example', blank=False, null=False) image = models.ForeignKey(Image, blank=False, null=False) additional_info = models.ForeignKey(AdditionalInfo, blank=True, null=True) class Example(models.Model): name = models.Charfield(max_length=255) images = models.ManyToManyField(Image, through=ExampleImage, through_fields=('example', 'image') def get_default_image(self): try: image = self.images.get(version=Version.objects.get(name=DEFAULT_VERSION)) except Image.DoesNotExist: # Get some other image, this happens maybe 1 out of 10 Now I have a very common need to query all Example objects along with their default image. Currently, I'm doing somewhat like following: example_list = [] examples = Example.objects.all() for example in examples: example_dict = dict(name=example.name, image=example.get_default_image()) example_list.append(example_dict) # Then show example_list in template This approach works but it causes thousands of database queries and takes over one minute to perform which is little too long to download a single web page! So my question is, what is the right approach to optimize this kind of use case. I could possibly set default_image field for the Example model (and use select_related then, but this makes adding images more complicated), hard code the Version id to get_default_image method … -
redirect to other page and get the data from database in django
**this is first page code** {% for x in JOBS %} {{ x.job_school_id }} <p>{{ x.job_school_name }}</p> {{ x.job_opening }} {{ x.job_city }} {% endfor %} [1]: http://localhost:8000/jobapply/ *this is jobapply page* {{ job_school_id }} {{ job_city }} {{ job_opening }} {{ job_school_name }} *also i have to get all other relative columns of table in database* -
Django 1.10 IntegrityError on register
I'm trying to set up a registration page and I have a model CafeUser which serves as the profile for the User model. I used a tutorial to set up a signal receiver so I could create a CafeUser for all new registered users. models.py: class CafeUser(models.Model): user = models.ForeignKey(User, unique=True, related_name="cafeuser") phone_number = models.CharField(max_length=15) birth_date = models.DateField('birthdate') def __str__(self): return self.user.first_name + " " + self.user.last_name @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: CafeUser.objects.create(user=instance) views.py: def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.cafeuser.birth_date = form.cleaned_data.get('birth_date') user.cafeuser.phone_number = form.cleaned_data.get('phone_number') user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('cafe:index') else: form = SignUpForm() return render(request, 'cafe/register.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') birth_date = forms.DateField(help_text='Rquired.') phone_number = forms.CharField(max_length=15) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',) When I try testing the registration, the user is created, however, the CafeUser is not: IntegrityError at /register/ null value in column "birth_date" violates not-null constraint DETAIL: Failing row contains (7, 8, null, ). Please let me know how … -
super(type, obj): obj must be an instance or subtype of type
I work on a small Django app and get an error tells me, super(type, obj): obj must be an instance or subtype of type. I get it from the views.py file after introducing the function get_object_or_404. The views.py file provided below, from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import View from .models import URL # function based view def redirect_view(request, shortcode=None, *args, **kwargs): obj = get_object_or_404(URL, shortcode=shortcode) return HttpResponse("Hello World, the shortcode is {shortcode}".format(shortcode = obj.url)) # class based view class ShortenerView(View): def get(self, request, shortcode=None, *args, **kwargs): obj = get_object_or_404(URL, shortcode=shortcode) return HttpResponse("Hello World 1, the shortcode is {shortcode}".format(shortcode = obj.url)) def post(self, request, *args, **kwargs): return HttpResponse() the full error message is here, TypeError at /b/p6jzbp/ super(type, obj): obj must be an instance or subtype of type Request Method: GET Request URL: http://127.0.0.1:8000/b/p6jzbp/ Django Version: 1.11 Exception Type: TypeError Exception Value: super(type, obj): obj must be an instance or subtype of type Exception Location: /Users/Chaklader/Documents/Projects/UrlShortener/src/shortener/models.py in all, line 18 The line 18 in the models.py is qs_main = super(URL, self).all(*args, **kwargs) and the models.py file is here, # will look for the "SHORTCODE_MAX" in the settings and # if not found, will put … -
Django ModelChoiceField, thousands of options , not user friendly
I have a ModelChoiceField in my form: customer = forms.ModelChoiceField(Customer.objects.all()) the problem is it renders as a drop down with hundreds of options and its difficult for users to find a customer, is there a way to overcome this??? -
Django RQ handles long serializer job
I have validator in the model. It does validation and then validated data will be saved to database. Problem: Validation and commit to database takes very long time. Therefore I decided to use Django-rq to handle the time consuming task views.py def save_serializer(serializer, request): serializer.save() if bool(serializer.errors): # If it has no errors it will be empty dictionary and bool({}) is False msg = serializer.errors else: msg = serializer.data email = EmailMessage( 'Message From jobs.siamsbrand.com', msg, settings.C0D1UM_SENDER, [request.user.email] ) email.send() class PriceListExcelFileList(generics.ListCreateAPIView): permission_classes = (DRYPermissions,) queryset = PriceListExcelFile.objects.all() serializer_class = PriceListExcelFileSerializer def perform_create(self, serializer, request): """ :param serializer: :return: """ django_rq.enqueue(save_serializer, serializer, request) def create(self, request, *args, **kwargs): """ I need to override the default behaviour because I am going to use rq and let it be an email notification :param request: :param args: :param kwargs: :return: """ serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer, request) headers = self.get_success_headers(serializer.data) data = { "id": "Processing", "file": "The response will be email to " + str(request.user.email) + " shortly", "permission": "-" } return Response(data, status=status.HTTP_201_CREATED, headers=headers) Error Messages: File "/Users/el/Code/siam-sbrand/portal/apps/price_list_excel_files/views.py", line 52, in create self.perform_create(serializer, request) File "/Users/el/Code/siam-sbrand/portal/apps/price_list_excel_files/views.py", line 40, in perform_create django_rq.enqueue(save_serializer, serializer, request) File "/Users/el/.pyenv/versions/siam-sbrand/lib/python3.6/site-packages/django_rq/queues.py", line 208, in enqueue return get_queue().enqueue(func, *args, … -
DRF: ModelSerializer for nested JSON data
I'm trying to convert my existing DJANGO app to API based. I have done the front-end in Angular and working on the backend now. The data from client is going to be in json format as below { "title": "wue", "author": "asd", "addons": { "header":"head", "footer":"foot" } } I have written the model.py class BookDetails(models.Model): title= models.CharField(max_length=10) author= models.CharField(max_length=10) addons= models.ForeignKey(Addons, null=True) class Addons(models.Model): header= models.CharField(max_length=10) footer= models.CharField(max_length=10) serializer.py class AddonsSerializer(serializers.ModelSerializer): class Meta: model = Addons fields = ('header', 'footer') depth = 2 class BookDetailsSerializer(serializers.ModelSerializer): addons = AddonsSerializer(many=False, read_only=True) class Meta: model = BookDetails depth = 2 fields = ('title', 'author','addons') views.py class BookDetailsList(APIView): def get(self, request): stocks = BookDetails.objects.all() serializers = BookDetailsSerializer(stocks, many=True) return Response(serializers.data) def post(self, request): serializer = BookDetailsSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my urls.py is urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^bookdetails/', views.BookDetailsList.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) Now when I'm using postman to send the data then the addons field is not getting populated, it gets null value. I have tried to write a custom create but I think somewhere I'm messing it up, but not able to figure out where. def create(self, validated_data): tracks_data = validated_data.pop('addons') addons = BookDetails.objects.create(**validated_data) Addons.objects.create(addons=addons, **tracks_data) … -
Form with checkboxes which change BooleanField value?
Can someone say, how create such form as in the picture below in Django? I have model Product with field is_visable. In form I want to show all products with field is_visable. User can select checkboxes and change the value of is_visable field. In other words make products visable or invisable. I am thing about MultipleChoiceField in my form but not sure is it correct in my case. models.py: class Product(models.Model): symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) is_visible = models.BooleanField(default=False) -
Implementing two different ModelForm Django
I'm trying to implement two forms in two different views. They follow the same procedure in the views but the data is saved according to different Models. Everything is ok with the first form, but when I open the second one I see the first one and then, when I submit that form I see the second one. The storage of the data works fine. I'm going to the forms template using buttons, so I need to go to one form with button and to the other with other button. I hope you can help me. If you need more information, please let me know! Thanks in advanced. My codes: Models.py class Control(models.Model): id_p = models.SlugField() pa_sis = models.CharField(max_length=3,) pa_dias = models.CharField(max_length=3,) stamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) prox_fecha = models.DateField(default=timezone.now) prox_hora = models.TimeField(default=timezone.now) def __str__(self): return self.pa_sis def __str__(self): return self.pa_dias class Med(models.Model): id_p = models.SlugField() stamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) med_m = models.CharField(max_length=255,) hora_m = models.TimeField(default=timezone.now) med_t = models.CharField(max_length=255,) hora_t = models.TimeField(default=timezone.now) med_n = models.CharField(max_length=255,) hora_n = models.TimeField(default=timezone.now) def __str__(self): return self.med_m def __str__(self): return self.med_t def __str__(self): return self.med_n forms.py from django.forms import ModelForm from .models import Control, Med class ControlForm(ModelForm): class Meta: model = Control … -
Django ORM - get() with order_by()
I want a mix of get() and order_by() like this Model.objects.get(some=condition).order_by('name') I want a single result (not filter) and ordered by name at the same time. -
<h1> styling not working but others will
I am using django and my <p> selector is working but the <h1> is not. I cant understand why some css is working and others isnt. What order does bootstrap work in? It does find the style.css file my text of the element works style.css font-family: 'Wendy One', sans-serif; font-family: 'Baloo', cursive; font-family: 'Libre Baskerville', serif; h1 { color:yellow; font-family: "Baloo", cursive; } p { color: red; font-family: 'Libre Baskerville',sans-serif; } index.html {% extends "base.html" %} {% block content %} <h1 class="text-center" >The Wish Fairy Foundation</h1> <p> this should be the index of wishfairies.</p> {% endblock %} base.html {% load static %} <!DOCTYPE html> <html lang="en"> {% block title %}{% endblock %} <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link href="https://fonts.googleapis.com/css?family=Baloo|Libre+Baskerville|Wendy+One" rel="stylesheet"> </head> {% block header %} {% endblock %} <body> {% block sidebar %} {% endblock %} <div class="container"> {% block content %} {% endblock %} </div> {% block footer %} {% endblock %} </div> </div> </div> </body> </html> -
Django Model Not Updating After Calling .save()
My model won't update after save() is called in my view. Looking into several places (here, here) didn't yield any answers for my case. My model does contains a ManyToManyField: Model: class Event(models.Model): name = models.CharField(max_length=120) date = models.DateTimeField(auto_now=False, auto_now_add=False) attendees = models.ManyToManyField(Employee) approval = models.ForeignKey(EventStatus, default=2) def __unicode__(self): return self.name def approve_url(self): return reverse("RGAU:EventApprove", kwargs={"id": self.id}) View: def EventApprove(request, id=None, **kwargs): instance = get_object_or_404(Event, id=id) instance.approval.id = 3 instance.save() messages.success(request, "Event Approved") return redirect("RGAU:UserDashboard") The goal is to have the Event instance updated to "Approved" when a button is pushed on the webpage (hence the view EventApprove). instance.approval.id is suppose to assign the correct approval status id but the save is not committed. What am I doing wrong? -
Upload file through django restful api
I've read all the stackoverflow questions and answers and every tutorial that I an find but I still cannot get this to work--I might be dumb. I'm trying to upload files to django via restful api through curl. My curl command is as follows curl -X POST -H "Content-Type:multipart/form-data" -u alex:password123 -F "docfile=@/Users/Alex/test.txt" http://127.0.0.1:8000/files/ models.py from django.db import models class File(models.Model): title = models.CharField(max_length=100, default='') docfile = models.FileField(upload_to='file/') views.py from rest_framework.parsers import FormParser, MultiPartParser from models import File from serializers import FileSerializer class UploadFile(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer parser_classes = (MultiPartParser, FormParser,) def preform_create(self, serializer): file_obj = self.request.FILES['docfile'] serializer.save(file_obj) serializers.py from rest_framework import serializers from models import File class FileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = File fields = ('docfile','name') urls.py from django.conf.urls import url, include from rest_framework import routers from quickstart import views router = routers.DefaultRouter() router.register(r'files', views.UploadFile) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] My media root is MEDIA_ROOT = '' I've read through a ton of documentation but I am really stuck on how all of this fits together/what I'm missing. Any help is appreciated. -
Django dot product with postgres ArrayFields
I have the following two models: class TestResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) scores = ArrayField(models.PositiveSmallIntegerField()) #...more fields... class TestCriteria(models.Model): category_weights = ArrayField(models.PositiveSmallIntegerField(), default=list) #...other fields ... What I'd now like to do, is given some TestResult, sort the users by the dot product of their TestResult.scores and the TestCriteria.category_weights. I don't know in advance how long these arrays will be, only that they'll be equally long. -
How do I fix this error in Django? <Corr: Item One>" needs to have a value for field "corr" before this many-to-many relationship can be used
I cannot figure out where this error is coming from. How do I solve this problem? models.py: class Corr(models.Model): name = models.CharField(max_length=255) attr_x = models.ManyToManyField(Attr, related_name='attr_x') attr_y = models.ManyToManyField(Attr, related_name='attr_y') def __str__(self): return self.name api.py: @api_view(['GET', 'POST']) def corr_list(request): if request.method == 'GET': corr = Corr.objects.all() serializer = CorrSerializer(corr, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': serializer = CorrSerializer(data=request.data) if serializer.is_valid(): # import pdb; pdb.set_trace() serializer.save() #<-- error here return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) What I have is a Corr model that can take two attr's, x and y, in a Many2Many relationship -- but when I call 'serialize.save()' I get the error above. I'm not sure how to solve this. Serializer doesn't have/respect save_m2m(). Any help would be appreciated. I've tried a few different ways to knock this out in PDB but I always come back to the same error. Help! How can I fix this? -
Django : How to show form validation errors if form is not valid on base.html?
I have a form on my base.html since I want to show it on every pages, I'd like to show validations errors whenever the form is not valid, the problem is that it redirects me to my view even if it's the validation is false and throws me an error 500. Here how I did : views.py def askProject(request): if request.method == 'POST': form = AskProjectForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('success-msg')) else: form = ContactForm() forms.py : class AskProjectForm(forms.ModelForm): class Meta: model = AskProject fields = ['prenom', 'nom', 'numero'] def clean_prenom(self): prenom = self.cleaned_data['prenom'] if len(prenom) < 3: raise ValidationError('Votre prénom doit etre plus long que 1 caractère.') return prenom ... context_processors.py : from pages.forms import AskProjectForm def AskProjectFormProcessor(request): return {'AskProjectForm' : AskProjectForm()} base.html : <form method="post" action="{% url 'ask-project' %}"> {% csrf_token %} <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <p>{{ AskProjectForm.prenom.errors }}</p> <label for="prenom">Votre prenom<span class="form-required" title="Ce champ est requis.">*</span></label> {{ AskProjectForm.prenom }} </div> ... <div class="form-button col-lg-12 col-md-12 col-sm-12 col-xs-12"> <button class="btn btn-default submit">C'est parti !</button> </div> </form> How can I resolve this issue since I cannot user render(request, ..., {...}) on base.html ? I'd like to return to the same page where the user is while showing the … -
What is an asynchronous http proxy?
I am tasked with building one for an interview, and I am not even certain about what it actually is. I am using python and django. I've read some tutorials about building a proxy (something I have never done before) and have been researching sockets. I have begun building, with my interpretation of an asynchronous http proxy being a proxy server site that could load any site without a new page load, though I am starting to believe I might be mistaken. Can anyone lend some insight? -
How to accept timezone in Postgres database using Django
I have a model models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone class Article(models.Model): sort = models.IntegerField(blank=True) pub_date = models.DateTimeField(default=timezone.now) title = models.CharField(max_length=30, blank=True) settings.py TIME_ZONE = 'America/New_York' USE_TZ = True tasks.py from __future__ import absolute_import, unicode_literals from celery.decorators import task from .models import Article import urllib2 import json import datetime @task(name="articles") def update_article(): # .... more code article = Article.objects.get(id=1) if article != None: article.pub_date = datetime.datetime.now() article.title = "Hello" article.save() When I run in the django shell import datetime pub_date = datetime.datetime.now() print pub_date The pub_date is EST / 'America/New_York' timezone - correct. I have a celery to update the Article, I wrote a simple code article.pub_date = datetime.datetime.now() When the pub_date is updated, in the DB the date is in UTC not America/New_York / EST timezone, even the shell is showing me correct ETC, but running it with the task, in the postgres DB it is UTC -
Advice on how to design datastructure in Django project
I'am a begginer in Django and Python in general, but I have to make a project for school. I decided to make something like soundcloud.com but much simpler. Basically, you create an account and you can add your songs (and organize them into albums, give them descriptions). You also can search for other people, visit their profiles and leave "likes" on songs you like. I also thought about being able to add comments to songs and maybe something like PM box. That's rough idea on how I would like it to look - how should I organize the data? Should I make one database with global "Songs" table, that would consist of all songs ever uploaded or maybe each user should have it's own table? If I would like to add comments feature, how and where should I store them? Keep in mind that this is just a school project, so the simpler the better, it's not meant to be another soundcloud.com, it just has to work. Thank in advance for any feedback. -
Why celery-haystack?
For a django project i like to run index updated by a celery worker to not hit the page parse time. I noticed celery-haystack that is able to do this but i'm wondering why it's that complicated. A much simpler solution would be to simply apply an async task from a post_save signal and invoke the signal processor from there, so not to apply the async part from within the signal processor but before. I guess i'm missing something? I'm aware that instances may not exist any more in case of delete signals...