Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get id from template in views using Django rest framework
I am totally new to Django rest framework. This is my models.py class Comments(models.Model): Blog_key = models.ForeignKey(Blog, on_delete = models.CASCADE) user_key = models.ForeignKey(User, on_delete = models.CASCADE) comment_content = models.TextField(blank = True, null=True) time_Commented = models.TimeField(auto_now_add = True) I have blog and I am trying to add comments to it using ajax My serializers.py looks something like this from django.contrib.auth import get_user_model from rest_framework import serializers from .models import Comments, Blog User = get_user_model() class UserDisplaySerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', ] class BlogDisplaySerializer(serializers.ModelSerializer): class Meta: model = Blog fields = [ 'title', ] class CommentsModelSerializer(serializers.ModelSerializer): user_key = UserDisplaySerializer(read_only=True) Blog_key = BlogDisplaySerializer(read_only=True) class Meta: model = Comments fields = [ 'user_key', 'Blog_key', 'comment_content', ] As We can see I am having Blog id in model having foreign key with Blog model. So in order to save comment, I need comment_content user id and blog id. My views.py looks like this class CommentsCreateAPIView(generics.CreateAPIView): serializer_class = CommentsModelSerializer def perform_create(self, serializer): serializer.save(user_key=self.request.user) #Here I can get user Id My question is how to get Blog id, I can get user id and can remove error But I am not able to remove error "null value in column "Blog_id" violates not-null … -
Passing an array form Django to Javascript
I am passing a django array to javascript to be processed. However i am seeing []; instead of ['ONXZOOlmFbM', 'GF-Lhuouucg']. How do I change the value so that I can retrieve the index of the i_number value as noted below? Any ideas? Note: console returns (Uncaught SyntaxError: Unexpected token '<'). Django template header if (b!=0) { var song = [{{l|safe}}]; var i_number = song.indexOf("{{b|safe}}"); }else(){ i_number=0 } Chrome developer tools.sources if (b!=0) { var song = [<QuerySet ['ONXZOOlmFbM', 'GF-Lhuouucg']>]; var i_number = song.indexOf("ONXZOOlmFbM"); }else(){ i_number=0 } views.py def PlaylistSelect(request, P_id): p=Playlist.objects.get(id=P_id) song_list=p.song.all() a=p.song.values_list('link', flat=True) l = json.dumps(list(a), cls=DjangoJSONEncoder) if request.user.is_authenticated: playlist = Playlist.objects.filter(author=request.user) else: playlist = None playlist_songs = None context={ 'playlist':playlist, 'song_list':song_list, 'l':l, } return render(request, 'playlist_mode.html', context) -
DRF user creation with one-to-one relation
I have made a model and serializers for User and additional ones for their profile (additional info). Model class Profile(models.Model): users = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True, ) nickname = models.CharField(max_length=10, unique=True) bio = models.CharField(max_length=300) def __str__(self): return self.nickname Serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username'] class ProfileSerializer(serializers.HyperlinkedModelSerializer): users = UserSerializer() class Meta: model = Profile fields = ['users', 'nickname'] It works fine for displaying it all out, but now i want to make it so i could create a new User with POST request AND also automatically assign a new empty or default Profile instance for that same User. DRF doesn't allow me to do that directly from Profile model API. Should i create a views.py function which will create a user and also create Profile for it separately or there's a built-in methods for that, so User then can update their Profile? -
Simple JWT add extra field to payload data in token
I use djoser and rest_framework_simplejwt. This my user model; class userProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name="profile") date_joined=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) def __str__(self): return self.user.username My views.py to get token for users give in below; class TokenObtainPairPatchedView(TokenObtainPairView): """ Takes a set of user credentials and returns an access and refresh JSON web token pair to prove the authentication of those credentials. """ serializer_class = TokenObtainPairPatchedSerializer token_obtain_pair = TokenObtainPairView.as_view() This is the serializer.py; class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer): def to_representation(self, instance): r = super(TokenObtainPairPatchedSerializer, self).to_representation(instance) r.update({'user': self.user.username}) r.update({'first_name': self.user.first_name}) r.update({'last_name': self.user.last_name}) return r I can get access and refresh token like this. { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTU4ODMzMTIzNywianRpIjoiZDNhODhiZjdlMTFmNDI1OGE2NWFlODZjYjA1YjQzZjMiLCJ1c2VyX2lkIjo1fQ.ojVC2d9edUknY-NG40ZPI4rqMtfLeYrxZtjzAr8SIk0", "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTg4MzMwMzM3LCJqdGkiOiJkYjEwM2ViYzZhODI0MGI1YmVlM2MyZDY2NTQxYjBlNSIsInVzZXJfaWQiOjV9.eh5VqE0Jj0VbM9NJ2BW3Ikr9GIXB0cNUJBSmE6IvUvk" } When encode token using jwt.io payload data is; { "token_type": "access", "exp": 1588329561, "jti": "944f97343b42448fbaf5461295eb0548", "user_id": 5 } I want to add users first_name, last_name in payload and ı want to get; { "token_type": "access", "exp": 1588329561, "jti": "944f97343b42448fbaf5461295eb0548", "user_id": 5, "first_name":"xxxx", "last_name":"xxxx", } -
how to synch offline first android app with web?
I want to sync my android app which is offline first, all changes made in the app then it can be synched. I have seen pervasync and AMPLI-SYNC. and also android sync adapter. but stuck in choosing the best practices. I also have a Django backend with the Postgres database. anyone knows how to synch room DB from android to web with Django backed. fastest and scalable way(if I want to implement maybe takes lots of time) PS: App is like Evernote and reminder app which can be must be synched and usable in offline and online -
Combining models within a single page in the admin page
I have a User class, and each user has a PersonalInformation model and a Profile model. In my admin panel I have: AUTHENTICATION AND AUTHORIZATION Users Groups USERS Profiles Personal Informations Users have a ONE-ONE relationship with 'PersonalInformation' and 'Profile', but the two models do not have a relationship. So I can view the Users, the PersonalInformation and Profile models separately, but I want to join them so I can view all one users information on one page. Thank you. -
I'm trying to save data from views into the data base and I'm getting this error(TypeError: User() got an unexpected keyword argument 'password1'
This is my view code: `from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] user = User.objects.create_user(username=username, password1=password1, email=email,first_name=first_name,last_name=last_name) user.save(); print('User Created') return redirect('/') else: return render(request, 'register.html')` -
Django Can't save record with ForeinKey
Hi familiar with the django and I am using django framework(2.2.2) in one of my website, But I am getting one weird issue for saving record with the foreign key: I have following two models class quick_note(models.Model): note_id = models.AutoField(primary_key=True) meeting_date = models.DateField(max_length=55) title = models.TextField(blank = True,null=True) headline = models.TextField(blank = True,null=True) class quick_note_details(models.Model): meeting_id = models.ForeignKey(quick_note,on_delete = models.CASCADE) summary = models.TextField(default='',null=True) Following is the code I have used for saving: quick_note_details_data = quick_note_details(summary = summary_data,meeting_id = 1) quick_note_details_data.save() Using this I am getting following error: ValueError: Cannot assign "2": "quick_note_details.meeting_id" must be a "quick_note" instance. Then, I have tried the following approach suggested in the following question, Django: ValueError when saving an instance to a ForeignKey Field quick_note_obj = quick_note.objects.get(note_id = note_id) quick_note_details_data = quick_note_details(summary = summary_data,meeting_id = quick_note_obj) quick_note_details_data.save() Using this I am getting following error: django.db.utils.ProgrammingError: column "meeting_id_id" of relation "website_quick_note_details" does not exist LINE 1: INSERT INTO "website_quick_note_details" ("meeting_id_id", "... I don't have a column like meeting_id_id, then why I am getting this error? I have been searching for this long time, but didn't get any solution, Hope I will get help here. -
How to annotate attribute base on some attributes that is in multiple rows in the table - django ORM
I have a model class Model(BaseModel): status = models.CharField(verbose_name='Status', max_length=255,null=True, blank=True) category = models.CharField(verbose_name='Service Category', max_length=255,null=True, blank=True) order_no = models.CharField(verbose_name='Order No', max_length=255, null=True, blank=True) item = models.CharField(verbose_name='Item', max_length=255,null=True, blank=True) operation_date = TimestampField(auto_now_add=False,null=True, blank=True) user_name = models.CharField(verbose_name='User Name', max_length=255,null=True, blank=True) service_status = models.CharField(verbose_name='Service Status', max_length=255,null=True, blank=True) status_message = models.TextField(verbose_name='Status Message', max_length=255,null=True, blank=True) I this above table, I want to calculate category, total order, order type. But the problem is order_type ins not in the above table ... we will have to calculate manually. Let if one Order No is 202025 and it's in two categories like cat1, cat2, we say the order_type is composite else it will be single ex: Order No category | 280436 | cat1 | | 280436 | cat2 | | 280435 | cat1 | | 280435 | cat3 | | 280435 | cat4 | | 280434 | cat1 | then we say Order no 280436 and 280435 are composite orders. SO the output should look like : Category order type total order total success orders cat1 single 10 8 cat2 composite 8 5 How can we model the Django query for the required output? Approche1 queryset = Model.objects.values('category', 'order_type').annotate( total_orders=Count('order_type'), total_success_order=Count('service_status', filter=Q(service_status='success'))).order_by() But How To Get Order … -
Chat application between user and customers [closed]
want to create a simple chat application between users and customers with the help of Django Channels.. this is my model. class ExternalMessageModel(models.Model): """ This class represents a chat message. It has a owner (user), timestamp and the message body. """ customers = models.ForeignKey('customers.Contact', on_delete=models.CASCADE, verbose_name='customer', related_name='from_customer', db_index=True) users = models.ForeignKey('users.UserProfile', on_delete=models.CASCADE, verbose_name='users', related_name='to_user', db_index=True) timestamp = models.DateTimeField('timestamp', auto_now_add=True, editable=False, db_index=True) body = models.TextField('body') I know how to create a chat application between users and users. -
How can I save the URL of the tiles seen by the user in leaflet with Django?
I have this HTML leaflet code in Django: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" /> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"/> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" ></script></head> <body> <div id="mapid" style="width: 600px; height: 400px;"></div> <script> var mymap = L.map('mapid').setView([51.505, -0.09], 13); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' ).addTo(mymap); </script> </body></html> This code: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') load all tiles in leaflet, how can I find which tiles have been seen by the user ? Leaflet have such function to when L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png') load tiles and same time send L.tileLayer('127.0.0.1:8000/{z}/{x}/{y}.png') to Django ? -
Django Rest Framework returns 200 OK with POST request (and object is not created))
I am learning DRF following the tutorial on the official website and everything works fine. The only thing I have changed is the model: instead of Snippet, I have Assessment, with only one attribute to be shown, and namely 'name' (a CharField). class Assessment(models.Model): name = models.CharField(max_length=150) # author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADEass) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] def __str__(self): return self.name def get_absolute_url(self): return reverse("assessment_detail", kwargs={"pk": self.pk}) When I visit http://127.0.0.1:8000/assessments/ the GET request method works fine, but when I try to post a new assessment (either trying to do it from the webpage by clicking on the post button or running http --json POST http://127.0.0.1:8000/assessment/ name='Test Quiz') the POST request doesn't enter the loop that handles it in views.py @api_view(http_method_names=['GET', 'POST']) def assessment_list(request, format=None): """ List all code assessments, or create a new assessment. """ if request.method == 'GET': assessments = Assessment.objects.all() serializer = AssessmentSerializer(assessments, many=True) print('THIS IS A GET REQUEST...') return Response(serializer.data) elif request.method == 'POST': serializer = AssessmentSerializer(data=request.data) print('SERIALIZER...') if serializer.is_valid(): serializer.save() print('serializer saved...') return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And the output inside the terminal is [01/May/2020 10:59:27] "POST /assessments/ HTTP/1.1" 200 11665 even though I am quite sure it should be 201 … -
Problem with model relationship and forms
Im building a warhammer project where a user: 1.Create a list 2.Select the soldier he want to add to the list and the weapons attached to the soldier Im struggling to understand how to list the weapons and the amounts he can choose. I try to "copy" this site: https://imgur.com/LitpaLa It's in French but I hope you get the idea My page: https://imgur.com/o20ZesU My models: class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) class Weapon(models.Model): name = models.CharField(max_length=30) points = models.IntegerField() type_of_weapon = models.CharField(max_length=30,choices=TYPE_OF_WEAPON) class Soldier(models.Model): title = models.CharField(max_length=30) weapons = models.ManyToManyField(Weapon) class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) amount_of_units = models.IntegerField(default=1) And the form I use to add a unit to a list: class SoldierToListForm(forms.ModelForm): def init(self, *args, **kwargs): self.faction_id = kwargs.pop('faction_id') super(SoldierToListForm, self).init(*args, **kwargs) self.fields['soldier'].queryset = Soldier.objects.filter(factions=self.faction_id) class Meta: model = SoldierToList fields = ('soldier','amount_of_units', ) Thanks for your help guys -
Django - Bcrypt: Authentication not working, TypeError
I am trying to use the Django User-Management with bcrypt. I want to simply take a plaintext password and check it against the stored hash. Bcrypt is installed, and my settings.py hashers look like this: PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', ) The user was created like this: my_user = User.objects.create_user('user', 'email@email.com', 'password') However, every time I try to compare the two: user = authenticate(username="user", password="password") I get the following error: TypeError at /login/ startswith first arg must be bytes or a tuple of bytes, not str Does anyone know how to fix this? -
Django Admin hide a field only in ADD form
In my django project i have this model: class v_pers(models.Model): a_id = models.ForeignKey(v_aree, on_delete=models.CASCADE) t_id = models.ForeignKey(v_tipopers, on_delete=models.CASCADE) p_name = models.CharField(max_length=100) p_sname = models.CharField(max_length=100) p_title = models.CharField(max_length=50) p_image = models.ImageField(upload_to ='pers') p_desc = models.TextField() def image_tag(self): return mark_safe('<img src="/%s" width="150" height="150" />' % (self.p_image)) image_tag.short_description = 'Image' class Meta: verbose_name = "Personale" verbose_name_plural = "Personale" def __str__(self): return self.p_name in my admin.py: class vpersAdmin(admin.ModelAdmin): readonly_fields = ["image_tag"] admin.site.register(v_pers, vpersAdmin) well, in my django admin i would hide my field image_tag only in ADD form and not in change, but if i cannot find how hide just in add form instead both So many thanks ina dvance -
Running Tests of Python and Django Module
I am wondering if there is a standard way to run tests for a Python package that is available on PyPi and Github. Suppose we have this package: https://github.com/Nekmo/djangocms-comments If one wants to run its tests, how would he do it? That is, I get that it should be python setup.py test or something like that. Prior to that, one needs to create a virtual environment with Django in it. After these steps, the command still errors with settings not being setup properly. Hence my question: am I doing something wrong or was this package simply not setup very well for running tests? More generally, what's the most optimal way to contribute code to such module? Should I set it up in a project and install into a virtual environment via pip install -e ./djangocms_comments? Or is there another way as well? Is it possible to run the tests of a package installed in a virtual environment? -
html and javascript audio player with django backend
I'm creating a music streaming website for my final year project.Most of my work is done except actually making the audio play and stream with django.I was wondering if i can make an audio player with html5 and js and get django to render it.Can any one point me to the right direction. -
Serving Django MVC and Django Rest Framework from same Model
This may be an opinionated question but sorry I am too curious. I learned to develop Django Model-View-Template websites ( multi page websites) and Django Rest Framework. From the same Django Model can I create Rest API's and MVC templates together ? I wanted to develop a Blog website that use session authentication and based on MVC architecture. The same server should create API's because the Mobile app for the Blog may consume the API's and use Token Authentication (using Djoser). If I use same User model for session and token authentication, Can mobile blog app users use their username and password to access website version ? -
how to reference a http://localhost location within a Django html page
I am trying to get hls.js to show a CCTV video on a webpage. I have ffmpeg runing on the same machine. In python, this requireshls1.loadSource("http//:xxx.xxx.xx.x/path_to/stream.m3u8"); If, in place of xxx.xxx.xx.x, I use localhost, 127.0.0.1, host_name or the IP_address_of_host I get error GET /path_to_django_app_folder/http://path_to/stream.m3u8 HTTP/1.1" 404 3239 If I drop http address i.e. hls1.loadSource("/path_to/stream.m3u8"); then I get GET /path_to/stream.m3u8 HTTP/1.1" 404 3103 I am sure it is simple but I can't see how to point hls to the relvant folder with an http: string. The file is located in /home/user_name/project_name/path_to/stream.m3u8 Thank you -
How to create a new model object and display the form information in DetailView?
I have a group of patients and location templates. Each patient has a DetailView where the user can link a location to a patient with extra information. How I handle this is I created a form with a dropdown menu and some extra fields different for each patient. When the user chooses a location template from the dropdown menu and fills in the rest of the form(specific to the patient), I want to create another location object with more details, link it to the patient and display this location information on the DetailView page. I believe all these are supposed to happen in PatientDetailView but I am not very experienced with Django, so I hope there is an easy solution. models.py class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) grid_y = models.IntegerField(null=True, blank=True) date_from = models.DateField(null=True, blank=True) date_to = models.DateField(null=True, blank=True) details = models.CharField(max_length=300, null=True, blank=True) category = models.CharField(max_length=300, null=True, blank=True) def __str__(self): … -
How to set nginx to serve React and Django properly
I use Linux server to serve React app as frontend and Django as a backend. The gunicorn config is as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=name Group=www-data WorkingDirectory=/var/www/backend/app ExecStart=/var/www/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/name/backend.sock app.wsgi:application [Install] WantedBy=multi-user.target And nginx config is as follows: server { listen 80; root /var/www/frontend/build; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location / { } location /graphql { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_cache_bypass $http_upgrade; proxy_redirect off; proxy_pass http://unix:/home/name/backend.sock; } } The Django app urls.py is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('reports/', include('reports.urls')), path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))) ] If I do a fetch request to www.example.com/graphql it works fine. But if I want to access Django admin dashboard as follows www.example.com/admin/ it doesn't work. If I understand it good, location /graphql {} means that Django apps runs on that url. Thus, If I want to access to some of the urls in urls.py file, i use www.example.com/graphql/url from urls.py Should it not be then www.example.com/graphql/graphql How to access admin dashboard? What I do not understand good? -
Add my own constraints to django crispy forms
I'm learning to program so I apologize for the broad (and likely silly) question. I am making a website in Django and using crispy forms. I want to add my own constraints and error messages to the form, which I know i can do when I clean the data or with validation. However, when I do this the error msgs appear differently to the crispy forms standard validation msgs (such as for a required field or that a username already exists. Please see this image for an example, the top error msg is a standard crispy one (which I would like all my msgs to be like, for consistency and to hopefully to further my understanding), whereas the one beneath is one I generated in my clean method. https://imgur.com/It0oCGG I just cannot find any information what-so-ever on how to do this. I found the link below, which mentions validation, but it doesn't seem to help me (or perhaps it's just beyond me) https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html#ajax-validation-recipe https://imgur.com/It0oCGG Any help or a push in the right direction (a resource maybe) would be greatly appreciated. Thank you. -
Django: Change font-color inside a javascript-function
Good day, the font-color of my html-body is changed via a css-file with following code: body { background-color: #6d6a6a; color: white; } Now I've included a Bootstrap-Popover... <button type="button" class="btn btn-sm btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button> ...and the necessary script... <script> $(function () { $('[data-toggle="popover"]').popover() }) </script> But because of my css-file, some parts of text inside my popver (the "title" to be exact) are also rendered in white! I'm really new to javascript, so is it possible - and when it's possible, what would be the best solution - to change my font-color inside my Popover to black? Thanks to all of you! -
Cannot start a project in Atom text editor
Using command:'django-admin startproject first_project' showing ImportError:No module named 'secrets'.enter image description here -
Using MultiFieldPanel inside a StructBlock
If you have a StructBlock class (used inside a StreamField)... Can you still use the Wagtail panels to group some fields (eg MultiFieldPanel) and (ideally!) use the collapsible class on the panel to hide them in some kind of "Advanced" panel? I have tried adding the block.TextBlock definitions into the array for a panel the, however neither the Panel nor the Fields appeared in the form. I cant see anything in the docs about using Panels in StructBlocks: https://docs.wagtail.io/en/v2.8.1/reference/pages/panels.html https://docs.wagtail.io/en/v2.8.1/topics/streamfield.html