Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create video streaming feature with django?
I want to create video streaming feature that, like twitch or something like that, who have any ideas? -
"double salting" a password with python
I am currently reworking a website that was written in php, in django and I need to copy over the old users. The problem is that the old website uses a "double salted" sha1 hashed password and I don't know how to replicate that with python. The code for the double salted password: sha1($salt . sha1($salt . sha1($password))); Addtionaly I really do not know much about php. Hopefully someone can help me with my issue. -
How to access Django database with JS
I have developed a website for an interactive game (mafia) using Django (python), but then i realized i need the displaying data(such as list of alive players, player messages, list of voted for lynch players, etc.) to be real-time and update instantly, whereas my website needs to be refreshed in order to see the updated database content. This is how it looks After realizing that, I started learning JavaScript, but now that I'm almost done, I noticed that Django and JavaScript functions cannot be called interactively, meaning I can't do JS functions and change database attributes at the same time. So I need an interactive frontend that updates data instantly, while being able to access and change database attributes as well(JS doesn't do this apparently). What should I learn for that? Thanks in advance. -
How to pass request.user / user to message in Django
So I want to let a user message another user. I want the 'sender' field automatically to be 'request.user' and the receiver field to be the user whom the sender clicked on through their profile page. How would I go about passing those into the form? forms.py/InstantMessageForm class InstantMessageForm(forms.ModelForm): class Meta: model = InstantMessage fields = ('receiver','sender','message') def save(self, commit=True): user = super(InstantMessageForm, self).save(commit=False) user.receiver = cleaned_data['receiver'] user.sender = cleaned_data['sender'] user.message = cleaned_data['message'] if commit: user.save() return user views.py/instant_message def instant_message(request): if request.method == 'POST': form = InstantMessageForm(request.POST) if form.is_valid(): form.save() return redirect('dating_app:home') else: form = InstantMessageForm() context = {'form':form} return render(request, 'dating_app/instant_message_form.html',context) models.py class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() class InstantMessage(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE ) message = models.TextField() instant_message_form.py {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} <h1>Start chatting now!</h1> <div class='container'> <form method="post" action="{% url 'dating_app:instant_message' %}" > {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> </div> {% endblock content %} -
Elasticbeanstalk Django issues with ondeck vs current version
Using Elasticbeanstalk to deploy a Django application. Within the .ebextensions directory I've got the following (this is just a subset): commands: 00_pip_upgrade: command: /opt/python/run/venv/bin/pip install --upgrade pip leader_only: true 01_pip_install: command: /opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt leader_only: true container_commands: 111_collectstatic: command: "source /opt/python/run/venv/bin/activate && python /opt/python/ondeck/app/manage.py collectstatic --noinput" leader_only: true The issue is that anything with ondeck isn't found. I am having trouble finding AWS documentation regarding the transitions between bundle, ondeck, and current directories. When I ssh into the instances I don't see any directory at all for /opt/python/ondeck. Can someone help to explain if /opt/python/ondeck should still be used or what my issues may be? -
rest_framework_simplejwt post to an APIView
I have this settings: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } And this view: class Config(APIView): def get(self, request, *args, **kwargs): if 'config' in request.GET.dict(): if os.path.isfile(settings.CONFIG): yaml = read_config(settings.CONFIG) return Response(yaml) else: return Response({ "success": False, "error": "config file not found!"}) else: return Response({"success": False}) def post(self, request, *args, **kwargs): if 'data' in request.data: print(request.data['data']) return Response({"success": False}) With axios I manage my api calls, for example: axios.post('api/config/?config', { data: obj, headers: { Authorization: 'Bearer ' + rootState.auth.jwtToken } }) The problem is now, that I can not post data. I get an Unauthorized (401) error and in the response message it says: {"detail":"Authentication credentials were not provided."} Can you please tell me, what I'm missing here and how can I fix this issue? -
ReactJs: Passing a prop and using it within a map()
I'm trying to take a user inputted code and compare it to code within my database. Right now I can bring the code and display it outside the map function but when I try to add it, it doesn't work. here is my database: [ { "dwelling_code": "ABC-XYZ", "dwelling_name": "Neves Abode", "has_superAdmin": true, "room": [] } This is the parent component: class Dwel2 extends Component { state = { house: [], selectedMovie: null, data: "ABC-XYZ" } componentDidMount() { fetch('Removed for question', { method: 'GET', headers: { } }).then(resp => resp.json()) .then(resp => this.setState({ house: resp })) .catch(error => console.log(error)) } houseClicked = h => { console.log(h) } render() { return <div> <EnterCode dataFromParent={this.state.data} house={this.state.house} houseClicked={this.house} /> </div> } } This is the child component: function EnterCode(props) { return ( <div> <div> *THIS BIT DISPLAYS THE CODE*{props.dataFromParent} </div> {props.house.map(house => { var test = house.dwelling_name var code = house.dwelling_code if (code === {props.dataFromParent}) { test = "Test" } return ( <React.Fragment> <div>{test}</div> </React.Fragment> ) })} </div> ) } I just want to compare the code in the database to the code defined in the parent component -
Why Django does admin change page displays html instead of link after upgrading from Django 1.11 to 2.2?
I recently upgraded to Django 2.2 and now the HTML of my link is display instead of an actual link. Here is the code I suspect has changed in behavior: class RequestAdmin(admin.ModelAdmin): ordering = ('id', 'status', ) list_display = ('detail_link', 'status', 'requester', 'added', 'type', 'change_description', 'approve_or_deny') ... omitted for brevity ... # ID in list is rendered as link to open request details page def detail_link(self, obj): return '<a href="%s%s%s%s%s" target="_blank">%s</a>' % (('https://' if self.request.is_secure() else 'http://'), self.request.META['HTTP_HOST'], (settings.GUI_ROOT if settings.GUI_ROOT != '/' else ''), '/#/requests/', obj.id, obj.id) Before this would render a link. But now if renders this text instead: <a href="http://app-dev-001.example.com:5200/gui/#/requests/1" target="_blank">1</a> -
Sharing a database on 2 Django projects
I made a webapp on django and it's working great. However, I got feedback that my userbase prefers an app over visiting a website. This is completely understandable and I started researching in how to develop one for both android and iphone phones. I came across flutter and got to work. My flutter frontend has to communicate with an api which communicates to the same database as my webapp. So I installed djangorestframework and got it to work. The problem here is that I want to use token authentication for my app and basic authentication for my website. Since you can't have both [:(] I started the api as an extra project. Project 1 has the web application, built on Django. Project 2 is the rest API for my mobile phone apps. Now comes the great question, how do I make them share one database? -
django-encrypted-filefield with cloud storage
I'm new to this and can't find any resources, except this which does not provide a final answer and the orignal demo which only does things locally. I have a django-encrypted-filefield in a model, and a method to get the url: class Item(models.Model): file = EncryptedFileField(upload_to="files/") def get_url(self): return self.file.url This then pushes to an S3 bucket, say https://bucket.org/assests/. As mentioned in the docs, urls contains the line: url(r"^fetch/(?P<path>.+)", MyFetchView.as_view(), name=FETCH_URL_NAME), and the required environment variables are present. In the docs, when attempting to get the local url, we could simply access: {{ object.get_url }} And from that url we could download a non-encrypted version. However, in the bucket case, accessing in that way will return something resembling fetch/https://bucket.org/assets/files/item.txt, which is not a valid url. I know I am probably missing something very simple, but I can't remove the fetch because that would catch all urls. I don't know how to write a view that solves this either. Please could someone advise me or link me to a tutorial that helps with this. Thanks, Joshua. -
NoReverseMatch at /post/31/
I am new to django and creating a blog of which while using class-based views, my post detail was displaying properly. I decided to use function-based views and I am coming up with this error. Please help. This is my views.py file # class PostDetailView(DetailView): # model = Post # template_name = 'ecommerce/post_detail.html' # def get_context_data(self, *arg, **kwargs): # context = super().get_context_data(**kwargs) # form = CommentForm() # context['form'] = form # Your comment form # return context def post_detail(request, pk): post = get_object_or_404(Post, pk = pk) is_liked = False if post.likes.filter(id=request.user.id).exists(): is_liked = True context ={ 'post':post, 'is_liked':is_liked, } return render(request, 'ecommerce/post_detail.html', context) My urls.py path('post/<int:pk>/', views.post_detail, name='post-detail'), My post_detail.html {% extends "ecommerce/base.html" %} {% load crispy_forms_tags %} {% block content %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small> {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content }}</p> </div> <form action="{% url 'like_post' %}" method="POST"> {% csrf_token … -
django add to model from model have foreign key to this model from admin
models.py from django.db import models # Create your models here. class Client(models.Model): name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(max_length=150, blank=True, null=True) class ClientNum(models.Model): number = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) class Ad(models.Model): num = models.CharField(max_length=20, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) i want to be able to add client from Ad model from django admin as i able to add number to client from client model i'm able to add user from Ad model in django admin but it opens new window i want to be in same window Acmin.py from django.contrib import admin # Register your models here. from .models import ClientNum, Client, Ad class ClinetNumAdmin(admin.TabularInline): model = ClientNum extra = 1 class ClinetNumRel(admin.ModelAdmin): inlines = [ClinetNumAdmin] class ClinetAdmin(admin.TabularInline): model = Client extra = 1 admin.site.register(ClientNum) admin.site.register(Client, ClinetNumRel) admin.site.register(Ad) -
how ajax work in Django getting id for new page this problem
$(document).on("click", "#transactRequest", function() { var request_no = $("#request_no").val(); $.ajax({ url: "{% url 'bond_fund:create-transaction/' request_no%}", method: "GET", success: function(data) {}, }); }); url path('create-transaction/', create_transaction), -
Serving two websites on one VPS
I am trying to serve two Django sites on one VPS (Digital Ocean) using Nginx and Gunicorn. I have an application called life-cal. When I type www.thelifecal.com into my browser address bar, I get exactly the response I am looking for and the Django app is served. However, when I just type thelifecal.com (no www.) I get the "Welcome to Nginx" page displayed. I used the following two tutorials to set up my server: https://gist.github.com/bradtraversy/cfa565b879ff1458dba08f423cb01d71#copy-this-code-paste-it-in-and-save https://medium.com/@caterinadmitrieva/serving-multiple-django-apps-on-second-level-domains-with-gunicorn-and-nginx-a4a14804174c /etc/nginx/sites-enabled/life-cal server { listen 80; server_name 167.71.116.21 thelifecal.com www.thelifecal.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/keegadmin/pyapps/life_cal; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/life-cal.sock; } } And a screenshot form namecheap: -
How to use for loop
I'am making movie website in django and I want to order my list of all movies from database .So I have found this second card with image on https://materializecss.com/cards.html but I really don't know how to use {% for %} {% endfor %} so I could have descriptions ,name of movie and image(poster) of movies in database.Can someone here could help me ? -
Django Rest Filterset - how to filter by nested serializer?
Good evening colleagues! I have the following code: serializators.py class CoinCostsSerializer(serializers.ModelSerializer): class Meta: fields = ('price', 'timestamp',) model = CoinCosts class CoinSerializer(serializers.ModelSerializer): class Meta: fields = ('symbol', 'crr', 'costs') model = Coins costs = CoinCostsSerializer(source='coincosts_set.all', many=True) views.py class CoinCostFilterSet(filters.FilterSet): class Meta: model = Coins fields = { 'symbol': ['exact'], } class CoinCostViewSet(viewsets.ModelViewSet): queryset = Coins.objects.all() serializer_class = CoinSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = CoinCostFilterSet And by typing the address /CoinCost/?symbol=ZERO for example, I have filtering from Django on this coin. So i need this url: /CoinCost/?symbol=ZERO&timestamp_start=2019-12-14T00:00:00&timestamp_end=2019-12-17T00:00:00 get filtering not only by Zero coin but also by Timestamp. Can you help? What should my code look like for this task? How do I filter by the embedded serializer as well? Thanks for the help! Have a good weekend! -
Django Ajax request gets stuck after pressing "submit"
I am using AJAX to create a blog post object from the website, however, after pressing submit chrome freezes and the modal doesn't hide. I can see in the terminal the view is being called but my chrome freezes and I have to close the tab and then enter the website again. I have also tried using Safari but it happens there as well, I havent changed anything in my code I do not know why this is appening. My view for creating a post: @login_required def post_create(request): data = dict() if request.method == 'POST': image_form = ImageForm(request.POST or None, request.FILES or None) form = PostForm(request.POST) if form.is_valid() and image_form.is_valid(): post = form.save(False) post.author = request.user post.save() images = request.FILES.getlist('image') for i in images: image_instance = Images(file=i,post=post) image_instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: image_form = ImageForm form = PostForm context = { 'form':form, 'image_form':image_form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my javascript for handling Ajax: $(document).ready(function(){ $(document).ajaxSend(function (event, jqxhr, settings) { jqxhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }); var ShowForm = function(e){ e.stopImmediatePropagation(); var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post … -
Axios Authorization not working - VueJS + Django
I am trying to build an application using VueJS and Django. I am also using Graphene-Django library, as the project utilize GraphQL. Now, The authentication works fine and i get a JWT Token back. But when i use the token for other queries that need authentication, i got this error in Vue: "Error decoding signature" and the Django Log also returns this: graphql.error.located_error.GraphQLLocatedError: Error decoding signature jwt.exceptions.DecodeError: Not enough segments ValueError: not enough values to unpack (expected 2, got 1) the bizarre thing is that the same query when executed in Postman just works fine. As i mentioned in the title is use Axios for my requests, here's an example of a request: axios({ method: "POST", headers: { Authorization: "JWT " + localStorage.getItem("token") }, data: { query: `{ dailyAppoint (today: "${today}") { id dateTime } }` } }); Note: It uses 'JWT' not 'Bearer' because somehow 'Bearer' didn't work for me. -
AJAX post-ing of python dictionary leads to JSONDecodeError
I am passing a python dictionary to a template then $.post-ing it to a view in django, and when I try to json.loads it in my post view, I get JSONDecodeError. Anyone know how I can fix this? //1. vars to templates @login_required def bracket(request): ''' :param request: :return: ''' ... context = {'arr':json.dumps(tournament_games_json_serializable), 'nested':nested_tournament_games['rounds']}#{'latest_question_list': latest_question_list} return render(request, 'madness/bracket.html', context) //2. AJAX post of template var $.post('{% url "update_bracket" %}', { bracketData: "{{arr}}" }, function(data, status, xhr) { console.log(JSON.stringify(data)); var nested = JSON.stringify(data); }).done(function() { }) .fail(function(jqxhr, settings, ex) { alert('failed, ' + ex); }); //3. update_bracket @csrf_exempt def update_bracket(request): bracketData = request.POST['bracketData'] print(json.loads(bracketData)) ... where tournament_games_json_serializable is tournament_games_json_serializable {'round_1_game_1': {'players': (2, 3), 'winner': None, 'loser': None, 'done': False}, 'round_2_game_1': {'players': (1, 'winner of Round 1 Game 1'), 'winner': None, 'loser': None, 'done': False}} request.POST['bracketData'] '{&quot;round_1_game_1&quot;: {&quot;players&quot;: [2, 3]... json.loads(bracketData) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 -
Initiate new instance from UpdateView
I am making an app to create repair work orders which also has an inventory app in it. I create and edit repair work orders using class-based views. I have a model for work orders; class Order(models.Model): """Maintenance work orders""" ... parts = models.ManyToManyField(UsedPart, blank=True) model for parts inventory class Part(models.Model): """List of company equipment""" partnum = models.CharField(max_length=20) amount_in_stock = models.PositiveIntegerField() price = models.FloatField(blank=True, null=True) vendr = models.ManyToManyField('Vendor', blank=True) ... And a model for instances of used parts class UsedPart(models.Model): """List of company equipment""" part = models.ForeignKey(Part, on_delete=models.CASCADE) amount_used = models.PositiveIntegerField() The way i wanted to implement it was. I create a UpdateView for an order. Check the parts i need in a m2m form and on submit create instances of this parts with associated amount. But i can't figure out how to initiate the instances from request. i wrote this, but id doesn't work class AddPartView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order form_class = AddPartForm template_name_suffix = '_add_part' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update(request=self.request) return kwargs def post(self, request, **kwargs): UsedPart.__init__(self) request.POST = request.POST.copy() request.POST['parts'] = request.POST.get('parts') return super(SomeUpdateView, self).post(request, **kwargs) form class AddPartForm(forms.ModelForm): class Meta: model = Order fields = ['parts', ] labels = {'parts': "", } def filter_list(self, … -
how to show list view in my urls based on string not integer in django
this is my model where I have people class where every person in this people class lives in a zone this is my people class and zone class class Zones(models.Model): zone_name = models.CharField(max_length=120) def __str__(self): return self.zone_name class People(models.Model): first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) address = models.TextField() phone_number = models.CharField(max_length=12) national_number = models.CharField(max_length=14) no_of_members = models.PositiveIntegerField(null=False, blank=False) zone = models.ForeignKey(Zones, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return self.first_name and how I want to show them the in the route /zone will be list of my zones, and when the user click on any of those zone I want him to see list of people who are in this zone here is my views class PeopleView(ListView): model = People template_name = "people.html" context_object_name = 'people_list' class ZoneView(ListView): model = Zones template_name = "zones.html" context_object_name = 'zones_list' class PeopleDetailView(DetailView): model = People template_name = "people_detail.html" and here is my urls urlpatterns = [ path('admin/', admin.site.urls), path('people/', PeopleView.as_view(), name='people'), path('zone/', ZoneView.as_view(), name='zone'), path('zone/<int:pk>/', PeopleDetailView.as_view(), name='detail'), ] and here is my html template for zone <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Zones List</title> </head> <body> <h1>Zones List</h1> <ul> {% for zone in zones_list %} <a href="#"><li>{{ zone }}</li></a> {% endfor %} </ul> </body> </html> -
Implementing MVC pattern with Django Rest Framework
I was wondering how could I implement a MVC pattern on a Django Api project, when I start a django project it gives me the apps.py, admin.py, models.py and the views.py , I understand the the models, should be the "M", and the views the "V", but as i'm using the project like an api, the view would be an Angular or React App, so where I put the logical ? Where is the right place to put the "C" controller on a django rest framework project, is it on views.py ? -
Select one field from a filter in Django
I have a quick question: How can I select only one field from my filter form in Django? I'm currently displaying the whole thing: <div class="container"> <form method="GET" > {{ filter.form.Precio|crispy }} <button class="btn btn-primary" type="submit">Aplicar filtros</button> </form> </div> I'd like to separe the filter form. I used to do this: {{ form.username }} but it doesn't seem to work... EDIT: This is filters.py class PubFilters(django_filters.FilterSet): Precio = django_filters.NumericRangeFilter() o = django_filters.OrderingFilter( choices=( ('-Más nuevo', 'Más nuevo'), ('Más nuevo', 'Menos nuevo') ), fields={ 'Fecha': 'Más nuevo', } ) class Meta: model = publicaciones fields = ['Título', 'Precio', 'Categoría'] fields ={ 'Título': ['icontains'], } -
How to respond with child object based on its parent id?
I have a parent class and a child class, like so: class Animal(models.Model): age = models.IntegerField() class Bird(Animal) wingSpan = models.DecimalField() Here's the view to get birds: class BirdViewSet(viewsets.ModelViewSet): queryset = Bird.objects.all() serializer_class = BirdSerializer And here is the serializer: class BirdSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Bird fields = ['age', 'wingSpan'] In the database, jango appropriately created an animal_prt_id field in the birds table, so that this view/serializer pair knows where to find the age, which is mapped to the parent class, Animal. How to make a view/serializer pair that does the opposite, meaning, it receives the id of an Animal and responds with the complete Bird (or with any other Animal subclass I might have)? -
DRF Update cross-table data
In my project I have Job, Skill and JobSkills models: class Job(models.Model): name = models.CharField( max_length=127, verbose_name=_('Job name'), ) description = models.TextField( verbose_name=_('Job description'), ) class Skill(models.Model): name = models.CharField( max_length=63, verbose_name=_('Skill name'), ) class JobSkills(models.Model): class Meta: verbose_name = 'Job skill' verbose_name_plural = 'Job Skills' unique_together = ['job', 'skill'], job = models.ForeignKey( Job, on_delete=models.CASCADE, related_name='job_skills', null=True, ) skill = models.ForeignKey( Skill, on_delete=models.CASCADE, related_name='job_skills', null=True, ) # generate list of lists of number from 1 to 10 like ((0, 0), (1, 1), ... (10,10)) SKILL_LEVEL = [(i, i) for i in range(1, 11)] level = models.IntegerField( choices=SKILL_LEVEL ) One job has many skills with skill level. User can add skills to job from default list and can not create new skill example data: PUT /api/jobs/1 { "name": "Job", "description": "Job description", "job_skills": [ { "id": 1, # job_skill_id "skill": { "id": 4, # skill_id }, "level": 7 } ], } class JobViewSerializer(serializers.ModelSerializer): job_skills = JobSkillsSerializer(many=True) def update(self, instance, validated_data) -> Job: job_skills = validated_data.get('job_skills') instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.save() But how to write the right logic for update Job skills? I need add new relation between Job and Skill if it doesn't exist, change Job skill …