Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zappa deployment successful without url
I am trying to deploy a django application through zappa. When I deploy the application everything works correctly and I also get the message "Your updated Zappa deployment is live". But I can't seem to find the url to access the live application. -
Django - Form not saved when submitted
I'm working on a question creation page on my website. I have two different types of questions : classical questions and MCQ. I have a dropdown list with the 2 types of questions and when I choose one and hit "confirm", the corresponding form appears. The problem is, when I submit the form, it doesn't save and a new, blank, form shows up. I created three models in models.py : from django.db import models from django.contrib.auth.models import User class Mod_Choix(models.Model): CHOIX = [ ('qcm', 'QCM'), ('question', 'Question') ] Type_de_question = models.CharField(choices=CHOIX, max_length=200, default='qcm') class Question_Num(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): num_question = models.IntegerField(default=0) question = models.CharField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' Then I use them in forms.py : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM, Mod_Choix class Form_Choix(forms.ModelForm): Type_de_question = forms.Select() class Meta: model = Mod_Choix fields = ['Type_de_question'] class Form_Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de … -
How to create search in product listing page Django
I am doing an eCommerce site in django. And in dashboard there is a product listing page so i need to create search with in the same page so that admin can easily access particular product by searching it. I haven't created search within the listing page rather I have created search page with search result separately.So if anybody could help me. -
Django Crispy Forms with MaterializeCSS
I am trying to write a helper to render MaterializeCSS forms with Django-crispy-forms. So far I couldn't find how to implement the tags properly or the form in general, to make them slide up in animation when active (A material thing, can be observed here: MaterializeCSS FormFields). My code looks like this: class SignUpForm(CustomUserCreationForm): class Meta: model = CustomUser fields = ('email', 'password1', 'password2',) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Div( Div( Field('email', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), Div( Div( Field('password1', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), Div( Div( Field('password2', css_class='validate'), css_class='input-field col s12' ), css_class='row' ), ) I am afraid I am making this overly complicated. Is there any better way to accomplish such html structure for my form with django-crispy-forms? Or would you suggest a different approach all-together, like not using crispy forms? Here is the HTML I am trying to replicate form my form: <div class="row"> <div class="input-field col s12"> <input id="password" type="password" class="validate"> <label for="password">Password</label> </div> </div> -
Getting this error psycopg2.errors.DuplicateTable: relation "posts_post" already exists
I am getting this error after deleting all migrations and again I did makemigrations and during make migrations getting this error. Applying posts.0001_initial...Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "posts_post" already exists The above exception was the direct cause of the following exception: return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "posts_post" already exists This is the production server I can't reset the psql database. -
Correct way for nested python classes (or django foreign keys.) *Conceptual/engineering question*
This is more of a conceptual/engineering question than an actual programming question, but I keep going back and forth between what is the "right" thing to do here. For quick background, I am still a bit of a noob at python/django and don't have a ton of experience working with classes. The program I'm trying to develop is an inventory management app. There are multiple products but lets simplify and say one is shoes and one is clothing. Both products share some attributes (UPC, size, color, etc), but also have some unique attributes (shoe_width, clothing_type) as well. Additionally, it seems like I should have a separate Product class (unique product attributes UPC, size shoe_width, clothing_type) and InventoryItem class (attributes unique to each piece of inventory such as price paid or condition) that inherits its corresponding Product class attributes. Conceptually, I am trying to build this multi-purpose. Users should be able to view product information (not inventory related) and add products and inventory items via django admin or via spreeadsheet upload (spreadsheet hooks already built.) So to the actual question, what is the correct way to implement the individual classes and what are some of the problems I may run into … -
update django inline formset class based view
i've created web blog with django 2.2 each post has multiple images , but when i try to update the post the images wont updated i use class based view class Post(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) title= models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) #others class PostImage(models.Model): post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images') media_files = models.FileField(upload_to=random_url) def __str__(self): return self.post.title and this my forms.py class PostImageForm(forms.ModelForm): class Meta: model = PostImage fields = [ 'media_files' ] class PostUpdateForm(forms.ModelForm): class Meta: model = Post fields = [ 'title','description',#and others ] my views.py PostImageFormSet = inlineformset_factory( Post,PostImage,form=PostImageForm,extra=1,can_delete=True,can_order=False ) class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model = Post form_class = PostUpdateForm template_name = 'posts/update_post.html' def get_context_data(self,**kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['images'] = PostImageFormSet(self.request.POST or None,self.request.FILES,instance=self.object) else: data['images'] = PostImageFormSet(instance=self.object) return data def form_valid(self,form): context = self.get_context_data() images = context['images'] with transaction.atomic(): if form.is_valid() and images.is_valid(): self.object = form.save() images.instance = self.object images.save() return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.username == post.user.username: return True return False def get_success_url(self): return reverse_lazy('post:post-detail',kwargs={'slug':self.object.slug}) it only save the post form not images , it doesnt affect images form thanks -
How to customize url pattern in django
First of all i am new & enjoying django application with no programming background. I was wondering can i generate urls like this www.example.com/user,1 instead of default www.example.com/user/1 where 1 is pk. -
How do I position a form 3-cols from both sides without using Bootstrap
How do I position the form(inside a card), 3-cols from both sides so the form lies in about 6-cols in the middle without using Bootstrap, Materialize or anything similar Thanks <div class="card"> <div class="form_top"> <h1>Form</h1> </div> <div class="field1"> <label>Username</label> <span class="holder">{{ form.username }}</span> </div> <div class="field1"> <label>E-mail</label> <span class="holder">{{ form.email }}</span> </div> <div class="field1"> <label>Password</label> <span class="holder">{{ form.password1 }}</span> </div> <div class="field1"> <label>Confirm Password</label> <span class="holder">{{ form.password2 }}</span> </div> </div> What is looks like: [1]: https://i.stack.imgur.com/BLcsQ.png What it should look like: [2]: https://i.stack.imgur.com/rYlJW.png -
DJango Ajax - Like button only toggle in first post
i am am working on a website where users can like posts, i have lists of all users posts in homepage. i am using ajax so prevent reload page when a like button is clicked. I was able to implement a like view, but i have an issue with Ajax. Ajax only work for the like button in first post, when i click on like button in second post it shows it's working in console, but the like button is not changed from Like to Unlike. @login_required def home_view(request): #All posts in new feed all_images = Post.objects.filter( Q(poster_profile=request.user, active=True)| Q(poster_profile__from_user__to_user=request.user, active=True)| Q(poster_profile__to_user__from_user=request.user, active=True)| Q(poster_profile__profile__friends__user=request.user, active=True)) #If post is liked displayed button posts = Post.objects.filter(pk__in=all_images) is_liked = {} for post in posts: if post.likes.filter(id=request.user.id).exists(): is_liked[post.id] = True context = {'all_images': all_images, 'is_liked': is_liked} return render(request,'home.html', context) #Post likes @login_required def like_post_view(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: is_liked = True post.likes.add(request.user) context = {'post': post, 'is_liked': is_liked,} if request.is_ajax(): html = render_to_string('ajax_postlikes.html', context, request=request) return JsonResponse({'form': html}) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Template: ajax_postlike.html <form action="{% url 'site:like_post' %}" method="POST"> {% csrf_token %} {% if is_liked %} <button type="submit" name="post_id" value="{{ … -
Deploying Django blog app on heroku returns a gunicorn error
I have tried multiple solutions but none of them seems to work. - This is the whole error log which I am getting from the server. 2020-05-01T11:50:22.440421+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-05-01T11:50:22.440421+00:00 app[web.1]: return self.load_wsgiapp() 2020-05-01T11:50:22.440421+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-05-01T11:50:22.440422+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-05-01T11:50:22.440422+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-05-01T11:50:22.440422+00:00 app[web.1]: mod = importlib.import_module(module) 2020-05-01T11:50:22.440423+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-05-01T11:50:22.440424+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-05-01T11:50:22.440424+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-05-01T11:50:22.440424+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-05-01T11:50:22.440425+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked 2020-05-01T11:50:22.440425+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 2020-05-01T11:50:22.440425+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in exec_module 2020-05-01T11:50:22.440426+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-05-01T11:50:22.440426+00:00 app[web.1]: File "/app/blog/wsgi.py", line 16, in <module> 2020-05-01T11:50:22.440426+00:00 app[web.1]: application = get_wsgi_application() 2020-05-01T11:50:22.440426+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-05-01T11:50:22.440427+00:00 app[web.1]: django.setup(set_prefix=False) 2020-05-01T11:50:22.440427+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup 2020-05-01T11:50:22.440427+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2020-05-01T11:50:22.440427+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2020-05-01T11:50:22.440428+00:00 app[web.1]: app_config = AppConfig.create(entry) 2020-05-01T11:50:22.440428+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2020-05-01T11:50:22.440428+00:00 app[web.1]: module = import_module(entry) 2020-05-01T11:50:22.440429+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module … -
Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name 'TodoItem' from 'todo.models'
enter image description here PS C:\Users\krish\Desktop\editdojo> python manage.py shell Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) from todo.models import TodoItem Traceback (most recent call last): File "", line 1, in ImportError: cannot import name 'TodoItem' from 'todo.models' (C:\Users\krish\Desktop\editdojo\todo\models.py) -
Assigning values in a particular order
I have a list which may have the following cases: Case 1: L = [3,2,1] Total_sum = 6, thus 6 elements need to be formed as below: O/P Should be: D = [3,2,1,3,2,3] Case 2: L = [3,2], Total_sum = 5 O/P: D = [3,2,3,2,3] Keeping in mind the list may contain any number of elements, but the functionality should be as above. I have written the code for the above, but am not able to get the correct results: count = 0 ads = iter(ads_query) if adslot_create_list: SongSlot.objects.bulk_create(adslot_create_list) for songslot in adslot_create_list: if count == total_songs: ads = iter(ads_query) count = 0 ad = next(ads,'Finish') if ad == 'Finish': ads = iter(ads_query) ad = next(ads,'Finish') songslot.ads.add(ad) count = count + 1 Here, ads_query = List of values. total_songs = Sum of total elements. Can anyone please guide me on what can we do? -
Django javascript file not loading
I am trying to add a javascript file (script.js) to my existing static directory. I have stored script.js under the same directory as main.css (which work's fine) I am trying to highlight the selected radio image like here: https://jsfiddle.net/dom_sniezka/78dy3to2/46/ I don't understand why it's not working in my Django Project. base.html <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'app_pickfeel/main.css'%}"> <script src="{% static 'app_pickfeel/script.js' %}"></script> </head> script.js jQuery(function ($) { // init the state from the input // sync the state to the input $(".image-radio").on("click", function (e) { $(".image-radio-checked").each(function(i){ $(this).removeClass("image-radio-checked"); }); $(this).toggleClass("image-radio-checked"); e.preventDefault(); }); }); main.css /*Changes Opacity when user hovers over image*/ .brightness { background-color: white; display: inline-block; } .brightness img:hover { opacity: .5; } .image-radio { cursor:pointer; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; border:4px solid transparent; outline:0; } .image-radio input[type="radio"] { display:none; } .image-radio-checked { border: 4px solid #f58723; } -
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 ?