Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to preview a Wagtail page with translated fields in different languages?
I have a multi-language Wagtail website with two languages (English and German) using duplicated fields in my page models, e.g. a text block has two fields, text_de and text_en, and I define text as a translated field following the example in the translating content documentation. (I.e. I am NOT duplicating the whole page tree.) Here's an example how that looks in my code: [models.py] class MyPage(Page): ... text_de = models.CharField(max_length=1024) text_en = models.CharField(max_length=1024) text = TranslatedField('text_en', 'text_de') Everything works perfectly fine, in templates I can just use {{ text }} and depending on the active language (using i18n patterns and LocaleMiddleware) the correct version is displayed. BUT: I have issues with getting a page preview in both languages. When an editor creates a draft page in Wagtail admin and clicks on 'preview', then a page preview is shown in the language used within the Wagtail admin, i.e. in the language defined by the current editor's language preferences in his or her account settings. How could the editor also preview the page in another language (without switching the language in his or her account settings back and forth)? Is there maybe a way to construct a view that sets a different … -
How to use django api with foreignkey
I try to save foreign key in django restframework serializer. My goal is to save in database information from iframely.com and this part works good. But I need to also save it in specific category. After add field "Board(my category name field)" I have error: null value in column "board_id" violates not-null constraint My model: class Embed(models.Model): url = models.URLField(max_length=255) title = models.CharField(max_length=255) description = models.TextField() thumbnail_url = models.URLField(max_length=255) html = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) board = models.ForeignKey(Board, on_delete=models.CASCADE, verbose_name='Kategoria') Form: class SubmitEmbed(forms.Form): url = forms.URLField() board = forms.ModelChoiceField(queryset=Board.objects.all()) Serializer: class EmbedSerializer(serializers.ModelSerializer): author = serializers.HiddenField(default=serializers.CurrentUserDefault()) board = serializers.RelatedField(read_only=True) class Meta: model = Embed fields = '__all__' View: def save_embed(request): if request.method == "POST": form = SubmitEmbed(request.POST) if form.is_valid(): url = form.cleaned_data['url'] r = requests.get('http://iframe.ly/api/oembed?url=' + url + '&key=' + settings.IFRAMELY_KEY) json = r.json() serializer = EmbedSerializer(data=json, context={'request': request}) if serializer.is_valid(): embed = serializer.save() return render(request, 'embed/embeds.html', {'embed': embed}) else: form = SubmitEmbed() return render(request, 'embed/embedadd.html', {'form': form}) -
How to map custom radio inputs to NullBooleanField
I have custom radio inputs sending the value "1" if "yes" and "0" if "no" (unchecked equals "no" in our case): <input type="radio" name="track" value="1" {% if form.instance.track %}checked{% endif %}> yes <input type="radio" name="track" value="0" {% if not form.instance.track %}checked{% endif %}> no But now I am trying to set up my ModelForm so that these values "1" and "0" map to True and False in the instance attribute value. I have read RadioSelect maps 0 to False and 1 to True for a NullBooleanField but this does not appear to be the case. I don't actually know if I need to set something else up or where to do it. -
django inspectdb green plum(postgres) error
I have connected GPDB successfully by psycopg2: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB', 'USER':'gpadmin', 'PASSWORD':'xxxxx', 'HOST':'xxx.xxx.xxx.xxx', 'PORT':'2345', } } and no any errors showed when I used python manage.py inspectdb > report_app\models.py But the models.py showed: # Unable to inspect table 'dictionary' # The error was: syntax error at or near "WITH ORDINALITY" LINE 6: FROM unnest(c.conkey) WITH ORDINALITY co... ^ The enviroment is: python3.5 django2.1.7 gpdb5.11.3 How to solve this? Thamks. -
How to build website with input to terminal program on server? And how to make query
I wonder how I can build a website with input interface to program on server? Can you sketch it for me? I have program in linux terminal so input or textarea (input will be in text format) will forward data and if data != None start the program? And how can I monit is program working on site interface? and how to make a instance of job? i.e. Someone input text program start the terminal and if someone else input new job start new instance. And accordnig to this how to set limit eg 10 instances and query? Please can u advice me with this? I do not know how this process is named in programing. I am looking for some tutorial For example there is program weblogo (http://weblogo.threeplusone.com/create.cgi) You can download standalone version (conda install -c bioconda weblogo) Sample input Terminal cmd: weblogo -f sample.fa -D fasta -o sample_logo -F pdf -
Prevent repeating query within SerializerMethodField s
So i got my serializer called like this: result_serializer = TaskInfoSerializer(tasks, many=True) And the serializer: class TaskInfoSerializer(serializers.ModelSerializer): done_jobs_count = serializers.SerializerMethodField() total_jobs_count = serializers.SerializerMethodField() task_status = serializers.SerializerMethodField() class Meta: model = Task fields = ('task_id', 'task_name', 'done_jobs_count', 'total_jobs_count', 'task_status') def get_done_jobs_count(self, obj): qs = Job.objects.filter(task__task_id=obj.task_id, done_flag=1) # this query take around 3 seconds return qs.count() def get_total_jobs_count(self, obj): qs = Job.objects.filter(task__task_id=obj.task_id) # this query also take around 3-5 seconds return qs.count() def get_task_status(self, obj): done_count = self.get_done_jobs_count(obj) total_count = self.get_total_jobs_count(obj) if done_count >= total_count: return 'done' else: return 'not yet' When the get_task_status function is called, it call other 2 function and make those 2 costly query again. Is there any best way to prevent that? And I dont really know the order of those functions to be called, is it based on the order declare in Meta's fields? Or above that? -
Changing the PDF FONT'S (DJANGO)
I have a project in django, and i want to render some text to pdf. It's already working but now i need to change my font. I have Gotham font install on pc , and i use for all my documets , but right now i want to render my pdf with Gotham font's. I download the font and put inside of my templates folder: myproject/ |-- myproject |-- templates/ |-- admin/ |-- font/ |-- GothamBookItalic.ttf |-- GothamBookLight.ttf |-- GothamBookLIghtItalic.ttf |-- GothamBookMedium.ttf And this is my css of my html @font-face { font-family: GothamMedium; src: url('/font/GothamMedium.ttf') format('truetype'); } but is not working , and i have no idea what i need to do. -
Template for Flat Page is not running on the browser
I have created Flat Pages in Django admin but i am not getting the templates on the browser. I have created a folder inside templates with name flatpages and add default.html file as my Flat Page Template -
Possible to serve Django Channels app only using Nginx and Daphne?
I was under the assumption that I could run a Django Channels app using only Daphne (ASGI) and Nginx as a proxy for my Django app to begin with. The application would be running with Daphne on 127.0.0.1:8001 However, I am running into a 403 Forbidden error. 2019/03/06 17:45:40 [error] *1 directory index of "/home/user1/app/src/app/" is forbidden And when I posted about that, another user mentioned There is no directive to pass http request to django app in your nginx config And suggested to look into fastcgi_pass or uwsgi_pass or Gunicorn. Obviously Django Channels runs on ASGI and I am passing all requests through that right now (not to uWSGI then on to ASGI depending on the request.) Can I serve my Django app with only Nginx and Daphne? The Django Channels docs seem to think so as they don't mention needing Gunicorn or something similar. my nginx config server { listen 80; #listen [::]:80 ipv6only=on; server_name your.server.com; access_log /etc/nginx/access.log; root /var/www/html/someroot; location / { #autoindex on; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. # try_files $uri =404; #proxy_set_header X-Real-IP $remote_addr; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #proxy_set_header Host $http_host; #proxy_set_header … -
how to run a pyro4.daemon in Django+celery project?
I need to run a pyro4.daemon for django server, but I have no idea how to start it just once. When I started the celery worker in another shell, an error happened(OSError: [Errno 98] Address already in use) that means the daemon will be ran again. That's not what I want. So anyone have ideas? Thanks a lot. -
Django Authentication credentials were not provided
So I'm using Http file to make GET request using rest_framework Authentication here is the command I use: GET localhost:8000/api-admin/products Authorization: Token 5e2cf6ddc7a0ff8fe03e4749d788a423f6640443 When I use the browser and go to that link it works successfully but when I use HTTP file or Postman I get Authentication credentials were not provided. error -
django 2 user edit and change password forms on the same page
I have a user profile page where I want to have two forms: - user info edit form - password change form Currently I do have two separate pages with separate views. For password change I'm using django's contrib auth provided views and forms. I want to be able to put this two forms into a single page and be able to either change user data or password. Any idea how this is best achieved ? What is the elegant way of doing this ? -
Django rest framework: use sqlalchemy models instead of django models
I have an application with 500+ tables and their models are written in sqlalchemy. I want to use these models in django application instead of writing all models again in django. I have tried django-rest-witchcraft but it does not work. Please suggest me more reliable solution -
Upload a folder (of files) from django views to html
Im trying to upload a folder of pdf files to html so that user can download them. I'm able to do a single file upload , but not sure on how to do for a folder. :( -
Django: how to redirect test_func to 403 forbidden page instead of login
When a logged in user wants to update a post (UpdateView) he has not created, the test_func function should redirect the user to the 403 Forbidden page instead of the login page. However in my case, it redirects to the login page even if the user is already logged in. Does anybody has an idea of why it is happening ? Thank you! class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super(PostUpdateView,self).form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False -
How to make foreign key unsigned in Django
I want to know how to make foreign key unsigned in Django v1.11. I have two tables: tournament and vip_promotion. The id primary key in vip_promotion is int, unsigned. When I created a migration for tournament table, I couldn't make a foreign key to vip_promotion, because Django only makes foreign key column is only int without unsigned. Is there any way to make foreign key column is unsigned in Django? class Tournament(BrickModel): display_name = models.CharField(max_length=255) vip_promotion = models.ForeignKey(Vip_Promotion, null=True, blank=True) -
Django authenticate method returns none [duplicate]
This question already has an answer here: Why authenticate() return None for inactive users? 1 answer I am creating a user login method wherein the admin of a domain can authorize other new users. Basically what I am doing is changing the is_active field to true from the admin. However when a new user signs up, their active status is false and I am displaying an appropriate message but my code for some reason is not reaching there. I even tried printing the user but it shows None. Also, once the active status is changed to True, they can login like normal. Here is my view: def login_user(request): if request.method == 'POST': login_form = Login(request.POST) if login_form.is_valid(): email = login_form.cleaned_data['email'] password = login_form.cleaned_data.get('password') user = authenticate(email=email, password=password) print user if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('dashboard')) elif user.is_active == False: return HttpResponse("<h2>Waiting for admin to authenticate you</h2>") else: return render(request, 'registration/login.html', {'errors': login_form.errors}) return render(request, 'registration/login.html', {'form': Login()}) -
Django-channels:chatSocket.onmessage does not work
i am trying to implement a django channels chat app. when the submit button of the room view is clicked, the message does not appear in the chat log. which make me think that somethings wrong with chat.onmessage command, it does not seem to fire. can someone help me fix the issue. here is the code for room view: {% extends "chat/base.html" %} {% block title %}Chat Room{% endblock %} {% block body %} <div class="container"> <textarea id="chat-log" cols="100" rows="20"></textarea><br/> <input id="chat-message-input" type="text" size="100"/><br/> <input id="chat-message-submit" type="button" value="Send"/> </div> {% endblock %} <script> var roomName = {{ room_name_json }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; </script> -
Django - extend User with Profile model during creation of user for account types
I've discovered from researching that the best way for me to create account types for users is a one-to-one model, which I have named profile. What is unclear and I am not finding a clear answer for is how I can create this at the same time as creating the user. I am using the default user model in django. I have tried the following, but it doesn't work, and is hacky trying to use a get method inside a post. user = User.objects.create_user(first_name=first_name, last_name=last_name, password=password, username=email, email=email) user.save() user = User.objects.get(pk=user_id) user.profile.account_type = 'User' user.save() If it is relevant, I am using a radio select in an html form for account types -
Django template context won't render
Hi I am trying to make a form submission app that just displays the entered information back to the user underneath the form they submitted. Unfortunately, I can't seem to load the context on the front end within the template. Template: You'll see under the form there is a for loop that is supposed to iterate the context, but nothing displays. I tried it with just email for now, but it does not work. <!DOCTYPE html> <html> <head> <title>Form Practice</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8"> <form style="margin-top: 600px;" method="post" action="/form"> {% csrf_token %} <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label" >Email</label> <div class="col-sm-10"> <input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email"> </div> </div> <div class="form-group row"> <label for="inputPassword3" class="col-sm-2 col-form-label" >Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password"> </div> </div> <fieldset class="form-group"> <div class="row"> <legend class="col-form-label col-sm-2 pt-0">Radios</legend> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked> <label class="form-check-label" for="gridRadios1"> First radio </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> Second radio </label> </div> </div> </div> </fieldset> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="customCheck1" name="check"> <label class="custom-control-label" for="customCheck1">Check this custom checkbox</label> </div> <select class="custom-select … -
Plotly and Cufflinks in django
I am currently experimenting how to display graphs into my django templates. I have a little success by converting the plots into image then display it in a template. But this scheme is not suitable for interactive graphs like Plotly and Cufflinks. How can I embed Plotly and Cufflinks into my django template so that my graph will be interactive? -
Django-rest-framework-social-oauth2 error with google
I am using Django 1.11 with Django Rest Framework 3.6. I am trying to schedule a social network login from an Android application with the django-rest-framework-social-oauth2 plugin but I am having an error that is not solved. Configuration setting.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.open_id.OpenIdAuth', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.facebook.FacebookAppOAuth2', # 'social_core.backends.instagram.InstagramOAuth2', 'rest_framework_social_oauth2.backends.DjangoOAuth2', 'frontend.login.EmailOrUsernameModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = **** SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = *** REST_FRAMEWORK = { ... 'DEFAULT_AUTHENTICATION_CLASSES': ( ... 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ) } The data configuration according to the documents. Then from Postman I make the next call and it returns an error 400. enter the description of the image here The fact is that it returns the error: The backend responded with HTTP403: the daily limit for unauthenticated use was exceeded. Continuous use requires registration. -
DRF | May not set both `read_only` and `write_only`
In my project I want to set password as both read_only(because I have a separate endpoint to reset password) and write_only(because I don't want password send in the response). Here is my serializer: class UserSerializer(serializers.ModelSerializer): """A Serizlier class for User """ class Meta: model = models.User fields = ('id', 'email', 'phone_number', 'user_type', 'password') extra_kwargs = { 'password': { 'write_only': True} } read_only_fields = ('password',) But I get an error saying: AssertionError at /api/user/21/ May not set both read_only and write_only How can I have a field be both read_only and write_only? -
How to hide source code of django from user?
I know my question title is a little confusing , but i want to do this : I have a project that's include these things : 1- A landscape page with html,css,... 2- A Django Admin-Panel for a mysql database . I'm using a VPS (Virtual Private Server) , and this VPS have not required disk space , i want to use Django admin-panel in local and give it to my employer , but i dont want to give the source code to him , is there any way to hide the source code from my employer but still give him the django admin panel to use on his own computer ? -
Bootstrap 3 display 3 blog posts in each row using in Django templates
I'm working on a project using Django(2.1.7) and Bootstrap (3.1), I need to display 3 blog posts in each row: Note: I have taken a look at various related questions but couldn't find any solution specific to my problem, so don't mark this question as duplicated, please! here what I have tried: <div class="container-fluid"> <div class="row"> <div class="col"> <div class="col-lg-9"> <div class="row"> {% for post in posts %} <div class="col-lg-4 col-sm-6 mb-4" style="margin-top: 2%"> <div class="card shadow border-0 h-100"><a href="post.html"> <img src="{{ post.photo.url }}" alt="..." class="img-fluid card-img-top"></a> <div class="card-body"><a href="{% url 'blog-post' post.id %}" class="text-uppercase text-muted text-sm letter-spacing-2">{{ post.category }} </a> <h5 class="my-2"><a href="post.html" class="text-dark">{{ post.title }}</a></h5> <p class="text-gray-500 text-sm my-3"><i class="far fa-clock mr-2"></i>{{ post.created_at }}</p> <p class="my-2 text-muted text-sm">{{ post.content }}</p><a href="{% url 'blog-post' post.id %}" class="btn btn-link pl-0">Read more<i class="fa fa-long-arrow-alt-right ml-2"></i></a> </div> </div> </div> {% endfor %} </div> </div> <div class="col-lg-3" style="background-color: darkgrey; height: 100%"> <div class="container"> <form class="form" style="margin-top: 3%"> <input type="search" name="search" /> <button type="submit">Search</button> </form> </div> </div> </div> </div> </div> And here's the css for some of these elements: .card-img-top { width: 100%; border-top-left-radius: calc(.4rem - 1px); border-top-right-radius: calc(.4rem - 1px); } img { vertical-align: middle; border-style: none; } .img-fluid { max-width: 100%; height: …