Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass an object file from view to template in Django using Ajax
I am trying to pass an object file (3d object) from a view to a html template using Ajax. Here is the basic code in the view: def guiMesh(request): if request.method == 'POST': if request.is_ajax(): obj = pywavefront.Wavefront( "test.obj") context = {'meshObj': obj} return render(request, 'template.html', context) here is the code the template $.ajax({ url : '', // the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken: csrftoken, cooVertex: cooVertex }, success : function(dataObj) { console.log("dataObj " + dataObj.size) }) The view side seems working as it does not give any error, but the template side seems not receiving the file correctly. Where am I doing wrong? Thank you very much for your help! -
View my Django site hosted in IIS with another computer
I have 2 pc and inside all the 2 i have installed Windows 10 pro X64 from hosted pc: I developpe my app with django==2.1.* I have configure IIS to host my django app I have test, all work like a charm. I have edit my hosts file and add line in the end of my hosts in system32/...etc like this: mycurrenthostedpc_ip myapp.extranet when i finish imake binding in IIS like this: myapp.extranet --->> host mycurrenthostedpc_ip ---->>>> IP address I have configure firewall to accept Inbound and port 80 In the hosted PC when icheck http://myapp.extranet/ ---->>> It work well in the hosted pc But when i check in second pc connect to my network like this: http://myapp.extranet/ or http://hosted_pc/myapp.extranet/ ------>>>> Not working How can i correctly (Please step by step) configure my hosted PC if i want to access to my django app (inside another computer) with this url (http://myapp.extranet/) Thank for advance... -
How do I search via md5 hash in django / postgres within an "OR" statement
I have a model with a title field: class Item(): title = models.TextField(blank=True, null=True) My database has a md5 index on the title field. I would like to search by a hashed md5 string, for example: Item.objects.extra(where=["MD5(title) = hashlib.md5("This is the title")"]) However, I would like to do this WITHIN an OR statement, so my current code looks like this: class ItemManagerQueryset(models.QuerySet): def is_matching_title(item): q_objects = Q() if item.title: q_objects.add(Q(title=item.title), Q.OR) self.filter(q_objects) How can I add a .extra within an OR statement, something like this: class ItemManagerQueryset(models.QuerySet): def is_matching_title(item): q_objects = Q() if item.title: q_objects.add(Q(title=item.title), Q.OR) q_objects.add(Q(extra(where=["MD5(title) = hashlib.md5("This is the title")"])), Q.OR) self.filter(q_objects) -
Cannot run daphne service on Google Kubernetes Engine (docker container) ubuntu
app/project-daphne.service [Unit] Description=daphne server script After=network.target [Service] User=root Group=root WorkingDirectory=/project Environment=DJANGO_SETTINGS_MODULE=settings ExecStart=/env36/bin/daphne -e ssl:8443:privateKey=/ssl-cert/privkey.pem:certKey=/ssl-cert/fullchain.pem asgi:application Restart=always [Install] WantedBy=multi-user.target Dockerfile FROM ubuntu:18.04 RUN apt-get update RUN apt-get install build-essential -y WORKDIR /app COPY . /app/ RUN cp -a project-daphne.service /etc/systemd/system/project-daphne.service RUN systemctl enable project-daphne.service RUN service project-daphne restart # Open port 80 for serving the webpage EXPOSE 80 $ docker build -t project-image . Error: /bin/sh: 1: systemctl: not found The command '/bin/sh -c systemctl enable project-daphne.service' returned a non-zero code: 127 It works on Google GCP Ubuntu 18.04 LTS by run the following commands: $ sudo systemctl enable project-daphne.service $ sudo service project-daphne start But it doesn't work on GCR/docker container I expect the project-daphne service can run on Google Kubernetes Engine/Google Container Registry. -
Django: How to check the view that renders a template
Want to know how to identify and output the view function that renders a template in HTML. Need it for debugging purposes. Something like this: {% if request.view == "index" %} <title>Company Name</title> {% else %} <title>{{ other_page_title }} &raquo; Company Name</title> {% endif %} -
Starting ./manage.py runworker in the background
I wanted to know what my options are of starting ./manage.py runworker in the background. I tried doing this python ./manage.py runworker 2>>./daphneWorker.log >&2 but that does not seem to work either. Any suggestions on how I can make it run in the background ? -
Rest API parameters are empty Serializer without model
In my view, I am not able to retrieve parameter coming in the rest API. when i print data i get {'in_text': ''} serializers.py class StandardizerSerializer(serializers.Serializer): in_text = serializers.CharField(max_length=2000,required=False) views.py class standardiz_text(APIView): def post(self, request): #serializer = StandardizerSerializer(context={'request': request}) serializer = StandardizerSerializer(data=request.data) print(repr(serializer)) if serializer.is_valid(raise_exception=True): print(serializer.data) else: print("----------not valid") return Response({'standardizer_text': ' test data'}) url to call from postman http://127.0.0.1:8000/standardiz/text/?in_text=tesinput outpt is StandardizerSerializer(data={}): in_text = CharField(max_length=2000, required=False) {} -
Django 2.x - using ModelForm to create a list in a form with unlimited items
I am attempting to create a ModelForm that contains (but is not just) a field where unlimited items can be added. To clarify, the common ToDo list example is almost exactly what I want to do, where users can add an item in an input and it is displayed to the user as added to the ToDo list. In it, the user can add as many items to a list as they want before submitting the form that also contains other fields like a title and description. I have seen how to do this with custom forms, but I am trying to master ModelForms and keep all the forms on this learning project as ModelForms. My question is, is this possible with ModelForms? I have thought that perhaps an array can be created, where each added item can be appended to the array, and on the final form submission that array can be stored in the db, but it is above my skill level to actually implement that. Is this the right track, or is there a better way? Thanks for helping me learn! -
Python: Can I avoid to set var=False?
I often run in the case that I have to set a variable to False. My last case is that one here. Is there a way to avoid setting self.dynamic_pricing_active = False? I have other cases were I had to define up to four vars with False due to the same reason as here. @cached_property def dynamic_pricing(self): self.dynamic_pricing_active = False test = self.request.event.tickets.filter(dynamic_pricing__activated=True) for ticket in test: if ticket.is_available(): self.dynamic_pricing_active = True break def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dynamic_pricing_active'] = self.dynamic_pricing_active return context -
Exception when using variable as part of tag in Django template (Wagtail CMS)
Setting up a Django/Wagtail CMS site. Trying to make a template for images, which takes sizing as an variable, and including the template with: {% include "patterns/molecules/media/image.html" with media=page.featured_image caption=page.image_caption imgclass="extra-wide" sizing="fill-854x480" %} And then in the template, I am using the following code: {% with sizing as size %} {% if size %} {% image media size as img %} {% else %} {% image media fill-1280x720 as img %} {% endif %} {% endwith %} However, it ends up with an exception: InvalidFilterSpecError at /slug/ Unrecognised operation: size Request Method: GET Request URL: http://localhost:8000/slug/ Django Version: 2.1.7 Exception Type: InvalidFilterSpecError -
Convert DRF 'POST' request body to json
I have model Chek class Check(models.Model): printer_id = models.ForeignKey(Printer, on_delete=models.CASCADE) type = models.CharField( max_length=8, choices=(("kitchen", "Kitchen"),("client", "Client")) ) order = JSONField(blank=True, null=True) status = models.CharField( max_length=10, blank=True, null=True, choices=( ("new","New"), ("rendered", "Rendered"), ("printed", "Printed")) ) pdf_file = models.FileField(blank=True, null=True) I am using Django REST framework. Here is POST request example { "id": 123456, "price": 780, "items": [ { "name": "pizza", "quantity": 2, "unit_price": 250 }, { "name": "rolls", "quantity": 1, "unit_price": 280 } ], "address": "client address", "client": { "name": "client name", "phone": client phone }, "point_id": 1 } As you can see, there is order = JSONField field in Check model. How can I convert whole request to json so I can use it in my model? I tried import json json_body = json.dumps(request.body) But got "You cannot access body after reading from request's data stream" error. json_body = json.dumps(request.data) Gave me "Error binding parameter 2 - probably unsupported type." -
Python Geo location grab
I don't even know if that's the right terminology but here goes. I'm trying grab my location and a another location (i.e a local park) and when I get near that location something happens. Any help is appreciated. Thank you -
React and Django deployment
I developed an app and I want to deploy it on a server. For backend I use Django and for frontend React. The communication between React and Django is via rest api. I also have an Arduino which communicates with Django via rest. I use nginx on server. What is the best way how to deploy this app? Thanks a lot -
Slug not rendering detail page in Django 2.0
What is the best way to use slug in this case and make it work properly. I can see the URL on the browser display the items requested but i am unable to render the detailed page. I cant find where the issue is coming from. When i access 'page_detail' the url is 'http://127.0.0.1:8000/posts/2019/03/23/greetings/', which is correct based on my input but django throw an error to render the page. Error is: TypeError: post_detail() got an unexpected keyword argument 'slug' MODEL: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') published = PublishedManager() # Custom Model Manager def get_absolute_url(self): ''' Canonical URL for post detail.''' return reverse('snippets:post-detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title URL app_name = 'snippets' urlpatterns = [ path('posts/', views.post_list, name='post-list'), path('posts/<int:year>/<int:month>/<int:day>/<slug:slug>/', views.post_detail, name='post-detail'), ] VIEWS def post_list(request): posts = Post.published.all() context = {'posts': posts} return render(request, 'snippets/list.html', context) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'snippets/detail.html', {'post':post}) post_list HTML … -
Django Rename Column In Postgresql
I have messed up my migrations and need to rename a column in my database, is that possible? Im also using docker which means I can't use any graphical interface to change tables in my db. If changing the column name isn't possible, maybe I could drop the hole table as there is no data saved on that table yet. How can I do that ? -
How to setup multiple interpreters in CircleCI using Tox and Poetry?
I'm setting up a reusable package for Django. I'm using Poetry as the package manager and I'm using tox for testing across multiple python environments. However, I keep on receiving the following error on CircleCI: py27-django111: commands succeeded ERROR: py34-django111: InterpreterNotFound: python3.4 ERROR: py34-django20: InterpreterNotFound: python3.4 ERROR: py34-django21: InterpreterNotFound: python3.4 py35-django111: commands succeeded py35-django20: commands succeeded py35-django21: commands succeeded py36-django111: commands succeeded py36-django20: commands succeeded py36-django21: commands succeeded ERROR: py37-django111: InterpreterNotFound: python3.7 ERROR: py37-django20: InterpreterNotFound: python3.7 ERROR: py37-django21: InterpreterNotFound: python3.7 I couldn't find any reports on how to solve this issue and I've seen different Django package projects in CircleCI however they differ on their approaches to build the environments. My circle.yml file: version: 2 jobs: development: docker: - image: circleci/python:3.6.8 steps: - checkout - run: name: Install command: | poetry install - run: name: Lint command: | poetry run flake8 django_package - run: name: Test command: | poetry run tox - run: name: Codecov command: | poetry run codecov deployment: docker: - image: circleci/python:3.6.8 steps: - checkout - run: name: Publish command: | poetry publish --build --username "${PYPI_USERNAME}" --password "${PYPI_PASSWORD}" --no-interaction workflows: version: 2 development-workflow: jobs: - development deployment-workflow: jobs: - development: filters: tags: only: /v[0-9]+(\.[0-9]+)*/ branches: ignore: /.*/ … -
Json Records returns only one rows of records from database via django
I have three records in database but json response returns only just one records. I need to display database records via json by instantiating a variables so that instead of using database coulmn name firstname and lastname, I can use something like fname and lname respectively when outputing json records from database. To this effect, I have created the following code below views.py def read(request): response_data = {} for members in Member.objects.all(): #members = Member.objects.all() response_data['fname']=members.lastname response_data['lname']=members.firstname print("successful....") jsondata = json.dumps([response_data]) #jsondata = json.dumps(list([response_data])) return HttpResponse(jsondata, content_type='application/json') My Issue: My problem is that each time the code above is run, it displays only just one records from database via json. Eg. Here [ {"fname": "Thorr", "lname": "Odinson"} ] My Requirements: How do I make it to loop more and display all the three records from database via json Eg. [ {"fname": "Thorr", "lname": "Odinson"}, {"fname": "Ann", "lname": "bell"}, {"fname": "Jon", "lname": "Han"} ] -
ModuleNotFoundError: No module named 'allauth'
This is my installed app. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'corsheaders', 'articles', ] I am using django 2.1 and rest framework.I want to implemet rest auth registration so I have followed this step by step guidlines from offcial documentation https://django-rest-auth.readthedocs.io/en/latest/installation.html . When I hit enter the migrate command python manage.py migrate I am getting following error: File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' Kindly Help. -
how to implement dependent choice list and input text in django form with ajax
i have a form with txo fields a dropdown list and input text field and i want to implement the relation between them which means if i choose a value from the choice list i want to render the value of the input text ,i have to send the value of choice list to the server and based on it i have to return the value of the input text: this is my view: def rander_plage_value(request): indice_id = request.GET.get('ind_val') plage=Plage.objects.get(indice=indice_id, etat=True) return render(request, 'ireapp/includes/partial_rang_form.html', {'plage': plage}) this is my java script file: $("#id_indice").change(function () { var url = $("#rangForm").attr("data-plages-url"); // get the url of the load_cities view var ind_val = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/) data: { 'ind_val': ind_val // add the country id to the GET parameters }, //dataType: 'json', success: function (data) { // `data` is the return of the `load_cities` view function $("#id_plage").html(data); } }); }); -
Better way to make usernames NOT case sensitive in Django?
Django's default User model username validator allows testUser and TestUser for 2 different usernames. I found a way to make username case insensitive during the registration but I am wondering if there's not a built-in way to do that. Here is how I did it: if form.is_valid(): username = form.cleaned_data['username'] brk = True try: conflicting_username = User.objects.get(username__iexact=username) except: brk = False if brk: messages.warning(request, 'Username already in use') return redirect('signup') form.save() This method looks a bit unprofessional. Isn't there a built-in way like there always is in Django? Something like an argument in the username model field. -
how to be authorized to create an object using django rest framework and CreateAPIView?
I have a problem when I want to create an object using CreateAPIView, I get the message: "detail": "Authentication credentials were not provided.". I use rest-auth and rest-authtoken apps. this is what I made so far: #models.py class CustomUser(AbstractUser): objects = CustomUserManager() is_normal_user = models.BooleanField(default=False) is_corporate_user = models.BooleanField(default=False) class CompanyProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) corporate_name = models.CharField(max_length=30) #serializers.py class CompanyProfileSerializer(serializers.ModelSerializer): class Meta: model = CompanyProfile fields = ['user', 'corporate_name',] read_only_fields = ('id',) #views.py class Authorized_Company_User(permissions.BasePermission): def has_permission(self, request, view): return bool(request.user and request.user.is_corporate_user) class CompanyCreateProfileView(generics.CreateAPIView): #queryset = CompanyProfile.objects.all() serializer_class = CompanyProfileSerializer #authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, Authorized_Company_User) I am wondering if I need to define create function, and use get method to get user authtoken. -
JWT Login Django Rest Framework
I' m trying to create login view with djangorestframework-jwt.When i logged my user (url 'login/') it was fine and everything worked but and switched to another page (url 'post_list') to create a post I got an error that my user is anonymous so that is why I decided that that my user is again unauthenticated. Could you please help me to create proper JWT Login view that will allow me to create and switch between different pages without any obstacles? My settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], } My Serializers: class TokenSerializer(serializers.Serializer): username = serializers.CharField(max_length=128) password = serializers.CharField(write_only=True, required=True, style={ 'input_type': 'password', 'placeholder': 'password' }) class PostSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') class Meta: model = Post fields = '__all__' My views: class UserLogin(generics.CreateAPIView): """ POST login/ """ permission_classes = (permissions.AllowAny,) queryset = User.objects.all() serializer_class = TokenSerializer def post(self, request, *args, **kwargs): username = request.data.get("username", "") password = request.data.get("password", "") user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) return Response({ "token": jwt_encode_handler(jwt_payload_handler(user)), 'username': username, }, status=200) return Response(status=status.HTTP_401_UNAUTHORIZED) class PostView(generics.ListCreateAPIView): """ POST, GET post_list/ """ serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(created_by=self.request.user) permission_classes = (permissions.IsAuthenticatedOrReadOnly, ) URLS: urlpatterns = … -
I want to be able to add somthing to my models with postman in my django server but i couldn't [on hold]
so i have 2 models text and its author , I want to add them from postman directly when i press send it doesnt add anything here is a screen shot of the postman if you want anything else to make it clearer tell me cause i don't know where the problem is exactly ... i could add things from the django server itself though and this is the postman's body <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Page not found at /</title> <meta name="robots" content="NONE,NOARCHIVE"> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Page not found <span>(404)</span> </h1> <table class="meta"> <tr> <th>Request Method:</th> <td>PATCH</td> … -
Django Allauth executes request.POST on signup, but no redirect or email sent?
This started happening yesterday (it was working fine before), I've retraced my steps and reversed any edits and it's still not working. I'm using Allauth with Django and the generic signup form /accounts/signup/ isn't redirecting to verification_sent.html. An email_confirm.html is also not being sent to confirm the account. I've set up an email backend to test on localhost and normally the emails come through fine via the terminal window. Now when I submit the form and request.POST, nothing happens. No emails, no verification_sent.html page redirection. The terminal isn't throwing any errors and says HTTP POST /accounts/signup/ 200 How can I go about debugging this? signup.html <form method="POST"> {% csrf_token %} {{ form.email|as_crispy_field }} {{ form.first_name|as_crispy_field }} {{ form.last_name|as_crispy_field }} {{ form.password1|as_crispy_field }} {{ form.password2|as_crispy_field }} {{ form.captcha|as_crispy_field }} <button type="submit" value="submit" id='signup_button'>Sign Up</button> </form> forms.py class UserRegisterForm(forms.Form): captcha = ReCaptchaField() email = forms.EmailField() first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() settings.py ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.UserRegisterForm' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS=7 ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds -
How to measure the total amount of time my React Native app gets used
I am about to launch a beta version for my react native application, and I want to get information on how much time users stay on my app, and actually use it, how frequently they enter it etc. That would help giving me feedback. Also could be useful to know which pages get used the most. Is there such a thing that exists for that?