Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF change url to absolute url
i uploaded some file to server you can see the adress: "file": "/upload/user_1/backup.zip", can you please tell me how can i change it to absolute url like: localhost:8000/upload/user_1/backup.zip", we had some function linke get absolute url in django i dont about drf its my serializer class: class ProductSerializer(ModelSerializer): product_ratings = ProductRatingsSerializer(many=True, read_only=True) product_video = ProductVideoSerializer(many=True, read_only=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name + ' ' + obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'title', 'mini_description', 'you_learn', 'you_need', 'full_description', 'price', 'video_level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_video' ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author', 'product_ratings'] def validate_title(self, value): if self.context['request']._request.method == 'POST': qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value -
set data in html django
I learning django rest. And now i wont output some json data in html. My json: {'Resul': {'Period Start': '2017-01-01', 'Period End': '2017-12-12'}} then i send it json to html: context = {'Resul': json_data['date']} content = render_to_string('balance.html', context) json_data['date'] - {'Period Start': '2017-01-01', 'Period End': '2017-12-12'} in html i write this code Period: {{ Resul['Period Start'] }} - {{ Resul['Period End'] }} but have error: Could not parse the remainder: '['Period Start']' from 'Resul['Period Start']' -
Adding new ManyToMany object in UpdateView
I have searched but can't find an answer to my query. I would like a similar functionality in front-end as is possible when adding an object in the Admin site (where you get a little green "add" button next to the select box for a ManyToMany relationship). This is my (simplified) Client model: class Client(models.Model): name = models.CharField(max_length=60) competitors = models.ManyToManyField(Competitor) def __str__(self): return self.name This is my UpdateView view within views.py: class ClientUpdate(UpdateView): model = Client fields = [ 'name', 'competitors', ] And this is my template: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> Can I change those aspects to be able to add a Competitor at the point of adding or updating a Client? -
Django: "initial_value must be str or None, not bytes" error
While learning Django and Python I am trying to download a pdf file. The files content should be from a html template. I am trying to do this using the pisaDocument example(and any other example from the internet are exactyle the same). In my case I am getting the: initial_value must be str or None, not bytes error on the StringIO(html.encode("utf-8")) part. I understand that the problem is that StringIo need a str and it returns bytes, but how can i convert the bytes to str? from django.http import HttpResponse, Http404 from django.shortcuts import render, redirect from django.template.loader import get_template from django.views.decorators.csrf import csrf_exempt from io import StringIO, BytesIO from cgi import escape def export(request): if(request.POST): client = request.POST.get('client') doc = request.POST.get('doc') template = get_template('files/insurance.html.twig') html = template.render() result = StringIO(html) pdf = pisa.pisaDocument(StringIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) else: raise Http404("POST data not found") -
How important is to have NAT for security for a Web application
I am using AWS for a Django web application. I have configured a public subnet in which I have a web server. The security group associated with it only allows ports 443, 80, 22, 123. I have a private subnet in which I have a DB server. The security group associated with it only allows 5432 from the other security group. So do I need to configure a NAT instance to which a public address is attached and only have private IP for the web server? How much does this sort of setup help with security or any other benefits? Is this sort of setup a must? -
how to create multiple user for roles django
how to create and show model and forms for different roles in django. I need admin,teacher,student roles. each role have different fields and permission levels so that I need to create for different form field for each role. ->admin can create teacher user ->teacher can create student user can any one can help me. -
Django - How number of apps affects framework's speed?
I am very new to Django and would like to know how number of installed apps affect the speed how pages on Django based site are served (all Google shows it is how to optimize Django for speed...) By "installed apps" I mean typical back-end apps, with no pages generated, no templates, like for example an app to sync the database with another one once a day, does its existence affects how other pages are served (from other apps)? Would it be better run the task from separate script executed on same server as Django site? Does it make difference at all? Thank you -
Django Rest Framework : Filtering against Table Field value
I'm improving my Django Web App with Django Rest API part and I have a question according to filtering against table field value. I have my serializer class like this : class IndividuResearchSerializer(serializers.ModelSerializer) : class Meta : model = Individu fields = [ 'id', 'NumeroIdentification', 'Nom', 'Prenom', 'VilleNaissance', ] My views.py file with this class : class IndividuResearchAPIView(ListAPIView) : permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,) serializer_class = IndividuResearchSerializer def get_queryset(self): queryset = Individu.objects.all() NIU = self.request.query_params.get('NumeroIdentification') queryset = queryset.filter(NumeroIdentification=NIU) return queryset And my pythonic file which let to simulate connexion from another software based to API Rest : import requests mytoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IkFkbWluIiwiZXhwIjoxNTE5NzMxOTAxLCJlbWFpbCI6InZhbGVudGluQGRhdGFzeXN0ZW1zLmZyIiwib3JpZ19pYXQiOjE1MTk3MjgzMDF9.493NzJ4OUEzTKu5bZsZ9UafMwQZHz9pESMsYgfd0RLc" url = 'http://localhost:8000/Api/Identification/search/' NIU = "I-19312-00001-305563-2" response = requests.get(url, NIU = NIU, headers={'Authorization': 'JWT {}'.format(mytoken)}) print(response.text) I would like to enter a NIU value into my request in order to filter my table and return the object according to this NIU. For example, in my database I have this object : I would like to return this object thanks to my API but I don't know if my function get_queryset is well-writen and How I can write my API request. Into my urls.py file, I have : url(r'^search/$', IndividuResearchAPIView.as_view() , name="Research"), So I am not making a … -
Unable to login a custom user using CBV in django
While trying my luck with Class Based views in Django, I am unable to get a custom user logged in. Here is my view: class Loginview(FormView): form_class = LoginForm template_name = 'login.html' def get(self, request, *args, **kwargs): return render(request, 'login.html', {'form': LoginForm}) def form_valid(self, form): return redirect('dashboard') def form_invalid(self, form): return render(self.request, 'login.html', {'form': form}) My form: class LoginForm(ModelForm): class Meta: model = Company fields = ['email', 'password'] My model: class Company(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=50) address = models.CharField(max_length=50) phone = models.CharField(max_length=50) date_joined = models.DateTimeField(auto_now_add=True) email = models.EmailField(max_length=50, unique=True) is_staff = models.BooleanField(default=True) email_confirmed = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserManager() FYI this is a custom model and has a separate user Manager. Whenever I submit the login template with the email and password fields, it returns me a form error saying that email and password do not match while they should be matching. -
how to convert evtx log file into cef log file using python script
List item i want to convert evtx log file in windows to convert in to .cef format using python script with the help of wmi so please suggest some answers for this problem -
LginRequiredMixin doesnt work in Django
i used LoginRequiredMixin restrict access only to logged in user. but still i am able to access that page. what mistake am i making here. VIEWS.PY class AddSupportUserView(LoginRequiredMixin,View): def get(self, request): form_class = AddSupportUserForm return render(request, 'add_support_user.html', { 'form': form_class, }) def post(self, request): form_class = AddSupportUserForm username = request.POST.get('username') email = request.POST.get('email') try: user_obj = User.objects.get(username=username) return render(request, 'add_support_user.html', {'errors': 'User already exits', 'form': form_class}) except User.DoesNotExist: user_obj = User.objects.create_user(username=username, email=email, is_staff=True, is_superuser=False) user_obj.set_password(email) user_obj.save() group_obj = Group.objects.get(name='support_group') user_obj.groups.add(group_obj) return HttpResponseRedirect('/admin/auth/user/') -
django dictionary for loop not printing anything
There are already a lot of questions+answers regarding for loops in django, but none of the solutions work for me, so there must be something fundamentally wrong. I have a dictionary in python/json (tried both) that I want to loop through and print. Doing the following print a new line for each character {% for item in data.dict %} <p>{{item}}</p> {% endfor %} so something like this get's printed { ' N o d e ' : The following code straight up prints nothing {% for key, values in data.dict.items %} <p>{{key}}</p> {% endfor %} Data is the name of my registered model and object is one of its variables. In my Views.py I have something similar to this: Data.objects.create( dict=theDictIAmPassing }.save -
AJAX django get request
Can u help me, please! I need to render a new content, when i click on button without refresh page. Now I am using jQuery cookie plugin, save button id into cookie, then read in view that value and render page. But it does not look friendly :c My JS: function initBrandSelector() { $('.tab button').click(function(){ var brand = $(this).val(); if (brand) { $.cookie('current_brand', brand, {'path': '/', 'expires': 365}); } else { $.removeCookie('current_brand', {'path': '/'}); } location.reload(true); return true; }); } $(document).ready(function(){ var brand = $.cookie('current_brand'); if (brand) { $('.tab button[value=' + brand + ']').addClass("active"); } initBrandSelector(); }); My view: def smartphones_list(request): current_brand = get_current_brand(request) if current_brand: smartphones = Smartphone.objects.filter(brand=current_brand) else: smartphones = Smartphone.objects.all() context = paginate(smartphones, 6, request, {}, var_name='smartphones') return render(request, 'main/smartphones_list.html', context) -
Integrity error when trying to save many-to-many field data
I have a Course model and a StudentData model. In order to enroll students to courses, I added a many-to-many field to the Course model. I can list the students with a checkbox, but problem is, when I press the Enroll button, to add those students to the course, I get the following error: http://dpaste.com/3E1XR4P #views.py if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): form.save() redirect('classroom') else: form = CourseForm() #forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ('student', ) widgets = { 'student': forms.CheckboxSelectMultiple } #models.py class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "Doctoral Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) slug = models.SlugField(max_length=140, unique=False, default=None, null=True, blank=True) class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default=None) name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, verbose_name="Course Teacher", related_name='%(class)s_course_teacher') teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True, verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher') slug = models.SlugField(max_length=150, unique=True) student = models.ManyToManyField('StudentData', default=None) class StudentData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) student_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) enrolled = models.BooleanField(default=False) #enroll.html <form action="" … -
502 Bad Gateway. Django Google App Engine
I deployed my django project in GAE and I get the 502 Bad Gateway error on all pages except the main one. The previous version was working, but is not working since I added API calls for storage (storages.backends.gcloud.GoogleCloudStorage). I added environment variable GOOGLE_APPLICATION_CREDENTIALS in both settings.py and app.yaml. Log shows this error: [error] 32#32: *111 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: , request: "GET /accounts/login/ HTTP/1.1", upstream: "http://xxx.xxx.xxx.xxx:8080/accounts/login/", host: "xxxx.appspot.com", referrer: "https://xxxx.appspot.com/" All is working in local, so that message is all I have. I tried things from google groups and other stackoverflow questions but it's not working. Thank you. -
Casting result from Database Function not working
I'm using the following to get the ISO Week Date: class DateWeek(Func): """ Return the ISO8601 Week Number """ def as_mysql(self, compiler, connection): self.function = 'WEEK' self.output_field = IntegerField() self.template = 'CONVERT(%(function)s(%(expressions)s, 3), UNSIGNED INTEGER)' return super().as_sql(compiler, connection) Which works fine: MyObj.annotate(wk=DateWeek('date')).values('wk') <QuerySet [{'wk': 1}, {'wk': 21}]> ...until I want to do something like: MyObj.annotate(wk=DateWeek('date')).filter(wk__gt=20) When I try and do this I get a dateparse error as Django is trying to calculate the filter assuming that wk is a date of some kind. I've set the output_field to IntegerField, is there anything else I should be doing? -
Channels 2 - When two users are on the same websocket connection, consumer is run twice
Based on the Channels 2 example, I've implemented a one-to-one chat with message persistence. I'm having an issue with chat_message() being run twice(message being broadcast/saved twice) whenever two users are sharing the same channel(live-chatting with each other). When they aren't on the same websocket connection, the messages will work as normal(send once). What's wrong with my configuration? This is the entire consumer--the saving happens in the very last function--chat_message(). It is called in send_room() itself called in receive_json() : class ChatConsumer(AsyncJsonWebsocketConsumer): ##### WebSocket event handlers async def connect(self): """ Called when the websocket is handshaking as part of initial connection. """ # Are they logged in? if self.scope["user"].is_anonymous: # Reject the connection await self.close() else: # Accept the connection await self.accept() # Store which rooms the user has joined on this connection self.rooms = set() async def receive_json(self, content): """ Called when we get a text frame. Channels will JSON-decode the payload for us and pass it as the first argument. """ # Messages will have a "command" key we can switch on command = content.get("command", None) recipient = content.get("recipient", None) sender = self.scope["user"] try: if command == "join": # Make them join the room await self.join_room(content["room"]) previous_message_list = await … -
dajngo text in form is not translating
I have the following code in my forms.py: def validate(self, request): try: id_exists(request, self["user"].data) except: self.add_error('user', ugettext_lazy("id is not available")) the problem is when my 'user' filed is not validated in my validate function, the error is displayed in English, however other texts in my whole project are translating. using ugettext_lazy nor ugettext solved the problem. Is there anything I am missing? tnx -
Django: failed: Error during WebSocket handshake
I'm getting below error WebSocket connection to 'ws://localhost/ws/testNoti?subscribe-broadcast&publish-broadcast&echo' failed: Error during WebSocket handshake: Unexpected response code: 500 Websocket connection is broken! supervisor conf file [unix_http_server] username = ubuntu password = password [program:uwsgi] command=/home/laptop30/bxd-life/venv/bin/uwsgi --ini /home/laptop30/bxd-life/bxd/bxd.ini autostart=true user=ubuntu autorestart=true stderr_logfile = /home/laptop30/bxd-life/logs/err.log stdout_logfile = /home/laptop30/bxd-life/logs/out.log stopsignal=INT [program:uwsgi_ws] command = /home/laptop30/bxd-life/venv/bin/uwsgi --http :8080 --gevent 1000 --http-websockets --workers=2 --master --module bxd.wsgi_websockets #directory=/home/laptop30/bxd-life/bxd autostart=true autorestart=true starttries=5 user=ubuntu environment=DJANGO_SETTINGS_MODULE='bxd.settings' nginx conf file upstream app_server { server localhost:8000; } upstream web_socket_server { server localhost:8080 fail_timeout=0; } server { listen 80; server_name _; location /static/ { alias /home/laptop30/bxd-life/bxd/static/; expires 30d; } location /ws/ { proxy_pass http://web_socket_server; proxy_http_version 1.1; #proxy_redirect ws://$server_name; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } } wsgi_websockets.py import os import gevent.socket import redis.connection redis.connection.socket = gevent.socket os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bxd.settings") from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() The above is working fine with ./manage.py runserver but not with nginx! Any help would be very much appreciated. -
Django: Prevent users from editing other accounts
I have created a simple API for editing user profile. class EditProfile(generics.UpdateAPIView): serializer_class = UserSerializer queryset = get_user_model().objects.all() permission_classes = (IsAuthenticated,) How can I prevent the user from editing other user's profile? -
DjangoRestFramework URLS with Django2.0
I'm trying to set up DjangoRestFramework with a Django2.0 project which means url(r'^something/' ... has been replaced with path(something/ ... I'm trying to work out how to set my rest_framework patterns. This is what I have: router = routers.DefaultRouter() router.register(r'regulations', api.RegulationViewSet) router.register(r'languages', api.LanguageViewSet) urlpatterns = [ ... path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ... ] If I got to http://127.0.0.1:8000/regulations I simply get Page not found (404) How should I set up my urlpatterns? -
How do I deserialize list of multiple objects in django rest framework?
I am developing a rest API that gets requests composed of multiple objects and saves them to the database. Then, another array of objects is returned as the response. All objects are of only one model. class Ratings(models.Model): id = models.AutoField(primary_key = True) userId = models.IntegerField() movieId = models.IntegerField() rating = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) timestamp = models.DateTimeField(auto_now = True) class RatingsSerializer(serializers.ModelSerializer): class Meta: model = Ratings fields = ('userId','movieId','rating') class RecommendationGenerator(generics.ListCreateAPIView): queryset = Ratings.objects.filter(id__in=(1,2))#all() serializer_class= RatingsSerializer def post(self, request, format='json'): serializer= RatingsSerializer(data = request.data, many = True) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_403_FORBIDDEN) When I test it in Postman with the JSON: [{ "userId": 13, "movieId": 1765, "rating": 5 }, { "userId": 13, "movieId": 1733, "rating": 3 }, { "userId": 13, "movieId": 1713, "rating": 2 }, { "userId": 13, "movieId": 963, "rating": 2 } ] The result is []. But for { "userId": 13, "movieId": 1765, "rating": 5 } The result is { "userId": 13, "movieId": 1765, "rating": 5 } How do I deserialize this data? What am I doing wrong here? -
Django: Overriding 'objects' of superclass without changing the code in superclass
I have 2 classes defined like: class Parent(models.Model) def foo: pass And the child class: class Child(Parent): def foo: print('abc') Now I want to override the 'objects' of class Parent. Normally it will go like this: class Parent(): objects = Child() But I can't modify class Parent because it's a third party library. Is there any workaround for this problem? -
must we render serialized data to json before sending response? DRF
The answer to this question is confusing me. Multiple Models in Django Rest Framework? the answer is to a question of sending multipule models in a response. I have the same use case. the author of the answer has this: def get(self, request, format=None, **kwargs): cart = get_cart(request) cart_serializer = CartSerializer(cart) another_serializer = AnotherSerializer(another_object) return Response({ 'cart': cart_serializer.data, 'another': another_serializer.data, 'yet_another_field': 'yet another value', }) but I am keeping with the documentation. http://www.django-rest-framework.org/api-guide/serializers/#serializing-objects EXAMPLE FROM DOCS serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} from rest_framework.renderers import JSONRenderer json = JSONRenderer().render(serializer.data) json # b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}' so which one is it? Do I JSON or not JSON. This is what I currently have. def get(self, request, format=None): searchcityqueryset = SearchCity.objects.all() neighborhoodqueryset = SearchNeighborhood.objects.all() serializedsearchcity = SearchCitySerializer(searchcityqueryset) serializedsearchneighborhood = SearchNeighborhoodSerializer(neighborhoodqueryset) jsonsearchcity = JSONRenderer().render(serializedsearchcity.data) jsonsearchneighborhood = JSONRenderer().render(serializedsearchneighborhood.data) return Response({ 'searchcity': jsonsearchcity, 'searchneighborhood': jsonsearchneighborhood, }) -
Why does testing uploaded media files during testing gives 404 with django webtest?
I have the following TestCase that adds an uploaded file to the model: from django_webtest import WebTest class LeaveDocumentPermissionTests(WebTest): '''Tests for supporting doc permissions ''' def setUp(self): # User uploads a supporting doc self.supporting_doc_leave_request = LeaveRequest.objects.create( user=self.user1, start_date='2017-12-10', end_date='2017-12-21', supporting_doc=SimpleUploadedFile( name='my-sick-note.pdf', content=open(TEST_PDF_PATH, 'rb').read(), content_type='applicaiton/pdf' ) ) def test_uploading_user_can_access(self): '''Ensure user that uploaded the file can view and download it''' file_url = self.supporting_doc_leave_request.supporting_doc.url response = self.app.get( file_url, user=self.user1, ) self.assertEqual(response.status_code, 200) The response I get is: webtest.app.AppError: Bad response: 404 Not Found (not 200 OK or 3xx redirect for http://testserver/media/uploads/leave/user_22/2017-12-10-my-sick-note_EZSplOs.pdf) b'<h1>Not Found</h1><p>The requested URL /media/uploads/leave/user_22/2017-12-10-my-sick-note_EZSplOs.pdf was not found on this server.</p>' So the uploaded file seems to not exist. Why is the file not being uploaded to the server or served? Whoops I think the test server is not serving the media url. I have the following in urls.py: if settings.DEBUG: urlpatterns + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) So when the tests run settings.DEBUG is False so that url is not there.