Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically load data in django
I've been learning django for the last couple of days and I'm trying to build a very simple app that consists on the following: models.py class Stock(models.Model): date = models.DateField() price = models.IntegerField() views.py def index(request): list_dates = Stock.objects.order_by('date').values_list('date', flat = True).distinct() my_dict = {'list_dates' : list_dates} return render(request, 'stocks/index.html', context = my_dict) index.html <body> <select name="date" id="date"> <option value="select">Select Data</option> {% for date in list_dates %} <option value="{{date}}">{{date}}</option> {% endfor %} </select> <h1>{{price here}}</h1> </body> This is a very simplified version of the final concept, which will have many more fields other than price What I want to do is: Get the date the user selected on the select tag Use it to access the django database and then only load the price that matches the selected date Insert it inside the h1 tag Refreshing this when the date is changed on the select tag What's the easiest way to do this? Thanks! -
Static files not loading
url inside main 'mySite' directory urlpatterns = [ path('admin/', admin.site.urls), path('coming-soon/', include('comingSoon.urls')), ] url inside comingSoon app directory urlpatterns = [ path("", views.index, name="coming-Soon") ] views.index inside comingSoon app def index(request): return render(request, 'comingSoon/coming-soon.html') inside template "coming-soon.html' <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="" /> <meta name="keywords" content="" /> <title>Pitnik Social Network Toolkit</title> <link rel="icon" href="images/fav.png" type="image/png" sizes="16x16"> {% load static %} {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/main.min.css'}"> <link rel="stylesheet" href="{% static 'css/style.css'}"> <link rel="stylesheet" href="{% static 'css/color.css'}"> <link rel="stylesheet" href="{% static 'css/responsive.css'}"> </head> <body> <div class="theme-layout"> <div class="gap2 mate-black medium-opacity vh100"> <div class="bg-image" style="background-image:url(images/resources/coming-soon-bg.jpg);"></div> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="coming-head"> <div class="logo"> <a href="index.html" title=""><img src="images/logo.png" alt=""></a> </div> <ul class="social-circle "> <li><a class="facebook-color" href="#" title=""><i class="fa fa-facebook"></i></a></li> <li><a class="twitter-color" href="#" title=""><i class="fa fa-twitter"></i></a></li> <li><a class="google-color" href="#" title=""><i class="fa fa-google-plus"></i></a></li> <li><a class="vk-color" href="#" title=""><i class="fa fa-vk"></i></a></li> </ul> </div> <div class="coming-meta"> <h1>We're Coming!</h1> <p>We are working hard to bring you new experience</p> <ul class="countdown"> <li><span class="days">00</span><p class="days_ref"></p></li> <li> <span class="hours">00</span><p class="hours_ref"></p></li> <li> <span class="minutes">00</span><p class="minutes_ref"></p></li> <li> <span class="seconds">00</span><p class="seconds_ref"></p></li> </ul> <form method="post"> <input type="text" placeholder="Submit inquiry..."> <button type="submit"><i class="fa fa-arrow-right"></i></button> </form> </div> </div> </div> </div> </div> … -
Download data as Excel file in Django with ajax
on the page with ajax code, there is a form that I filter. I am sending the filtered data to download_excel method with ajax, but the download is unsuccessful. What is the reason? view.py def download_excel(request): jsdata = request.GET.get('listed_data') objdata = eval(jsdata) #objdata = [{"id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1"},{"id":"123123123","location":"test_location_1","device":"test_device_1","datetime":"12/12/2020","name":"asdas asdas","age":"21","gender":"male","temp":"37.6","mask":"0",risk":"1"}...] response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = "attachment; filename='Report.xls'" wb = xlwt.Workbook(encoding="utf-8") ws = wb.add_sheet("Report") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ["ID","Location","Device","Datetime","Full Name","Age Range","Gender","Body Temp","Mask","Risk"] for col_num in range(len(columns)): ws.write(row_num,col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() for row in objdata: row_num += 1 ws.write(row_num, 0, str(row["id"]), font_style) ws.write(row_num, 1, row["location"], font_style) ws.write(row_num, 2, row["device"], font_style) ws.write(row_num, 3, row["datetime"], font_style) ws.write(row_num, 4, row["name"], font_style) ws.write(row_num, 5, row["age"], font_style) ws.write(row_num, 6, row["gender"], font_style) ws.write(row_num, 7, row["temp"], font_style) ws.write(row_num, 8, row["mask"], font_style) ws.write(row_num, 9, row["risk"], font_style) wb.save(response) return response urls.py path('ajax/download_excel/', views.download_excel, name="download_excel") template html function download_excel(){ $.ajax({ url: "/events/ajax/download_excel/", data:{ 'listed_data': "{{data|safe}}" } }) } -
Render a Multipage Excel File
There is a library called templated-docs that allowes render templates to different file formats. My goal is to render multipage Excel file: I have an .ods template which looks like this: Also have a list of dicts each for a page: context = [ {"number": 1}, {"number": 2}, ] Rendering of context happens here https://github.com/alexmorozov/templated-docs/blob/master/templated_docs/init.py#L128. As far as I can see context should be a dictionary. And there is no built-in way to render a multipage excel, right? Well, for now everything I could figure out is to render data dicts by one (template.render({"number": 1}), template.render({"number": 2})) and then combine them into a single entity. But I'm not sure this to be a proper way. Could you say please if there is some another ways to solve this problem? P.S. The real file have 15 pages. -
virtualenvwrapper on Mac (using terminal) : Error while finding module specification for 'virtualenvwrapper.hook_loader'
Trying to finish installing virtualenvwrapper. I have already installed Python 3.8.3 and virtualenv/virtualenvwrapper but when I am exporting to setup a virtual environment location using: export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 ' export PROJECT_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh It says there is no directory. So I have changed my source to be /Library/Frameworks/Python.framework/Versions/3.8/bin/virtualenvwrapper.sh because after using which virtualenvwrapper.sh, that is where it is. once I have done this though i get the error virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 and that PATH is set properly. What exactly do I need to change for this environment to work? -
Django Query In Views.py Overriding Another Query In Views.py
I have an issue where the max_views_query if statement qs is overriding the min_views_query if statement qs. How would I prevent the max_views_query if statement qs from overriding the min_views_query qs and keep them separate from each other but still work with the rest of the code? Courses Forms.py: class CourseForm(forms.Form): min_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'min_views', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) max_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_views', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['min_views'].label = "Min Views:" self.fields['max_views'].label = "Max Views:" Courses Views.py: class CourseListView(ListView): model = Course def get_queryset(self): qs = super().get_queryset() self.form = form = CourseForm(self.request.GET) if form.is_valid(): min_views_query = self.request.GET.get('min_views') max_views_query = self.request.GET.get('max_views') if min_views_query: qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__gte=min_views_query) if max_views_query: qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__lte=max_views_query) return qs Courses Models.py: class Course(models.Model): views = models.PositiveIntegerField(default=0) @property def total_lesson_views(self): lessons_dictionary = Lesson.objects.filter(course=self).aggregate(Sum('views')) return lessons_dictionary['views__sum'] class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views = models.PositiveIntegerField(default=0) -
in django template unable to show content inside if block
when i write if statement nothing show in html but when i remove the if statement the code show all items what is wrong {% for catagory in catagory_list %} {% for item in product_list %} {% if item.catagory == "Fruits" %} <p>{{item.catagory}}</p> <p>{{item.name}}</p> <p>{{item.price}}</p> <img src="{{item.image.url}}" alt=""> {% endif %} {% endfor %} {% endfor %} <!-- <p>{{item -
How to get a pk from Django URL into ajax
I have a django url that uses a primary key in it, and I want to be able to reference it in my javascript/ajax snippet. I can't find any examples online though, is this possible or do I need to do something like remove all letters from the url? urls.py path('survey/<int:pk>/record_question/', QuestionRecordView.as_view(), name='survey-question-record'), -
Why is my smooth scrolling function not working?
I'm creating a website using Django, and I want the link in the navbar (when clicked) to smoothscroll to the element that I want. This is what I have: base.html <li> <a class="nav-item nav-link" href = '' class='scroll-about'>About</a> </li> //unrelated elements <script> // scroll into view document.querySelector('.scroll-about').addEventListener('click', function(e) { e.preventDefault(); document.querySelector('.about').scrollIntoView({ behavior: 'smooth' }); }); home.html <div class="about col-12 col-md-6"> <div class="d-flex flex-column align-items-center py-5 text-uppercase"> <h3 class="h3-responsive bg-primary text-center text-white rounded font-weight-bold w-50 px-4 py-2 shadow">About</h3> <h1 data-easy-reveal = "" class = " h1-reponsive font-weight-bold my-5 ml-3">Our vision is for every business to leave its mark on the digital world</h1> <h1 data-easy-reveal = "" class = "down h1-reponsive font-weight-bold ml-3">Our vision is to bring them to the next level </h1> </div> </div> The rest of the code works fine, the Django templating is all fine. I just can't seem to get this scroll function to work. I've tried moving the script around the bottom of the html file, and as well as putting it in the head element of the html file. I've also tried using jQuery smooth scroll and it doesn't work either. Hope someone can help me with this! the jQuery code I tried (in this case … -
models.DoesNotExist [...] matching query does not exist. Result is being found in the DB
I 've found just a few questions about that without any answer. I have this error message when running my django app: Cellar.models.DoesNotExist: LotModel matching query does not exist. What bother me, is that when I try this in the console while debugging (when the program stop at this error message in PyCharm), I do find a correct answer so the matching query does exist! If I change return self.lots.get(birth=self.dt, death=self.dt) by return self.lots.filter(birth=self.dt, death=self.dt).first() this error is not raised... I can't figure why. This error comes from here: class PrimaryItem(Item): is_primary = True class Meta: proxy = True @property def lot(self) -> PrimaryLot: return self.lots.get(birth=self.dt, death=self.dt) # <- line producing the error, note that this is not a multiple results problem I can't find why django is throwing me this, since there is no "real" error. If I change this line by return self.lots.filter(birth=self.dt, death=self.dt).first(), the error is not raised as I said, but after that I will have this line: transfer.starting_lot.children.add(new_lot) giving me this error: AttributeError: 'NoneType' object has no attribute 'children' and guess what? transfer.starting_lot is not None if I manually check that. It seems to be the same problem here. Can it be django-polymorphic (seems to … -
How to name a audio file when saving into server with POST
I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server. The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this? Python views.py def voice_request(request): f = open('./Grabaciones/file.wav', 'wb') f.write(request.body) f.close() return HttpResponse('audio received') Javascript part function sendData(data) { let csrftoken = getCookie('csrftoken'); let response=fetch("/salud/voice_request/", { method: "post", body: data, headers: { "X-CSRFToken": csrftoken }, }) } -
I am new in django, I have written function to display latest entered record,But got problem that no output of function is displayed
I have created models in models.py as under: class Student(models.Model): gen_choices = ( ("Male", "Male"), ("Female", "Female"), ("Third", "Third"), ) enrollNo = models.IntegerField(default=add_one) fname = models.CharField(validators=[max_len_check], max_length=26) lname = models.CharField(validators=[max_len_check], max_length=26) gender = models.CharField(max_length=6, choices=gen_choices) dob= models.DateField() address = models.CharField(max_length=256) email = models.EmailField() mobile = models.BigIntegerField() status = models.BooleanField() userID = models.OneToOneField(User, on_delete=models.CASCADE) image = models.FileField(upload_to="stdimages/", null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return str(self.enrollNo) My views.py contains to display the latest entered data from database as under: def std_info(request): if request.user.is_authenticated: result = Student.objects.latest('created_at') pars = {'result': result} return render(request, 'std_info.html', pars, {'title': 'Student registration Success'}) else: messages.info(request, 'You need to Login first.') return redirect('/user/logout') My urls.py contains as under details: path('std_info/', std_info, name='std_info'), My templates contains details as under: {% extends 'user/layout1.html' %} {% block content %} <table width="100%"> <tr> <td align="left" width="80%"><a href="/user/add/"><h1>Congratulation! Entrance Exam Form Registered Successfully.</h1></a></td> <td align="right" width="30%"><a href="/user/home">CLOSE</a></td> </tr> </table> <hr> <br> <font color="blue" size="4" face="times newroman"><u><b>To Generate 'Entrance Exam Hall Ticket' Enter Enroll No. and click on [GENERATE HALL TICKET]:</b></u></font><br> <form action="/user/hall_ticket1" method="GET"> {% csrf_token %} <!--<div class="form-row"><label for="enrollno1">Enroll No.</label></div>--> <div class="form-row"><input type="enrollno1" id="enrollno1" name="enrollno1" placeholder="Enter Enroll No."> <input … -
Check for string in queryset within a Django template
I know this should be straight-forward, but for some reasons I'm not getting the results I want. This instruction: {{user.profile.role.all}} in my Django template outputs this: <QuerySet [<Role: Creator>, <Role: Performer>, <Role: Venue>]> I'd like to check if a role is within this queryset; so, for instance, if I want to check if a role 'venue' is present, according to what the documentation tells me, I should do: {% if "Venue" in user.profile.role.all %} Right? The above-mentioned if, though, returns false. Why is that? -
Selecting only non null fields from the filter rows django
I have this query which are getting the required rows which i want but the problem is most fields/columns have null values I just want to get only those fields from these rows which have non null values queryset = User.objects.filter(email__exact=email) Here, is my model class User(models.Model): email = models.CharField(max_length=50, null=True, blank=True) password = models.CharField(db_index=True, max_length=40, null=True) source = models.CharField(default='unknown', max_length=150, null=True) domain = models.CharField(max_length=50, null=True, blank=True) before_at = models.CharField(max_length=255, null=True, blank=True) username = models.CharField(db_index=True, max_length=150, null=True, blank=True) hash = models.CharField(max_length=255, null=True, blank=True) ipaddress = models.CharField(max_length=50, null=True, blank=True) phonenumber = models.CharField(max_length=100, null=True, blank=True) def __str__(self): if self.email != None: return self.email elif self.username != None: return self.username -
File upload field doesn't display (Django)
I have a django form, but it's not showing the "upload file" field when I render it on my website. What am I doing wrong? Ideally, the form has a question ID associated with it that's submitted automatically (e.g. it doesn't have to be manually put in by the user when uploading the file) models.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) response_file = models.FileField(upload_to='audio_responses') forms.py class PostAudio(forms.ModelForm): class Meta: model = Choice fields = ('response_file',) views.py def QuestionRecordSubmitView(request, pk): model = Question if request.method == 'POST': form = PostAudio(request.POST, request.FILES) if form.is_valid(): form.instance.question_id = pk form.save() # get survey pk question_instance = Question.objects.get(pk=pk) survey_pk = question_instance.survey.pk return redirect('survey-share',pk=survey_pk) else: form = PostAudio() return render(request, 'survey/question_audio_submit.html') html {% extends "landing/base.html" %} {% block content %} <h2>New Submission</h2> <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock content %} -
How to set default group group for users in Django Rest Framework?
I would like to automatically assign the newly registered user to the "User" group. So the group "User" should be the default group for all users. Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'groups') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): groups_data = validated_data.pop('User') user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) for group_data in groups_data: user.groups.add(group_data) return user Register API # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) [1] }) When i run the code i get an error: Bad Request: /api/auth/register. I can not really trace back where my mistake is? Im happy for any clarification. -
django docker-compose failed can't find static
So this is my backend Dockerfile it can't find backend/static what is wrong here? FROM python:3.8.0-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip ADD requirements.txt /app/ RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt -r requirements.txt COPY scripts/start*.sh / ADD . /app/ CMD ["python3", "backend/manage.py", "collectstatic", "--no-input"] CMD ["python3", "backend/manage.py", "makemigrations"] CMD ["python3", "backend/manage.py", "migrate", "--no-input"] CMD ["gunicorn", "backend.wsgi", "-b", "0.0.0.0:7000"] and this is my frontend Dockerfile # build stage FROM node:14.3.0-alpine3.10 as build-stage WORKDIR /app/ COPY frontend/package.json /app/ RUN npm cache verify RUN npm install COPY frontend /app/ RUN npm run build # production stage FROM nginx:1.17.10-alpine as production-stage COPY nginx/prod/prod.conf /etc/nginx/nginx.conf COPY backend/static /usr/src/app/static/ COPY --from=build-stage /app/dist /dist/ EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] if you need more info(docker-compose file): https://github.com/Kenan7/djangorf-vue-ecommerce/tree/gcloud ALSO, does GCP support docker-compose.yml file? if not what do I convert it into? -
How do I resolve a non-interactive object in Django
error_template Some answers that I have seen here mention that it has to do with the dictionary and the keywords of the same that interact with the template, ** but ** the error is that you cannot interact with Downloads, I do not understand that it has to do something with the other one. Models class Repositories(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) url = models.TextField(blank=True, null=True) class Downloads(models.Model): category_name = models.CharField(max_length=125, null=False, blank=False) category_url = models.TextField(null=False, blank=False) download = models.BooleanField(default=False) register_date = models.DateField(auto_now=True) harvest_date = models.DateField(null=True, blank=False) number = models.IntegerField(null=True, blank=False) repository = models.ForeignKey(Repositories, models.CASCADE, db_column='repository') class Raw(models.Model): raw_html = models.TextField() process = models.BooleanField(default=False) identifier = models.ForeignKey(Identifiers, models.DO_NOTHING, db_column='identifier') download = models.ForeignKey(Downloads, models.DO_NOTHING, db_column='download') View def rawPendientes(request): cntxtRaw = {} metaDataPendiente = [] rawPendientes = Raw.objects.filter(process=0) for raw in rawPendientes: # Con la FK se busca la categoria categoria = Downloads.objects.get(id = raw.download.id) # print(categoria.__str__) # Con la FK de la Categoria se busca el Repo repo = Repositories.objects.get(id = categoria.repository.id) totalProcesadoCategoria = Raw.objects.filter(process=1, download= categoria.id).count() totalPendienteCategoria = Raw.objects.filter(process=0, download= categoria.id).count() metaDataPendiente.append((repo, categoria, totalProcesadoCategoria, totalPendienteCategoria)) cntxtRaw = { 'metaDataPendiente': metaDataPendiente, } return render(request, "home_process.html", cntxtRaw) The queries I do with the foreign keys FK in case suddenly there … -
How I can upload file in django, and access to the file content?
I tried this code but it doesn't work, I tried to add files from admin panel it works but when I create a new form it doesn't submitted this is my code, any help: views: class PostCreateView(LoginRequiredMixin, CreateView): model = Post #fields = ['title', 'content', 'XMLcontent'] template_name = 'blog/new_post.html' form_class = PostCreateForm success_url = reverse_lazy('new_post') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() XMLcontent = models.FileField() post_date = models.DateTimeField(default=timezone.now) rate = models.FloatField(null=True, blank=True) post_update = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def display_text_file(self): with open(self.XMLcontent.path) as fp: return fp.read().replace('\n', '<br>') def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', args=[self.pk]) forms: class PostCreateForm(forms.ModelForm): title = forms.CharField(label='title ') content = forms.CharField(label='content ', widget=forms.Textarea) XMLcontent = forms.FileField(label='structured content ') class Meta: model = Post fields = ['title', 'content', 'XMLcontent'] -
Django Delete Function without return but a popup success message
i am trying to have a delete button in the list view that once clicked a popup success message shows and once confirmed the data get deleted and return to the same page. also note that my form and list are in the same page as i am trying to achieve a single page CRUD. appreciate any idea on how to approach this. -
Creating a Register Page by using DJANGO
How can I redirect in such a way that whenever a new USER account is created in my site in "REGISTER" page then after the creation of that account, the account should get logged in simultaneously into my website?? -
Difference on field based on other field value?
So this is my model: class InAndOut(models.Model): quantity = models.FloatField() date= models.DateField(null=True) type = models.CharField(max_length=12) id_product = models.ForeignKey(Products, on_delete=models.CASCADE) I want to query distinct values based on id_product and for each one the difference quantity based on type field("in" or "out"): So a real example would look like: quantity = 1500 type = In id_product = Gas quantity = 300 type = Out id_product = Gas query - Gas 1200 -
Heroku - I deleted migrations in my local enviro, pushed to staging no issues, and then pushed to product and SQL error
I ran into an issue with my migrations in local environment so I deleted migrations in my local enviro and reset database. I pushed these changes to staging on Heroku through git command with no issues my procfile contained the following command release: python manage.py migrate. No issues in staging environment. I then promote to production within Heroku admin portal and run into SQL errors in production environment. My application is built in Django / Python. Any idea how to resolve this conflict - I cannot delete the database as this is a production app? -
Django - Query user groups and load iframe source in a custom template based on user group
I usually develop in PHP but I took it upon myself to learn Django so please be patient with me, I have a long way to go... I am working on a project that simply does one thing for now, user can login and when the user is logged in the app will show an Iframe that streams some digital content that is created by another server I have which is stored in this model: class Show(models.Model): show = models.CharField(max_length = 200) description = models.TextField() mfg_date = models.DateTimeField(auto_now_add = True) iframe = models.CharField(max_length = 300, null=True) group = models.ForeignKey( Group, default='1', on_delete=models.CASCADE,) active = models.CharField(max_length = 1, choices = Active) def __str__(self): return self.show def show_desc(self): return self.description[:50] My views.py currently: from django.shortcuts import render from django.views.generic import TemplateView class StreamingView(TemplateView): template_name = 'stream/stream.html' And my template stream.html: {% extends '_base.html' %} {% load static %} {% block title %}[I would like to print "show" from my model here{% endblock title %} {% block content %} <div class="pricing-header px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center"> <h2>[I would like to print "show" from my model here]</h2> <iframe width="560" height="315" src="[input "iframe" as the iframe src based on user group, and if user … -
How to do location wise product display in Django for eCommerce site
I want to know What is the best way for displaying products location wise in eCommerce website like used in these websites (https://www.walmart.com/) (https://grofers.com/) (https://www.bigbasket.com/) Please share any eCommerce opensource project of Django where this kind of location filtering is done