Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Subpages created via admin disappears in menu
I'm creating subpages using admin panel. Then I'm using loop to add them to main menu. They are displayed only on home page. If I switch to one of them they no longer show up in menu (same happen with languages prefixes). so lets say we have home.html with menu: home | about | createdsubpage1 | createdsubpage2 | EN | DE | PL then I go to 'createdsubpage1' or any other page and in menu left only: home | about some views: def index(request, *args, **kwargs): multilanguage = Multilanguage.objects.all() sub_links = Subpage.objects.all() return render(request, 'home.html', {'multilanguage':multilanguage, 'sub_links':sub_links}) def generated_page(request, slug): unique_subpage = get_object_or_404(Subpage, slug=slug) sub = Subpage.objects.get(slug=slug) if sub.is_active: context = { 'unique_subpage': unique_subpage, } return render(request, 'subpage.html', context) else: return render(request, '404.html', {'sub':sub}) app url: urlpatterns = [ path('', views.index, name='index'), path('o-nas', views.about, name='about'), path('oferta', views.offer, name='offer'), path('kontakt', views.contact, name='contact'), path('subpage', views.subpage, name='subpage'), path('<slug:slug>', views.generated_page, name='generated_page'), ] header.html: <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="{% url 'index' %}">{% trans 'Strona główna' %}</a></li> <li><a href="{% url 'offer' %}">{% trans 'Oferta' %}</a></li> <li><a href="{% url 'about' %}">{% trans 'O Nas' %}</a></li> {% for sub in sub_links %} {% if sub.is_active %} <li><a href="{% url 'generated_page' sub.slug %}">{% trans sub.title %}</a></li> {% endif … -
How to get those subcategories to show on main categories?
I'm very new to django and I'm making a ecommerce website. I'm trying to have subcategories for my products so I assigned each product with subcategories and the subcategory have parent_category. However I'm have trouble getting all products of the parent category to show. Can you help me out please class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(unique = True) parent_category = models.ForeignKey('self', null=True, blank=True,on_delete=models.DO_NOTHING) def list_of_post_by_category(request,category_slug): maincat = [] subcat = [] categories = Category.objects.all() obj = Product_info.objects.filter() if category_slug: category = get_object_or_404(Category, slug=category_slug) obj = obj.filter(category=category) for c in categories: if c.parent_category == None: maincat.append(c) elif c.parent_category == category: subcat.append(c) context = {"category":maincat,"subcategory":subcat,"obj_list":obj,"showcat":category} return render(request,'cat.html',context) -
Django models for social media apps ValueError in ManyToManyField
I am building a social media apps. This is my models: from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): admin = models.ManyToManyField(Person, related_name='admin') members = models.ManyToManyField(Person, blank=True, related_name='members') def save(self, *args, **kwargs): self.members.add(self.admin) super(Group, self).save(*args, **kwargs) When i try to create new group, it throws me following error because of overriding save method.. ValueError at /admin/social/group/add/ "<Group: Group object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. I want an admin of a group also will be a members of the same group, that is why i override the save method but it throws me above errors. Also i tried to achieve this with Django signal like below @receiver(post_save, sender=Group) def make_admin_also_members(sender, instance, created, **kwargs): if created: instance.members.add(instance.admin) instance.save() and it throws me following error: TypeError at /admin/social/group/add/ int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager' then i try achieve it like this: @receiver(post_save, sender=Group) def make_admin_also_members(sender, instance, created, **kwargs): if created: instance.members.add(str(instance.admin)) instance.save() it throws me following error: ValueError at /admin/social/group/add/ invalid literal for int() with base 10: 'social.Person.None' After i got above error, i tried to achieve this like below @receiver(post_save, … -
"Back button" problem with AJAX form post on a multi-page site
In my Django project I have a page with a table of devices and a form to add a new device. And now I want to translate that form post to AJAX. I've done this with a help of jQuery Form Plugin (http://malsup.github.com/jquery.form.js): $('#deviceAddForm').ajaxForm({ dataType: 'json', async: true, cache: false, success: function (data) { device_row = '<tr>' + '<td>' + data['name'] + '</td>' + '<td>' + data['description'] + '</td>' + '</tr>'; $(device_row).hide().appendTo($('#deviceTableBody')).show("slow") } }); And now I have a browser "back button" problem. If a user posts some devices, goes to different site and then back (through browser back button) additional AJAX content is not displayed. This problem is usual to AJAX, and all of the solutions, that I've found refer to History API. When AJAX content is updated there should be history.pushState call, and browser back/forward buttons should be handled through window.onpopstate event. Maybe I am missing something, but this way seems to work only if a user travels only on one particular single page application site (SPA). If a user goes, for example, to Google and back onpopstate event will not fire (HTML5 History API: "popstate" not called when navigating back from another page). So this doesn't seem … -
Django Updating A one To Many Array
So I get this error Direct assignment to the reverse side of a related set is prohibited. Use emails.set() instead. This is how my code looks like class Client(models.Model): class Email(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails', null=True, blank=True) email = models.CharField(null=True, blank=True, max_length=50) class EmailSerializer(serializers.ModelSerializer): class Meta: model = Emailfields = '__all__' class ClientSerializer(serializers.ModelSerializer): emails = EmailSerializer(required=False, allow_null=True, many=True) def update(self, instance, validated_data): # Update all fields of Client. [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() return instance So the client can have many emails. When update is called, it says Direct assignment to the reverse side of a related set is prohibited. Use emails.set() instead. This error message can be avoided by removing the emails from the validated_data via let emailsData = validated_data.pop('emails', []). but once done, im not sure what to do next in order to update the emails array if it needs updating, or deleting it if it is not in the emailsData array anymore. Thoughts? -
How to save a qr code image as a model field in Django
I want to add a qr code image field to my 'Person' model. The data of the qr code will come from the user_id and will store its profile page – for example, user 1234 will have the qr code that contains siteurl.com/1234. I began by creating the image field, but I am not sure as to where to go from there. Any help would be appreciated! Models: from django.db import models import uuid class Person(models.Model): user_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() number_of_guests = models.PositiveIntegerField() qrcode_image = models.ImageField( upload_to='qr_code_images', blank=True, null=True ) def __str__(self): return " ".join([self.first_name, self.last_name, str(self.user_id)]) -
Django: How do I show formatted number with thousands separator correctly?
I am trying to show formatted number with thousands separator like '123,456,789', but with below code it doesn't show as desired at html. How should I correct this? The below does work but it shows like '123456789 EUR' views.py class ScatterView(TemplateView) : def get(self, request, *args, **kwargs) : context = super().get_context_data(**kwargs) context['price'] = str(plots.get_price()).format() return render(request, 'index.html', context) index.html {{ price }} EUR -
How to save textarea data when click outside the textarea using ajax
I am using froala editor and i want text in text area of editor saved when user clicks outside that textarea using Ajax i am new in ajax id of content editor is #id_content This is my form part in django <form method="POST" id="froala_form" class="PageForm _inputHolder"> {% csrf_token %} <div class="_alignRight posR _saveBTNOut"> <button type="submit" class="_btn btnPrimery">Save as Draft</button> This is what i have tried but not getting any proper logic function loadDoc(){ var xhttp=new XMLHttpRequest(); xhttp.onreadystatechange=function{ if(this.readyState==4 && this.status==200){ var x = document.getElementById("id_content"); x.addEventListener("click", ajaxsavefunc); } }; xhttp.open("GET",'url', true); xhttp.send(); } function ajaxsavefunc(xhttp) { document.getElementById("froala_form").innerHTML = editor.html.get() } -
Django JSONField versus normal fields
i want to store statistics of game (online games) which method should i use Does using JSONField have a performance impact, and what problems can it cause in the future? class Statistics(models.Model): game=models.Foreignkey data=JSONField() { "team1": { "rank": 25, "point": "10", "assists": 25, "prize": 4, "name": "TeamName", "players": { "top": { "items": [ { "id": 1, "name": "aa" }, null, { "id": 2, "name": "bb" }, { "id": 5,... OR class Statistics(models.Model): game=models.Foreignkey rank=models.SmallIntegerField() point=models.SmallIntegerField() and more... -
Should I divide a table by OneToOneField if the number of columns is too many?
I have a student model that already has too many fields including the name, nationality, address, language, travel history, etc of the student. It is as below: class Student(Model): user = OneToOneField(CustomUser, on_delete=CASCADE) # Two many other fields A student has much more information I store in other tables with a OneToOne relationship with the student model such as: class StudentIelts(Model): student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) # 8 other fields for IELTS including the scores and the date and file field for uploading the IELTS result # I have other models for Toefl, GMAT, GRE, etc that # are related to the student model in the same manner through a OneToOne relationship Should I merge the tables into one table or the current database schema is good? The reason I chose this schema was that I was not comfortable working with a table with two many columns. The point is that for every student, there should be a table for IELTS and other models and, as a result, the number of rows in Student table is the same as the number of rows in the IELTS table, as an example. -
How to get views.py variables into <script> code django
I'm creating a chatbot using html template and django. I am able to get user input from html to views.py but when I'm unable to send the output to the same html. I have tried giving {{output}} in the script tag. But didn't work. My chatbox.html code including jquery: <html> <body> <form action="/chatbot/" method="post"> {% csrf_token %} <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).on("keypress", "input", function(e){ if(e.which == 13){ var inputVal = $(this).val(); document.getElementById("myTextarea").innerHTML += '\nMe: '+inputVal+'\n'); var outputVal = '{{output}}' || false; function printText(){ document.getElementById("myTextarea").innerHTML += '\nBot: '+outputVal +'\n'; } setTimeout(printText,500); } }); </script> <textarea id="myTextarea" rows="30", cols="60", name="text-area">Hi dude! Welcome to Chat Bot</textarea> <input id='myInput' name="utext" placeholder="Ask Something..." type="text"> </form> </body> </html> My views.py file: from django.shortcuts import render, HttpResponse def get_input(request): print(request.POST) input = request.POST.get('utext',False) print("input:",input) output = "Hello! How are you doing?" return render(request, "chatbox.html", {'output': output}) Hi dude! Welcome to PIP Bot Me: hi Bot: Hello! How are you doing? This is the expected output from this view. -
How to check last login in django template?
Here I am trying to display user online if the user is currently logged in the site else I want to display the last login in with timesince .But I got stuck while checking if the user is currently logged in or not in the site. How can I check it ? templates {{user.username}} <small class="sidetitle" style="color:red;"> {% if user.currently_logged_in %}Online {% else %} seen {{user.last_login|timesince}} ago{% endif %} </small> -
Include custom URL prefix for languages in Django
I am trying to include the country codes as well while implementing django language translation apart from the usual language codes like en and ar which would be appended to the url's. I am trying to acheive something like this https://docs.djangoproject.com/uae/1.10/howto/ # this will be English by default https://docs.djangoproject.com/uae-ar/1.10/howto/ # this will be Arabic https://docs.djangoproject.com/uae-fr/1.10/howto/ # this will be French Below is my settings file variables LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en', _('English')), ('uae-ar', _('Arabic')), ('uae-fr', _('French')), ) I would like to know the best practice of implementing this method. Please do let me know if I am missing out on anything here. -
How to Make username field case insensitive in Dnago? Is my Implementation right?
I am in starting of my web project using Django and Django Rest Framework. I wanted my username field to be case Insensitive and hence I searched web about how to achieve it and got to this beautiful blog: https://simpleisbetterthancomplex.com/tutorial/2017/02/06/how-to-implement-case-insensitive-username.html. He suggested this method: from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) class CustomUser(AbstractUser): objects = CustomUserManager() for models.py But when I wrote tests, they were failing because User.objects.get_by_natural_key was returning two user objects when I created two users with same username, but different case (ex: 'aniket' and 'Aniket'). So, I got through this approach : from django.contrib.auth.models import UserManager, AbstractUser # Create your models here. class CustomUserManager(UserManager): def create_user(self, username, email=None, password=None, **extra_fields): return super().create_user(username.lower(),email,password,**extra_fields) def create_superuser(self, username, email, password, **extra_fields): return super().create_superuser(username.lower(),email,password,**extra_fields) def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) class User(AbstractUser): objects = CustomUserManager() So, is this approach up to the mark? -
Manually displaying formset forms as a table in Django
I am trying to create an inline formset displaying form fields as a header table (for header data) and then the item data as a child table. Header data is displayed as expected but I am stuck at the child data (refer the image). I have so far done this (as shown below): models.py class MaterialTyp(models.Model): material_type_id = models.CharField(primary_key=True, max_length=4, verbose_name='Material Type') material_type_desc = models.CharField(max_length=100, verbose_name='Material Type Desc') def __str__(self): return '{0}-{1}'.format(self.material_type_id, self.material_type_desc) class PurchOrder(models.Model): PO_Number = models.IntegerField(primary_key=True, max_length=10, unique=True, verbose_name='PO Number') po_doc_type = models.CharField(max_length=2, null=True, default='PO', verbose_name='Doc Type') po_date = models.DateTimeField(default=datetime.now, null=True, verbose_name='PO date') po_closed = models.BooleanField(default=False, verbose_name='Close PO') def __str__(self): return '{0}'.format(self.PO_Number) class PurchOrderItem(models.Model): po_item_num = models.AutoField(primary_key=True, verbose_name='Line Item Number') hdr_po_num = models.ForeignKey(PurchOrder, on_delete=models.CASCADE, null=True, verbose_name='PO Number') po_itm_matl_type = models.ForeignKey('MaterialTyp', on_delete=models.SET_NULL, null=True, verbose_name='Matl Type') po_itm_split_allowed = models.BooleanField(default=False, verbose_name='Split?') def __str__(self): return '{0}'.format(self.po_item_num) forms.py class CreatePoForm(forms.ModelForm): class Meta: model = PurchOrder fields = ('po_doc_type', 'po_date', 'po_closed') widgets = { 'po_doc_type': forms.TextInput(attrs={'readonly': 'readonly', 'style': 'width:60px; background:lightgrey'}), } class CreatePoItemForm(forms.ModelForm): class Meta: model = PurchOrderItem fields = ('po_item_num', 'po_itm_matl_type', 'po_itm_split_allowed') CreatePoFormset = inlineformset_factory( PurchOrder, PurchOrderItem, form = CreatePoItemForm, can_delete=True, min_num=0, validate_min=True, max_num=100, extra=1, ) views.py def create_dynamic_po(request, object_id=False): template_name = "pudding/purchorder_create_dyna.html" if object_id: fresh_form = PurchOrder.objects.get(pk=object_id) else: fresh_form = PurchOrder() if … -
Django: Accessing variables in class-based views
I'm setting up a website with a fairly basic users system where you can do the usual stuff like login, change your password etc. I'm using an example Django project and changing it a bit here and there. When the user is logged in I am able to access the user's email address and put it into the page by adding this to the template {{ request.user.email }}. But in a link emailed to user to reset their password where the user is not logged in the same thing doesn't work. I'm guessing it must be possible to access it somehow though. This is the class view that I'm using: class RestorePasswordConfirmView(PasswordResetConfirmView): template_name = 'accounts/restore_password_confirm.html' def form_valid(self, form): form.save() messages.success(self.request, _('Your password has been set. You may go ahead and log in now.')) return redirect('/') def get_context_data(self, **kwargs): context = super(RestorePasswordConfirmView, self).get_context_data(**kwargs) context = {**context, **host_(self.request)} return context Is there any way to access the user.email variable? -
Need help in emailing errors
I can't seem to get my errors emailed, It gets logged successfully but no email gets sent! There is no traceback or any other errors, just that if an error code 500 is encountered, it logs it but doesn't send any email to the admins! I have tried many solutions on the internet and none have worked! Here is a part of my settings.py: ADMINS = [('Prithvi', '<email1>')] #Email Settings MAILER_LIST = ['<email1>'] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST = '<email2>' EMAIL_HOST_PASSWORD = '<password>' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_USE_LOCALTIME = True SERVER_EMAIL = '<email2>' DEFAULT_FROM_EMAIL = '<email2>' #Logger and Handler settings # Python logging package import logging # Standard instance of a logger with __name__ stdlogger = logging.getLogger(__name__) # Custom instance logging with explicit name dbalogger = logging.getLogger('dba') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'development_logfile': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.FileHandler', 'filename': … -
Django ORM Count by multiple fields
I'm working with Django and I need to group a model by multiple fields. The query I want is: select field1, field2 from tbl group by field1, field2 having count(*) > 1 Then what I've tried is the following: Tbl.objects.annotate(cnt=Count('field1','field2')).filter(cnt__gt=1) But, it didn't work. Can't group by multiple fields on ORM? Do I need to write RawQuery? -
HttpResponse data not available to jquery code
I am trying to implement a success or error pormpt on submission of a contact_me form. I am writing this for a portfolio website and the data fields of contact_me form is been emailed to the client and the email service in the back-end is working properly. @method_decorator(csrf_protect) def post(self, request, *args, **kwargs): subject = request.POST.get('subject') name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') try: mail_message = Mail( from_email=email, to_emails='mailid@website.com', subject=subject, html_content="from: " + name + " Message: " + message ) response_data = "SUCCESS!!" print(response_data) return HttpResponse(json.dumps({'data': response_data}),content_type="application/json") except Exception as e: print(str(e)) return HttpResponse(json.dumps({"nothing to see": "this isn't happening"}),content_type="application/json") return render(request, self.template_name) function create_contact() { $.ajax({ url:'', type:"POST", data: { name : $("input#name").val(), email : $("input#email").val(), phone : $("input#subject").val(), message : $("textarea#message").val(), }, success: function(json) { console.log("SUCCESSFUL!!"); }, error: function(xhr,errmsg,err) { console.log("error!!"); } }); }; $("#contactForm").on("submit",function(event) { console.log("contactForm onclick worked"); // event.preventDefault(); create_contact(); }); the above code outputs a "error!!" even on successfull submission of the contact_me form -
There are some values Django cannot serialize into migration files
Cannot makemigrtions. ValueError: Cannot serialize: stories.validators.ValidateImageSize object at 0x7fb4e8c8b810 There are some values Django cannot serialize into migration files As I understood, we can't serialize class, anyway, how to solve this problem? field in model image = models.ImageField(upload_to=upload_location, validators=[ValidateImageSize('1 kb')])) validators.py class ValidateImageSize(object): ... -
Domain Port uWsgi Tutorial - uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html#about-the-domain-and-port
Am following the Tutorial here - as i was tinkering with my working Nginx config and messed things up . Now i have a very basic doubt . In the uWsgi docs here - https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html#about-the-domain-and-port Its mentioned that - This should serve a ‘hello world’ message directly to the browser on port 8000. Visit: http://example.com:8000 I substitute my own domain / FQDN , here -- http://digitalcognition.co.in:8001/dc/datasets_listView zilch - nothing ? My question - having gone through the tute till this stage , how does anything know yet whats my domain - i havent configured Nginx yet ? Total confusion. Someone kindly help thanks . -
How to auth using JWTTokenUserAuthentication
Henlo! App deps: djangorestframework-simplejwt==4.3.0, djangorestframework==3.10.3 I'm trying to auth User with JWTTokenUserAuthentication without using DB using shared SECRET_KEY. In my settings I have: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=120), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(hours=12), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': SECRET_KEY, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': datetime.timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': datetime.timedelta(days=1), } For the views I use rest_framework_simplejwt.views.TokenObtainPairView. And in my app's urls: urlpatterns = [ path('test-token/', TokenObtainPairView.as_view(), name='token_obtain_pair') ] So, I'm making post request providing it with Bearer token and credentials as username and password. But I get message: { "detail": "No active account found with the given credentials" } What should I do to auth correctly? -
how to write serializer for joined model?
i have applied join on two tables with following query, VIEWS.PY class performance(viewsets.ModelViewSet): queryset = Leads.objects.select_related('channelId').values("channelId__channelName").annotate(tcount=Count('channelId')) serializer_class = teamwise_lead_performance_serializer but i am unable to catch response using this serializers, SERIALIZER.PY class channel_serializer(serializers.ModelSerializer): class Meta: model = Channels fields = ['channelName'] class performance_serializer(serializers.ModelSerializer): tcount = serializers.IntegerField() channel = channel_serializer(many=True, read_only=True) class Meta: model = Leads fields = ['tcount', 'channel'] i am getting the following, [ { "tcount": 88 }, { "tcount": 25 }, { "tcount": 31 }, { "tcount": 4 }, { "tcount": 1 }, { "tcount": 23 }, { "tcount": 2 }, { "tcount": 27 } ] expected response is, [ { "channelName": "abc", "tcount": 88 }, { "channelName": "def", "tcount": 25 }, { "channelName": "ghi", "tcount": 31 }, { "channelName": "qwe", "tcount": 4 }, { "channelName": "rty", "tcount": 1 }, { "channelName": "uio", "tcount": 23 }, { "channelName": "psa", "tcount": 2 }, { "channelName": "dfg", "tcount": 27 } ] i have tried the following, How to join two models in django-rest-framework why is it not getting the channelName in response? what am i doing wrong here? Thank you for your suggestions -
ModuleNotFoundError: No module named 'webpushapi'
I'm implementing a package called django-webpush in my project Ref: https://pypi.org/project/django-webpush/ Firstly, I installed this package using the command pip install django-webpush and it got installed successfully. Next in my INSTALLED_APPS in Settings.py I included the new application called web push. When I run python manage.py run server It tells me: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'webpushapi' -
django a particular view is getting triggered twice (GET/POST) both and only in chrome, firefox and postman requests trigger the view just once.W
get requests are javascript redirects just by changing window.location.href and post requests are ajax requests, same url in django url conf serves the two of them. The page is heavily populated with data, images and links etc. which do come as a response in get and post requests. On Chrome it executes the request twice, I cannot see it going twice in the Network tab on dev tools but at the terminal where I am running server I can see the view's print statements executing twice. I could have kept it fine like this, but then the first request goes with parameters and the second goes without the parameters(data to post) and the resultant page is always from the second request which is not exactly what the user is asking for.