Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to connect android studio to django for developing a android app with django backend
I have developed a website with django framework(simple website),but now i want to build a android app with django back end so can i use to android studio for front end and django for back end and if yes how to connect both for setting up development environment?? -
Using custom user model after having run migrate for the first time
In the documentation it says that if I want to override the default user model in a project, I need to do so before running any migrations or running manage.py migrate for the first time. I wonder what happens if I do the opposite, which is changing the user model to a custom one AFTER having run the migrations. I only have myself registered as a user to test the functionality of my web app, if I lose it, it doesn't matter to me. -
How can one display plain text obtained from a Validation Error?
Trying to display an error that was raised as part of a Validation sequence. But, the message being returned from the call, has HTML text that is a part of it. Would just like to have plain text available (with no HTML markups) Basically, the code that is being used is: forms.py def clean_username(self): username = self.cleaned_data.get('username') try: match = User.objects.get(username=username) except User.DoesNotExist: # Unable to find a user, this is what is wanted - so - just return the username return username # If a user was found with this as a username, raise an error. raise forms.ValidationError("This userid is already in use. Please supply a different userid.") views.py [.. snip ..] if user_form.is_valid() and profile_form.is_valid(): [... snip ...] registered = True message = 'Field employee has been registered' else: print(user_form.errors, profile_form.errors) message = str( user_form.errors ) + ' - ' + str( profile_form.errors ) <<<< message is being caught here else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'authorization/registration.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered, 'message': message}) on the template, this is what is displayed (in the case of a user already being in the DB) <ul class="errorlist"><li>username<ul class="errorlist"><li>This userid is already in use. Please supply a … -
Prepare Django app for tests with Postman
I'm working on a Django project that requires component tests using Postman. Usually I just use the tests that are available in the Django Rest Framework, but that is not sufficient for this project. I have all the tests working as they should, so that is not the problem here. The problem is that I have to prepare the data in the database manually every time the tests need to run. I have already created some helper functions that I can use to clear the database and enter the data again, but that still requires a manual action every time. Now I am looking for a way to automatically prepare the application for each test (suite) that needs to run. That way I could also use Jenkins or another CI framework. There are some requirements to the method that I would like to use: It must also be used by other testing frameworks (e.g. Cypress) It must be able to run automatically each time the tests are run I would like to use factory_boy as much as possible, but still have the ability to use fixed data. I have already thought of some ways that I could use: Create an … -
About capabilities and limitations of django relating to postgresql and deployment
I am currently developing an e-commerce website in django. As it is the first time that I am doing this, I should like to ask for some information regarding deployment in order to plan ahead. I am familiar with the general procedure for deploying to hosting services such as heroku, pythonanywhere, or AWS. I wanted to check, however, whether or not the specific database that I am using (postgresql) can be transferred to the remote postgres server that I will eventually use when I deploy my app, and if this is possible, how it is to be done? -
Running Django runserver doesn't respond on the browser
I've create a project in a server with CentOS, Django 1.10.1 and using python 3.5. When I run in the terminal py manage.py runserver 0.0.0.0:8000 it shows Performing system checks... System check identified no issues (0 silenced). December 10, 2017 - 15:45:23 Django version 1.10.1, using settings 'samplepy35.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. When I use the command netstat -tuplen it says that python is listening on PORT 8000. But when I try to access on the browser it doesn't respond. What can the problem be? -
Why doesn't DRF's serializer validate PositiveSmallIntegerField?
Using Django 1.11 and Django Rest Framework 3.7, I have a Person model class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() age = models.PositiveSmallIntegerField() with a PersonSerializer class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'name', 'age', 'email') and a ListCreate view class PersonList(generics.ListCreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer Using HTTPie, I can create a Person like this: $ http POST http://127.0.0.1:8000/api/people/ name=Alice age=26 email=alice@example.com HTTP/1.0 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Length: 60 Content-Type: application/json Date: Sun, 10 Dec 2017 15:00:28 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "age": 26, "email": "alice@example.com", "id": 1, "name": "Alice" } When I create a Person with a bad email address, I get an error: $ http POST http://127.0.0.1:8000/api/people/ name=Bob age=33 email=oops HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Length: 42 Content-Type: application/json Date: Sun, 10 Dec 2017 15:01:08 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "email": [ "Enter a valid email address." ] } DRF knows it's an EmailField and automatically applies validation, so far so good. However, when I create a Person with a bad age (negative number), I get no error: $ http POST http://127.0.0.1:8000/api/people/ name=Charlie age=-10 email=charlie@example … -
Change the template and CBV depending on the nuber of results in queryset
I have a CBV that inherits from Listview. I need: If there is no element in the queryset, is empty, I need to show the template with a different message or another template If there is just one element in the queryset I need to go(redirect) to the DetailView Based on some previous answers that I received(on other questions) for 2, I think I need to overwrite get. If I I fully change get, my concern is that, later, if change change behavior, can create issue(it has also pagination, context related code). If I call super() and store get in a variable, how do I know/get the result of get_queryset ? -
Creating the object of a foreign or onetoone field from the model linked to it in the form?
Example model : class Profile(models.Model): user=models.OneToOnefield(User) name=models.Charfield() phone=models.IntegerField() Now in forms.py, I want to signup with all the above information. How can we nest the foreign or onetoone field so we can create user. -
django rest's viewset calls default serializer's create method instead of overriden method
I have a nested serializer with overridden create method: class OrderSerializer(serializers.ModelSerializer): data_model=Order user = UserSerializer(many=False) class Meta: model = Order fields = ['uid', 'user','price'] def create(self, validated_data): validated_data=validated_data.pop('user') order=self.data_model.objects.create(**validated_data) order.user=self.context['request'].user order.save() return order class LifeOrderSerializer(OrderSerializer): data_model =LifeOrder class Meta(OrderSerializer.Meta): model = LifeOrder fields = OrderSerializer.Meta.fields + [ "birth_year", "contract_duration",] and in the views.py class OrderViewSet(viewsets.ModelViewSet): queryset_model = LifeOrder serializer_class = LifeOrderSerializer def get_queryset(self): self.queryset_model.objects.all() but when I send a post request to create , model serializers defualt create method gets called! what is the problem? -
Django add recipe form
I'm Django newbie and I have some problem with my code. I hope you will give me some advice. So I can't save Recipe into my database through RecipeCreateForm. Here is my code: models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='recipes_created') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) image = models.ImageField(upload_to='recipes/%Y/%m/%d') description = models.TextField("Description") ingredients = models.TextField("Ingredients") preparation = models.TextField("Preparation") created = models.DateField(auto_now_add=True, db_index=True) def __str__(self): return self.title forms.py from django import forms from .models import Recipe class RecipeCreateForm(forms.ModelForm): class Meta: model = Recipe fields = ('title', 'image' 'description', 'ingredients', 'preparation') And how should look like views.py file? -
Django form sender is receiver
I'am creating simple contact form in Django for a website. It works fine, however, mail to a receiver is send from receiver and not from sender specified in a form. Consequently, receiver can not respond to a mail. I can try to paste a sender email to a message so receiver will know an address, but there must be more elegant way of doing that and I dont't know the way. -
How to play background video in Django form?
{% load staticfiles %} <!DOCTYPE html> <html> <head> <title style="font-weight:bold; font-family:cursive">Font Maker </title> <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 href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <link href='ank1.css' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <div class="embed-responsive embed-responsive-4by3"> <body> <div class="page-header"> <h1><a href="/"style="font-weight:bold; font-family:cursive">FoNt MaKeR</a></h1> </div> <video autoplay loop muted="background"> <source src="//player.vimeo.com/external/158148793.hd.mp4?s=8e8741dbee251d5c35a759718d4b0976fbf38b6f&profile_id=119&oauth2_token_id=57447761"type="video/mp4"></source> </video> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </div> </body> </div> </html> By this, video is playing but not in background of the page. Video is playing in another section but not in background. One more thing, I am not able to play video which is downloaded in my system. -
Django: allow multiple accounts for a single profile
I would like to enable multiple logins (credentials & permissions) for a single profile in my app. Here is my current code: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Ideally, I'd like the User model to have a ForeignKey to Profile, and that would be it. I could then have several Users for a same profile, and my problem would be solved. Unfortunately I don't want to extend the User model because it's quite nasty, so I'd like to be able to put it in my Profile model. ManyToManyField would work, but then the Users could have several profiles and that is not possible. Do you have a clean, simple way to make some kind of "Reverse Foreign key" ? Best, -
Cannot modify a model field on save()
I'm a beginner with Django, and first time askig :) I'm following a simple tutorial on generating a slug for a string (let's say a slug for a blog post generated from its title). Perhaps I'm following an outdated guide, perhaps I'm missing a basic thing, I have no idea. Django 2.0 Python 3.6 I am trying to do a very simple task of slugifying a simple string, so: User enters a string in a simple form When hitting 'save', the title goes through slugify and creates the slug Save. models.py from django.db import models class Testmodel(models.Model): title = models.CharField(max_length=220) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title views.py from django.views.generic.edit import CreateView class TestCreate(CreateView): model = Testmodel fields = '__all__' forms.py from django.forms import ModelForm from .models import Testmodel class TestCreateForm(ModelForm): class Meta: model = Testmodel fields = '__all__' Up until here everythig works, if I enter the slug manualy. In order to do it automaticaly, I have tried: Overriding the save() method withing my ModelForm class. Overriding the form_valid() method within the CreateView Overriding the save() method within the model itself. Tried to connect a pre_save signal to the model. In all of these 4 tries, I had … -
Django url with query params and single view to retrieve different set of objects
I have a model Book: class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A book can have multiple authors and an author can have multiple books author = models.ManyToManyField('Author') genre = models.CharField(max_length=20) isbn = models.CharField(max_length=20) summery = models.CharField(max_length=100, null=True) language = models.CharField(max_length=20, null=True) status = models.CharField(max_length=15, null=True) number_of_pages = models.IntegerField(blank=True) borrowed = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) loan_period = models.IntegerField(default=14) due_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) #This helps to print in admin interface def __str__(self): return u"%s" % (self.title) I have one url that gives me all the books in a specific library: urlpatterns = [ url(r'^books/(?P<library_id>[0-9]+)$', book_list), ] My view that returns those book objects: @api_view(['GET', 'POST']) def book_list(request, library_id): """ List all books in a specific library, or create a new book for a specific library """ if request.method == 'GET': books = Book.objects.filter(which_library=library_id) print(books) serializer = BookSerializer(books, many=True) return Response(serializer.data) My question is: can I and if yes how can I modify my url and view so that this complete list of books can be filtered for different query params to return those specific books i.e. if I hit url such as api/books/1?genre=Fiction&status=Available should further filter … -
authenticating user and user groups django
iam a intermediate django developer who can create a simple blogs in django can anyone tell me is there any way to create django user groups where a user can create a group and add users (everything should be clientside not on the admin side) to that group and they can share (links,pdf,documents everything in the group "Note":this is not the actual question just to have a glance about my question) and the outsider cannot see the group's activities any kind of help is highly appreciated or if you feel like it is a typical question please suggest me some ideas to make this happen if you have any reference links it will be helpfull for me thanks in advance -
MySQL Explain statement showing conflict results
Hi, We have this SQL query which is taking more time, we tried to dig deep into it, when I do explain, it shows the below output Query: SELECT `product_product`.`product_description_id` FROM `ss_shopproduct` INNER JOIN `product_product` ON (`ss_shopproduct`.`product_id` = `product_product`.`id`) INNER JOIN `product_productdescription` ON (`product_product`.`product_description_id` = `product_productdescription`.`id`) WHERE (`ss_shopproduct`.`shop_id` = %s AND `product_product`.`reservation_info_id` = %s AND `product_productdescription`.`is_combo` = %s) EXPLAIN command: *************************** 1. row *************************** id: 1 select_type: SIMPLE table: product_product type: ref possible_keys: PRIMARY,product_product_65ff6ffd,idx_product_description_id_id,product_product_3801de99 key: product_product_3801de99 key_len: 5 ref: const rows: 271608 Extra: Using where *************************** 2. row *************************** id: 1 select_type: SIMPLE table: product_productdescription type: eq_ref possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: bbdb.product_product.product_description_id rows: 1 Extra: Using where *************************** 3. row *************************** id: 1 select_type: SIMPLE table: ss_shopproduct type: ref possible_keys: idx_product_id key: idx_product_id key_len: 4 ref: bbdb.product_product.id rows: 2 Extra: Using where The problem is product_product table is retrieved with index product_product_3801de99 has cardinality of 56, but the rows scanned were 271608. I couldn't figure out, what causing that table to scan that many rows. I have checked that ss_shopproduct table doesn't have index on shop_id but it's showing it scanned 2 rows. The tables product_product, ss_shopproduct and product_productdescription have 1.2M, 2.5M, 0.5M rows respectively. The EXPLAIN … -
InheritanceManager bug when access parent-class elements (Django 2.0)
I'm currently trying to have a object oriented schema in Django 2.0 (Python 3.6.3) with a parent class Program and some children classes Snippet and Software. I saw that the model_utils module contains some tools to handle the polymorphism, and tried to replicate the tutorial (http://django-model-utils.readthedocs.io/en/latest/managers.html), here is what it gives in my case: models.py from django.db import models from model_utils.managers import InheritanceManager class Program(models.Model): name = models.CharField(max_length=100) objects = InheritanceManager() class Snippet(Program): code = models.TextField() class Software(Program): repoLink = models.URLField() Django shell >>> from coding.models import Program >>> programs = Program.objects.select_subclasses() >>> programs Traceback (most recent call last): File "<console>", line 1, in <module> File "...\py3django\lib\site-packages\django\db\models\query.py", line 248, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "...\py3django\lib\site-packages\django\db\models\query.py", line 292, in __getitem__ qs = self._chain() File "...\py3django\lib\site-packages\django\db\models\query.py", line 1156, in _chain obj = self._clone() File "...\py3django\lib\site-packages\model_utils\managers.py", line 100, in _clone return super(InheritanceQuerySetMixin, self)._clone(**kwargs) TypeError: _clone() got an unexpected keyword argument 'subclasses' I don't understand this error and how to fix it, and even don't know if it is a fail in my design or a bad use of the InheritanceManager. So what can be the origin of this error message? -
Configure django model form with jquery and javacript
I have three models : class Instances(models.Model): name_of_instances = models.CharField(max_length=255) url_of_instances=models.URLField(max_length=255,default='') def __str__(self): return self.name_of_instances class Projects(models.Model): name_of_instances = models.ForeignKey(Instances,on_delete=models.CASCADE) name_of_jproject = models.CharField(max_length=255) project_id= models.CharField(max_length=25) def __str__(self): return self.name_of_project class All(models.Model): choices_instance=Instances.objects.all() b = [str(i.name_of_instances) for i in choices_instance] a=[str(i.url_of_instances) for i in choices_instance] choices_instance=tuple(zip(a,b)) name = models.CharField(max_length=255,choices=choices_instance) project = models.CharField(max_length=255,) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) def __str__(self): return self.name I have a models form: class Form(ModelForm): class Meta: model = All fields =('name','project','story','depends_on','rfc') In template i want to know what user has drop down in 'name' field , and i want to send the name value to back end function where i willl filter out all the prijects associated with name value , and send the result to 'project' field as choices (drop down). Kindly help . -
Django Rest add 2 models from single post
Here is my models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=140) class DatewiseTweets(models.Model): name = models.ForeignKey(User) tweets = models.TextField() date = models.DateTimeField(null=True) serializers.py from rest_framework import serializers, fields from twitterApp.models import User, DatewiseTweets class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class DatewiseTweetsSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = DatewiseTweets fields = ('tweets','date','user') view.py class SaveTweetCountView(APIView): datewiseTweetsSerializer = DatewiseTweetsSerializer() def post(self, request, *args, **kwargs): name = request.data['name'] tweetCount = 10 tweets = get_tweets(name, tweetCount) return Response(tweet_dict ,status=status.HTTP_201_CREATED) POST METHOD { "name":"netflix" } Here I'm sending tweeter account name and according to this twitter handle(name) it will find top ten tweets from get_tweets() function. So I want to save this name and all tweets in db. I'm confused how to store data in two tables. here are sample tweets: [ { "date": "2017-12-09T22:36:24", "tweet": "Dear Cluster: I Love You Always" }, { "date": "2017-12-09T22:25:25", "tweet": "RT @sense8: *tap tap* \n\nis this thing on?" }, { "date": "2017-12-09T16:13:54", "tweet": "RT @rachmeetsworld: Personal announcement: I just ordered room service (soup and breadsticks) and I'm going to watch A Christmas Prince!!" }, { "date": "2017-12-09T07:12:02", "tweet": "@emilynussbaum @ilovebakedgoods I would be happy to send you both free corn dogs … -
Celery interval schedule time
I am using django celery beat to schedule my task . Currently i am just creating a interval schedule of 2 days and creating a periodic task to run at that interval . My main problem is , when i schedule a task to run at 2 days , at what time does it run ? and cant i change that time , because i need to run the interval task at certain time provided by the user . The code written so far is periodic_task=PeriodicTask.objects.update_or_create( name='my-interval-task, defaults={ 'interval': schedule, #interval schedule object 'task': 'myapp.tasks.auto_refresh', } ) -
Serilizer.response messing out model Response
I am having an issue that I do not know how to solve. I am using the REST framework, in my views.py I have a model called Response that I want to query with Response.objects.all() The thing is since I imported the serializer from rest_framework.response import Response I think that that Django is getting lost and give me an output that AttributeError: type object 'Response' has no attribute 'objects' Is there a way to deal with that issue without having to rename my model ? Thx you, Raphael -
Access TTN GET request info in Django
I am working on a Django app to process information from The Things Network (TTN). The backend sends information by a GET request, and I want to process this information. A POST request would also be a possibility but then I have to configure/disable CSRF. I can view the information I need when I use request.body but then the information is converted to a byte string. Here is how the input of request.body looks like: b'{"app_id":"111111111111","dev_id":"111111111111","hardware_serial":"11111111111111","port":2,"counter":119,"payload_raw":"UEtUICN2","metadata":{"time":"2017-12-10T09:14:40.469432186Z","frequency":868.1,"modulation":"LORA","data_rate":"SF7BW125","coding_rate":"4/5","gateways":[{"gtw_id":"eui-11111111111111","timestamp":1204471818,"time":"2017-12-10T09:14:40.439773Z","channel":0,"rssi":-66,"snr":6,"rf_chain":0,"latitude":51.986214,"longitude":6.742897,"location_source":"registry"}]},"downlink_url":"https://integrations.thethingsnetwork.org/ttn-eu/api/v2/down/f4ce46a550ec/12?key=ttn-account-v2.-1111111111111-1111111111111111"}' The output of request.META is: {'PATH_INFO': '/', 'wsgi.run_once': False, 'uwsgi.version': b'2.0.15', 'REMOTE_PORT': '42732', 'SERVER_NAME': 'myapp.mydomain.com', 'HTTP_HOST': 'myapp.mydomain.com', 'HTTP_CONTENT_TYPE': 'application/json', 'QUERY_STRING': '', 'SERVER_PORT': '80', 'HTTP_CONTENT_LENGTH': '649', 'DOCUMENT_ROOT': '/home/myapp/domains/myapp.mydomain.com/public_html', 'CONTENT_TYPE': 'application/json', 'REQUEST_URI': '/', 'wsgi.file_wrapper': <built-in function uwsgi_sendfile>, 'wsgi.multiprocess': True, 'wsgi.url_scheme': 'http', 'REQUEST_METHOD': 'GET', 'CONTENT_LENGTH': '649', 'wsgi.version': (1, 0), 'HTTP_USER_AGENT': 'http-ttn/2.6.0', 'REMOTE_ADDR': '111.111.111.111', 'wsgi.errors': <_io.TextIOWrapper name=2 mode='w' encoding='UTF-8'>, 'wsgi.multithread': False, 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.input': <uwsgi._Input object at 0x7ffa3deaf390>, 'SCRIPT_NAME': '', 'HTTP_ACCEPT_ENCODING': 'gzip', 'uwsgi.node': b'server.myserver.com'} Shout I convert the byte string from request.body to a dictionary, or is there an easier way to access the data? -
Display Django logs in templates
I'm working on a project with Python(3.6) and Django(1.10) in which I'm doing some execution in Django views.I'm printing some messages and other execution information in the console but I want to display this information inside the template which is going to be rendered after the completion of a request from Django views. Here's an example code from my Django views: # Start deployment # Setup istio on cluster service = discovery.build('container', 'v1beta1', http=views.getGoogleAuth(), cache_discovery=False) svc_req = service.projects().zones().clusters().get(projectId=deployment.project, zone=deployment.zone, clusterId=deployment.cluster) svc_res = svc_req.execute() print('Status is : {}'.format(svc_res['status'])) status = svc_res['status'] while status != 'RUNNING': svc_res = svc_req.execute() status = svc_res['status'] print('Current Status is : {}'.format(svc_res['status'])) print('Fetching Cluster configs ....') print(subprocess.call( 'gcloud container clusters get-credentials ' + deployment.cluster + ' --zone ' + deployment.zone + ' --project ' + deployment.project, shell=True)) print('Cluster is still Provisioning - Current Status is: {}'.format(status)) How can I display this log information inside Django template when the request has been completed. Help me, please! Thanks in advance!