Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to allow others to connect to my Django website?
I'm very new to Django website hosting. Now that I have created a website, and I wish the users can connect to my website within a local network. However my website now can only be accessible from the localhost (my pc), the others are not able to connect to my website when typing my ip address for example xxx.xxx.xxx.xxx:8000 on their browser. I launch the service on my localhost using # python manage.py runserver. May I know if there is a way/command to allow the others to connect to my website? Thank you very much and appreciate your help! Note: I have tried # python manage.py runserver 0.0.0.0:8000 as well, which allow all incoming, but it didn't work. -
Django-REST API Raising an Error in Serializer when Email Exisit
so a quick over view, the Front ends sends me a email,password and confirmpassword. and i store them in an API and then will later on store in the database, but for the mean time, i am only saving them when the sent email doesn't exist first of all that's my views.py class UserList(APIView): def get(self,request): users = Users.objects.all() serializer = UserSerializer(users,many=True) return Response(serializer.data) def post(self,request): serializer = UserSerializer(data=request.data) #here i serialize the data entered by the user if serializer.is_valid(): try: #and then i check if the email already exists or not, if it not exist, it will save it in the API, if not it should raise an errro!, i tried saying serializers.validationerror bs that wouldn't work at all. match = Users.objects.get(email=serializer.validated_data["email"]) except Users.DoesNotExist: # Unable to find a user, this is fine] serializer.save() print ('money here come the money') return Response(serializer.data, status=status.HTTP_201_CREATED) raise (?!) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Why Model field validation happens before validate or validate_<field> is called?
I just started learning Django Rest Framework and I can't understand why DRF runs Model field validation before Own Validation I have a model which has a URLField and basically all I want to add http:// or https:// before it validates, so wrote custom validation method class ShortenerSerializer(serializers.ModelSerializer): class Meta: extra_kwargs = { 'count': {'read_only':True} } fields = ('id', 'url', 'short_url', 'count', 'created_at') model = Shortener def validate_url(self, url): if not 'http://' in url and not 'https://' in url: url = 'http://' + url url_validate = URLValidator() try: url_validate(url) except: raise serializers.ValidationError("Please Enter a Valid URL") return url I even overide the validate method but again it is called after model field validation as it raises Exception. I guess i need to overide some method but no idea which one to override. -
xframe_options_exempt not working with django
So I've configured a website that allows me to display data from the waves blockchain onto a django site running on an AWS EC2 instance. The webpage works as shown here www.wavesico.tk/Project/get-ico/jacks-easter-eggs In my views file I have included: from django.views.decorators.clickjacking import xframe_options_exempt and @xframe_options_exempt def crowdFund(request, company_name): c = WavesCompany.objects.get(name=company_name) data = tokens.getTokenData(c.holdersKey, c.tokenKey) return render(request, 'crowd_fund.html', data) I have also included the middleware in my settings file: 'django.middleware.clickjacking.XFrameOptionsMiddleware', However, Chrome still reports the error 'Refused to display 'https://www.wavesico.tk/Project/get-ico/jacks-easter-eggs/' in a frame because it set 'X-Frame-Options' to 'sameorigin' I have tried changing the 'render()' function to 'HttpResponse' but still no luck. Thanks everyone, Jack -
Handling ManyToMany field in DRF serializer
I have the following Django models: class Article(models.Model): name = models.CharField(max_length=30, unique=True) tags = models.ManyToManyField(Tag) ... class Tag(models.Model): name = models.CharField(max_length=30, unique=True) ... I would like to be able to add a list of existing tags while creating Article via POST request, i.e. { 'name': 'My Org Name', 'tags': [1,2,3] } Where [1, 2, 3] is a list of tag ids. My serializer looks like this: class ArticleSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, read_only=True, allow_null=True) class Meta: model = Article fields = ('name', 'tags', ...) def create(self, validated_data): # in create I will add tags, i.e. article.add(tag) return Article.objects.create_article(**validated_data) But then I would like to do some validation such that I know that tag ids that are passed in belong to existing Tag instances. So I tried adding the method below to my serializer. def validate_tags(self, tags): if tags: for tag in tags: if not Tag.get(pk=tag): raise ValueError('Tag with id not found...') return tags For some reason this validation method is not triggered. I'm trying to figure out the right way to handle adding tags to articles, any suggestions would be highly appreciated. -
django model field in url
I've been learning django for a little bit now but I've ran myself into the ground with this one. I've been looking for an answer for two days and, annoyingly, I think I stumbled across it at one stage but I didnt realise until later that I forgot to change the template (by which time I forgot what post I read so I could recreate it). I'm trying to create something where users can signup then create a "channel" to store their stuff. I have that working just fine, but now I want to make it so the URL's look nicer (like Github or youtube). I'd like the URL's to display as "example.com/channels/channel-name" rather than "example.com/channels/1" This is what I have so far: url: url(r'^(?P<slug>[\w-]+)/$', channel_views.DetailView.as_view(), name="channel-detail"), (note: when slug is changed out for (?P< pk >[0-9]+) it works) views: class DetailView(generic.DetailView): model = Channel template_name = 'channels/channel-detail.html' models class Channel(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=150) def get_absolute_url(self): return reverse('channels:channel-detail', kwargs={'slug':self.name}) index.html: <a class="channel-link text-center" href="{% url 'channels:channel-detail' channel.id %}">{{channel.name}}</a> I feel like I need to run the "name" field through slugify then call that in the HTML template instead of "channel.id"? -
I have deleted the registration from site-packages but still it is not showing me import error
urls.py in my main app my project structure, it can be seen that there is no module named registration Still when i run the server it doesn't give me any error any runs as it was before deleting. Please help me to resolve this issue. -
What is the purpose of defualt=False in django management command
I'm trying to write a management command in django. According to the documentation default is set to False. I would assume that the default is the default value of the argument that is being passed. Make django custom management command argument "Not Required" What's the benefit of stating that deafult=False class Command(BaseCommand): help = "helps in doing stuff" def add_arguments(self, parser): parser.add_argument( 'name', type=str, default=False help="The name of the folder to be created") def handle(self, *args, **options): pass -
Celery task.delay blocked in docker container
I use celery in my django project. It works well on my MacBook and in a CentOS VM. When I run it in a docker container, the request which contains add.delay(add is a task) method is always blocked. I created a demo project on github: https://github.com/fengyouchao/proj_test My task: @shared_task def add(x, y): return x + y My view: def index(request): a = int(request.GET.get('a', 1)) b = int(request.GET.get('b', 2)) add.delay(a, b) return HttpResponse("Hello world") def hello(request): return HttpResponse("hello") In the demo project I created three services in docker-compose.yml: web - The service which run "manage.py runserver 0.0.0.0:8000" celery - The service which run "celery" rabbitmq - The service wich run rabbitmq-server Run services docker-compose up Test curl localhost:8000 # blocked curl localhost:8000/hello # OK Run the django project in current system(use the same rabbitmq-server in docker container) manage.py runserver 0.0.0.0:18000 Test curl localhost:18000 # OK , and the "celery" service printed task logs This problem has been bothering me for a long time, and I don't know where the problem is. I hope someone can help me. Thanks! -
Apps aren't loaded yet exception occurs when using multi-processing in Django
I'm doing a Django project and try to improve computing speed in backend. The task is something like a CPU-bound conversion process Here's my environment Python 3.6.1 Django 1.10 PostgreSQL 9.6 And I stuck with following errors when I try to parallel a computing API by python multi-processing library. File "D:\\project\apps\converter\models\convert_manager.py", line 1, in <module> from apps.conversion.models import Conversion File "D:\\project\apps\conversion\models.py", line 5, in <module> class Conversion(models.Model): File "C:\\virtenv\lib\site-packages\django\db\models\base.py", line 105, in __new__ app_config = apps.get_containing_app_config(module) File "C:\\virtenv\ib\site-packages\django\apps\registry.py", line 237, in get_containing_app_config self.check_apps_ready() File "C:\\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") look like each process import Conversion model and Conversion model is like from django.db import models Conversion(model.Model): conversion_name = models.CharField(max_length=63) conversion_user = models.CharField(max_length=31) conversion_description = models.TextField(blank=True) ... Below is my sample function which I want to parallel, each iteration is independent but will access or insert data into SQL. Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] for p in p_list: list_result = self.Couputing_api(p) list_merge_result.extend(list_result) and I'm try to do is from multiprocessing import Pool Class ConversionJob(): ... def run(self, p_list): list_merge_result = [] p = Pool(process=4) list_result = p.map(self.couputing_api, p_list) list_merge_result.extend(list_result) In computing_api(), it'll try to get current conversion's info which has completed and … -
Pass xml file from directory to javascript using django
I'm creating an .xml file and then trying to pass this file to javascript, so I could use it there. Here's the output in browser's console: Failed to load file:///D:/Geoinformation%20systems/Maps/Markers/static/Markers/data.xml: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. Here is my view function: def index(request): markers_set = Marker.objects.all() root = Element('markers') tree = ElementTree(root) for m in markers_set: name = Element('marker') name.set('id', str(m.id)) name.set('name', m.name) name.set('address', m.address) name.set('lat', str(m.lat)) name.set('lng', str(m.lng)) name.set('type', m.type) root.append(name) tree.write(open(r'Markers\static\Markers\data.xml', 'wb')) return render_to_response('index.html', {'xmldata' : r'D:\Geoinformation systems\Maps\Markers\static\Markers\data.xml'}) Here is a piece of template "index.html" where javascript code is located: <html> <body> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(-33.863276, 151.207977), zoom: 12 }); var infoWindow = new google.maps.InfoWindow; <!--Here I'm taking data that is passed--> downloadUrl('{{ xmldata }}', function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName('marker'); ... function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } }); } </script> </html> How should I pass/get the file, so not to failing loading it? I know … -
TypeError: save() missing 1 required positional argument: 'self'
this is views class RegisterView(View): def get(self,request): register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get("email", '') pass_word = request.POST.get("password", '') user_profile = UserProfile user_profile.username = user_name user_profile.email = user_name user_profile.password = make_password(pass_word) user_profile.save() #error send_register_email(user_name,"register") I want to save user_profile to mysql,But user_profile.save() has an error, TypeError: save() missing 1 required positional argument: 'self',How should I solve it? -
Django admin cannot load data from database
After I create feature translate use Django model translation and then I was deployed Django project to the server and get I problem, My code was running well, in local development, Django admin can load data from the database without any problem. But the problem is when code deployed to server data in Django admin cannot load, they load blank data without error or any problem. But in database data is still available. models.py: from django.db import models from base.models import BaseModel class Platform(BaseModel): name = models.CharField(max_length=255) icon = models.ImageField(upload_to='gopay_platformicon') order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class Method(BaseModel): name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True) platform = models.ForeignKey(Platform) note = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='gopay_method', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name class TopupStep(BaseModel): name = models.TextField() method = models.ForeignKey(Method) picture = models.ImageField(upload_to='gopay_topupstep', blank=True, null=True) order = models.PositiveIntegerField(default=1) class Meta: ordering = ['order'] def __str__(self): return self.name translation.py: from modeltranslation.translator import translator, TranslationOptions from . import models class MethodTranslationOptions(TranslationOptions): fields = ('name', 'description', 'note', ) class TopupStepTranslationOptions(TranslationOptions): fields = ('name', ) translator.register(models.Method, MethodTranslationOptions) translator.register(models.TopupStep, TopupStepTranslationOptions) admin.py : from django.contrib import admin from base.admin import BaseAdmin from gopay … -
Django Roles and permissions
I am working on django roles and permissions, for this i am using django-role-permissions library. Issue : Create one role 'Director', director role assign user able to login into django admin area and view ( only view permissions ) filter data ( just like that : student which have 90% and above ) . Note : I already have two roles 1. Teacher 2. Student. -
Using django app config to change model.Meta.managed
Given the following architecture of django projects apps and database schemas: There is a django app which I want to share between several django projects. Each project has it's own postgresql schema in behind. All schemas live in the same postgresql database. One project is owner of the apps data, this project is responsible to run migrations and the data should live in its schema. All other projects may access the data from the other projects schema, because they have a proper postgresql search path set. We already use this concept with an app that has all models set to unmanaged, which works. But database changes always needs to be done manually. I'd like to benefit from django migrations and therefore I want my models either managed or unmanaged. Do you think app config is good place to change the models meta? Any other suggestions and approaches on how to solve the requirement are also welcome. -
Not able to make a ajax request in django using postgresql
So i've developed a django app,and i'm trying to POST something to Postgresql,i understand that CSRF token is necessary during an ajax request made to a view,which i have done,this is my csrf.js,which i've included in my header template // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); and this is my ajax request being made in a template $.ajax({type: 'POST', url: '/sample/saveData/', // some data url data: {param: workHours.length, param1: $(getDayName[i]).text(),param2: bla,param3: bla1,param4: bla2}, // some params success: function (response) { // callback if (response.result === 'OK') { if (response.data && typeof(response.data) === 'object') { // do something with the successful response.data // e.g. response.data can … -
Uncaught TypeError: Cannot read property 'weight' of undefined [D3.js jquery-3.2.1.slim.min.js]
I am using Django framework and D3.Js to render some svg graphs. Everything works fine when i test in my local system. But while I deploy to the production server, the "Uncaught TypeError", pops in and fails to render. Following are the things I have tried, 1. commented the google analytics to get more detail bug report [no luck] 2. disabled the force in JS, the figures renders but the graph messed up. [do not want to do this] 3. Tried changing the name of property, but the error still persists for property like "name". Is there any permission issue I should check? Any help to get the bug will be very helpful. -
Django - filtering queryset with optional FormFields
Let's say I have a model: class House(models.Model): (...) price = models.DecimalField(decimal_places=2, max_digits=8) area = models.DecimalField(decimal_places=2, max_digits=6) And I have a Form for searching of Houses: class SearchHouseForm(forms.Form): price_min = forms.DecimalField(required=False, initial=0, decimal_places=2, max_digits=8) price_max = forms.DecimalField(required=False, initial=999999, decimal_places=2, max_digits=6) And the view function: def search_for_houses(request): queryset = House.objects.all() if request.method == 'GET' and 'search-submit-button' in request.GET: form = SearchHouseForm(request.GET) if form.is_valid(): queryset = queryset.filter( price__lte = form.cleaned_data['price_max'], price__gte = form.cleaned_data['price_min'] ) else: (...) return render(request, template, {'house_list': queryset, 'form': form}) I have a problem with the .filter()-ing. I want to apply the filter if and only if the user provides any value in the form field. If the price_max field is left blank, only the price__gte = form.cleaned_data['price_min'] should be applied. If both price_max and price_min are left blank, all House objects should be returned. Currently I get ValueError Cannot use None as a query value Is there a clean way to do that? The only thing I can think of is a long list of if statements for all such optional fields: if form.cleaned_data['price_max'] is not None: queryset = queryset.filter((...)) if form.cleaned_data['price_min'] is not None: queryset = queryset.filter((...)) (...) This does not seem as a good idea, especially … -
Paginator Number of Pages does not update in HTML after filtering results - Django
Paginator Number of Pages does not update in HTML after filtering with django_filter. html file <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.</span> The page_obj.paginator.num_pages is the initial number (without any filters) of all results in the table (example: I got 12 results and showing 3 results/page => 4 pages) views class SearchBookView(ListView): template_name = "booksearch.html" paginate_by = 3 model = Book def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) book_qs = Book.objects.all() book_filter = BookFilter(self.request.GET, queryset=book_qs) paginator = Paginator(book_filter.qs, self.paginate_by) print(paginator.num_pages) ### Prints the correct num pages everytime even after filtering page = self.request.GET.get('page') try: book_list = paginator.page(page) except PageNotAnInteger: book_list = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) context['book_list'] = book_list context['book_filter'] = book_filter return context After adding a filter (let's say after filtering it shows 5 results) page_obj.paginator.num_pages should be 2 in my HTML, right? Although in my view in print(paginator.num_pages) it shows 2, in the HTML it stays the original 4 pages. How can I pass this to the HTML file? WORKAROUND I did a workaround but it is kind of ugly: in my view I added a context['num_pages'] = paginator.num_pages and pass it my HTML: <span>Page {{ page_obj.number }} of {{ num_pages }}.</span> Any suggestions on how to … -
How to encrypt the Django website?
Our company has developed a website system using Django, and we can sell to other merchants (set up the website on the merchant's servers), the merchants can show the website to their users. But our company does not want to let merchants see the website source code, is there some way to encrypt the Django website? Or some other way that the merchants cannot access the website source code? -
MultipleObjectsReturned: get() returned more than one Feed -- it returned 2
I'm writing some simple test for an django-model and I'm just using assertEqual and assertNotEqual for it. Now I'm not fully grasping how to test BooleanField in this case. I have a model field like this: duplicate = models.BooleanField(default=False) and I'm writing this test for it, just to check is it equal ` def test_feed_duplicate_create(self): stefan_feed_duplicate = Feed.objects.get(duplicate='False') milan_feed_duplicate = Feed.objects.get(duplicate='False') self.assertEqual( stefan_feed_duplicate.duplicate, 'False') self.assertEqual( milan_feed_duplicate.duplicate, 'False')` But the error that I'm facing is: (venv) vagrant@jessie:/var/www/vhosts/bspotted.net/app$ ./manage.py test --keepdb socialmedia nosetests socialmedia --verbosity=1 Using existing test database for alias 'default'... ............E.................... ====================================================================== ERROR: test_feed_duplicate_create (app.socialmedia.tests.test_feed_model.CommentsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/var/www/vhosts/bspotted.net/app/socialmedia/tests/test_feed_model.py", line 225, in test_feed_duplicate_create stefan_feed_duplicate = Feed.objects.get(duplicate='False') File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/query.py", line 338, in get (self.model._meta.object_name, num) socialmedia.models.feed.MultipleObjectsReturned: get() returned more than one Feed -- it returned 2! ---------------------------------------------------------------------- Ran 33 tests in 0.159s Can someone explain me what is the proper way of testing BooleanField in this case. Thanks. -
Django - Is this possible that the add default values when model is creating?
I want to add some default values in my database when the related model is creating with makemigrations command. For example I have this as model; class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created Date') modified_at = models.DateTimeField(auto_now=True, verbose_name='Update Date') is_deleted = models.BooleanField(default=False, verbose_name='Deleted') class Meta: abstract = True class ModelType(BaseModel): description = models.CharField(verbose_name='Name', max_length=225 ) and as I said before I want to add some default values ("value1", "value2", "value3", "value4") for my ModelType table. Is that possible? -
How to get data from a Formdata object in my views?
My AJAX call sends a FormData object with an uploaded image data inside it: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); $.ajax({ type:'POST', url: '/change_banner_image/', data : { form_data: form_data, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, traditional: true, cache: false, success: function(response){ console.log('Success'); }, }); }); and I succesfully receive the call in my views: def change_banner_image(request): if request.is_ajax(): data = request.POST.get('form_data') profile = get_object_or_404(Profile, user=request.user) profile.image = data profile.save() print(data) return HttpResponse() print(data) prints: [object FormData]. So how would I get the uploaded image from this FormData object? Which will then be the value of profile.image (which is a FileField). -
Django: return old data
I deleted the database - to update the new version of the data psql -U postgres - drop my_db created new with same name 'my_db' added new data: psql -U postgres -d my_db < my_db.sql after it in admin page i see new data - my_site/admin but on client side - i see data which i saw before drop database I clean cache, all data for this site what could it be? did anyone come across this? -
Django how to merge query results
I have an ArrayField with choices and i'm trying to filter the choices: PAYMENT_CASH = '0' PAYMENT_CARD = '1' PAYMENT_BANK = '2' PAYMENT_ONLINE = '3' PAYMENT = ( (PAYMENT_CASH, _('Cash')), (PAYMENT_CARD, _('Card')), (PAYMENT_BANK, _('Bank')), (PAYMENT_ONLINE, _('Online')), ) options = ArrayField(models.CharField(max_length=1, choices=PAYMENT, default='0'), size=4) When i use Location.objects.filter(city__id='683506').values_list('options', flat=True) it returns me <QuerySet [['0'], ['0', '1', '2', '3'], ['0', '1', '2'], ['0', '1'], ['0', '1', '2', '3']]> I wish to get all the options that are used. How can i merge the query or make them into a list and merge them? This is what i wish to get ['0', '1', '2', '3']