Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing context to serializer from Viewset
I have Viewset with get_serializer_context method class UserRetrieveView(generics.RetrieveAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = UserProfilePageSerializer def get_serializer_context(self): context = super(UserRetrieveView, self).get_serializer_context() context.update({'room' : self.get_object().room_set.all()}) print(context['room']) return context And now I want to put this context to my serializer : class UserProfilePageSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'name','bio'] Honestly I have no idea how to do this. I would really appreciate any help or even some clue -
Django passing data through the url, not finding page in url patterns
I'm trying to pass an object's id through the url, but its not able to find the page even after it tries the path when it goes through its patterns Error: Using the URLconf defined in GroomingService.urls, Django tried these URL patterns, in this order: admin/ [name='Home'] appointment-Maker/ account/ admin-home view_appointment/<id>/ login/ [name='Login Page'] registration/ [name='Registration Page'] logout [name='Logout Page'] The current path, adminview_appointment/21/, didn’t match any of these. GroomingService.urls #urls urlpatterns = [ path('admin/', admin.site.urls), path('', Home_view, name="Home"), path('appointment-Maker/', include('appointmentApp.urls')), path('account/', include('accountApp.urls')), path('admin-home', include('adminApp.urls')), path('view_appointment/<id>/', viewAppointment_view), #this is the page it is not finding path('login/', Login_view, name='Login Page'), path('registration/', Registration_view, name='Registration Page'), path('logout', Logout_view, name='Logout Page') ] adminApp/views.py viewAppointment_view def viewAppointment_view(request, id): appointments = Appointment.objects.get(id = id) context = { 'appointments' : appointments } return render(request, "admin_templates/viewappointment.html", context) templates/admin_templates viewappointment.html {% extends 'base.html' %} {% block content %} <a>appointment view</a> {% endblock %} templates/admin_templates adminhome.html (the link is clicked through this page) {% extends 'base.html' %} {% block content %} <a>this is the admin page</a> <br> {% for a in appointments %} <a href="adminview_appointment/{{a.id}}/">Client name:{{a.client_dog_name}}</a><br> {% comment %} this is the link that is clicked {% endcomment %} {% endfor %} <br> <a>find month</a> <form method="POST"> {% csrf_token %} … -
How to iterate through queryset and get value Django
I wanna do a simple recommendation system based on users' Animals that they added. I want to show only products of a category, that's been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset? class MyAnimal(models.Model): name = models.CharField(max_length=256) animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) class Product(models.Model): product_category = models.ManyToManyField(EcommerceProductCategory) def list(self, request): zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3} qs = MyAnimal.objects.filter(user=self.request.user) #checking if there is an animal with user == self.request.user if qs: if len(qs)==1: # if user has only 1 animal, get that animals race and if compare it with the dictionary to get product__product_category … -
heroku error - template does not exist at / web/index.html
i have been stumped for days, trying to figure this out. Ive looked at every stack overflow post relating to this and now I'm resorting to making my own. all the other posts say the error has something to do with the settings.py file so here it is: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent.parent ALLOWED_HOSTS = [ '127.0.0.1', 'd1sbot.herokuapp.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'botfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'botfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ os.path.join(os.path.dirname(__file__) ,'../templates').replace('\\','/') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) # … -
How to get data from django orm inside an asynchronous function?
I need to retrieve data from the database inside an asynchronous function. If I retrieve only one object by executing e.g: users = await sync_to_async(Creators.objects.first)() everything works as it should. But if the response contains multiple objects, I get an error. @sync_to_async def get_creators(): return Creators.objects.all() async def CreateBotAll(): users = await get_creators() for user in users: print(user) Tracing: Traceback (most recent call last): File "/home/django/django_venv/lib/python3.8/site- packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/django/django_venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/django_venv/src/reseller/views.py", line 29, in test asyncio.run(TgAssistant.CreateBotAll()) File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/django/django_venv/src/reseller/TgAssistant.py", line 84, in CreateBotAll for user in users: File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/django/django_venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql cursor = self.connection.cursor() File "/home/django/django_venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 31, in inner raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. -
django show last 3 char of string in admin fields
database | id | salary_number | | --- | ------------- | | 1 | 1042 | models.py class user(AbstractUser): salary_number = models.CharField(max_length=4, unique=True, null=True, blank=True) def __str__(self): return f'{self.salary_number[-3:]}' admin.py class UserAdmin(admin.ModelAdmin): fields = ('salary_number[-3:]',) I would like to show Salary number: 042 in admin fields instead of 1042. Is it possible? -
creating/deleting folders in runtime using heroku/django
I have developed a Django app where I am uploading a file, doing some processing using a project folder name media. Process: user uploads a csv file, python code treats the csv data by creating temp folders in Media folder. After processing is complete, these temp folders are deleted and processed data is downloaded through browser. I am using the below lines of code to make and delete temp file after processing temp = 'media/temp3' os.mkdir(temp) shutil.copyfile('media/' + file_name, temp + '/' + file_name) shutil.rmtree(temp, ignore_errors=True) To set the media root, I used the below lines in settings.py which I am sure I am not using in other parts of the code. MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = "/media/" Everything works fine when I run the app on local host. but as soon as i deployed it to heroku, it seems like these folders were not created/not found. I am looking for: Either a solution to create, read and delete folders/files in runtime using heroku, or a better way to manage files/folders in runtime. -
How to add a searchable text field to select a foreign key item in Django form?
I have a filter form as you can see in the screenshot. I would like to add a searchable field(in the red area) so users can filter the campaign naming tool object instead of scrolling. Any help is appreciated. My filter class class UserInsertionOrderFilter(django_filters.FilterSet): start_date = django_filters.DateFilter(widget=DateInput) end_date = django_filters.DateFilter(widget=DateInput) class Meta: model = UserInsertionOrder fields = [ 'campaign_naming_tool', 'start_date', 'end_date' ] My filter form -
Django request for CAC (common access card)
I am currently running my Django application on an Apache v2.4.5.2 server. When the user hits initial page (i.e. www.djangoApp.com) they are prompted to insert their CAC and PIN. Once complete, the PIN entry pop-up goes away and the user is directed to the landing page. The issue I'm having is figuring out how to identify the user based on the HTTP response received from the external source (GCDS). In the server logs, I can see the request information, but I am unsure how to view that request in Django views. I tried to comment out all middleware so that the request would make it through, but that doesn't work. Does Apache block certain HTTP Requests? Is there somewhere I need to allow external requests? The only request I'm getting is: {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REQUEST_METHOD': 'GET', 'QUERY_STRING': '', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'PATH_INFO': '/', 'PATH_TRANSLATED': '\DjangoWebProject1\\wsgi.py\\', 'HTTP_HOST': 'glen', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"', 'HTTP_SEC_CH_UA_MOBILE': '?0', 'HTTP_SEC_CH_UA_PLATFORM': '"Windows"', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'HTTP_SEC_FETCH_SITE': 'none', 'HTTP_SEC_FETCH_MODE': 'navigate', 'HTTP_SEC_FETCH_USER': '?1', 'HTTP_SEC_FETCH_DEST': 'document', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.9', 'HTTP_COOKIE': 'csrftoken=Nd3ggEPk0vqYJwZKOVZZoZtUqZWXs155Y6V1q', 'HTTP_X_FORWARDED_FOR': '128.202.106.24', 'HTTP_X_FORWARDED_HOST': 'glen', 'HTTP_X_FORWARDED_SERVER': … -
Django kubernetes error error converting YAML to JSON: yaml: line 11: mapping values are not allowed in this context
im using Django and kubernetes to create a website and when i run helm upgrade --install --dry-run --debug django-test ./helm/django-website there seems to be a problem with deploypment.yaml but i cant seem to find the issue ive tried multiple methods from forms and used yaml checkers but i cannot fix it i dont know why it has a problem to begin with because the program generated it all i added was command: ["make", "start-server"] on line 36 here is the code for deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "django-website.fullname" . }} labels: {{ include "django-website.labels" . | nindent 4 }} spec: {{ if not .Values.autoscaling.enabled }} replicas: {{ .Values.replicaCount }} {{- end }} selector: matchLabels: {{- include "django-website.selectorLabels" . | nindent 6 }} template: metadata: {{- with .Values.podAnnotations }} annotations: {{- toYaml . | nindent 8 }} {{- end }} labels: {{- include "django-website.selectorLabels" . | nindent 8 }} spec: {{- with .Values.imagePullSecrets }} imagePullSecrets: {{- toYaml . | nindent 8 }} {{- end }} serviceAccountName: {{ include "django-website.serviceAccountName" . }} securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }} containers: - name: {{ .Chart.Name }} securityContext: {{- toYaml .Values.securityContext | nindent 12 }} image: "{{ .Values.image.repository }}:{{ … -
How to call function from views.py to models.py?
Problem I'm new in Django, I have a function to retrieve foreign key object in views.py and I want to call this function to models.py, is there any way to do this? views.py def get_fk(request): if request.method == 'POST': category = itemCategory.objects.get(pk=request.POST.get('idItemCat')) return category models.py class MyUser(AbstractUser): pass class ItemCategory(models.Model): idItemCat = models.CharField(primary_key=True max_length=5) nameCategory = models.CharField(max_length=150) class ItemCode(models.Model): idItemCode = models.CharField(primary_key=True, editable=False, max_length=20) idItemCat = models.ForeignKey(ItemCategory, on_delete=models.DO_NOTHING) What I've tried To import a function usually in django like this from .views import get_fk, but every time I did that it doesn't work and getting this error, it said that my custom user has not been installed. Traceback (most recent call last): File "D:\VS_Code\.venv\lib\site-packages\django\contrib\auth\__init__.py", line 160, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "D:\VS_Code\.venv\lib\site-packages\django\apps\registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "D:\VS_Code\.venv\lib\site-packages\django\apps\config.py", line 270, in get_model raise LookupError( LookupError: App 'aset_app' doesn't have a 'MyUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Zeidan\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\VS_Code\.venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\VS_Code\.venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\VS_Code\.venv\lib\site-packages\django\core\management\__init__.py", … -
Django - (admin.E015) The value of 'exclude' contains duplicate field(s)
I have the following Models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') These are registered to django-admin as follows: @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): list_display = ['identifier', 'name'] @admin.register(Step) class StepAdmin(admin.ModelAdmin): list_display = ['start_time', 'time', 'schedule'] exclude = list('schedule') However when running the server I get the following error: ERRORS: <class 'manager.admin.StepAdmin'>: (admin.E015) The value of 'exclude' contains duplicate field(s). How can I resolve this issue? I am unfamiliar with how Two way binding in Django is supposed to work? -
How to map out With python Django Management CMD [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. -
Getting Realtime data and parsing it locally in Django Rest Framework
I want to build a Django REST API that gets crypto pricing data from Coin Market Cap and shows it on GET localhost according to my own parameters. There are a few questions, however, Coin market cap uses API auth keys, where does it go? Where do I put it? In What headers? Do I really need models if I am getting a predefined URL that already displays what I want? -
getting "This field is required" message. while uploading image
i don't have any problem in submiting char fields but when i put an image field i get this message -> "This field is required" while im filling the form . models.py : class Home(models.Model): image = models.ImageField(upload_to='image') titr = models.CharField(max_length=200) description = models.TextField() created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) class Meta: ordering = ['created'] def __str__(self): return str(self.titr) views.py : def craethome(request): form = HomeForm() if request.method == "POST": form = HomeForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect("home") return render(request, 'home/home_form.html', {"form":form}) forms.py : from django.forms import ModelForm from .models import Home class HomeForm(ModelForm): class Meta(): model = Home fields = "__all__" my html file: {% extends 'main.html' %} {% block content %} <img src="{{home.image.url}}"> <h1>{{home.titr}}</h1> <p>{{home.description}}</p> {% endblock content %} -
Why does HTML/Django template execute code out of order?
This html template from my online class executes as intended, but why? It seems like it is executing out of order: It calls my python form class using Django's syntax {{form}} to inject the blank fields for the user to fill out (name, email, textbox) The user can enter and hit the "Submit" button but then (confusingly) is that it seems the {{form}} class is called again with the entry information as it then successfully prints out user input to the terminal. Why is this? html in templates.py <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <h1>fill out the form</h1> <div class="container"> <form method="POST"> {{form}} {% csrf_token %} <input type="submit" class="btn btn-primary" value="submitme"> </form> </div> </body> </html> Form class in views.py def form_name_view(request): form = forms.FormName() if request.method == "POST": form = forms.FormName(request.POST) if form.is_valid(): print("VALIDATION SUCCESS") print("NAME: " + form.cleaned_data['name']) print("EMAIL: " + form.cleaned_data['email']) print("TEXT: " + form.cleaned_data['text']) return render(request, 'first_app/form_page.html', {'form' : form}) Supplemental: the url that uses the html template and my forms class from django.urls import path from first_app import views urlpatterns = [path('formpg', views.form_name_view, name = 'formpg')] -
How to change CSV value into a DateTime object
I am trying to upload data from a CSV into a Django model. On the CSV there is a date field and the values look like this: 2020-11-11 14:06:25+00:00 Which brings up this error: '“Deadline” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.' I am saving the value into a DateTimeField. How would I convert the CSV data into a DateTime object? I appreciate your help on this. Thanks! -
Google Cloud Run correctly running continuous deployment to github, but not updating when deployed
I've set up a Google Cloud Run with continuous deployment to a github, and it redeploys every time there's a push to the main (what I what), but when I go to check the site, it hasn't updated the HTML I've been testing with. I've tested it on my local machine, and it's updating the code when I run the Django server, so I'm guessing it's something with my cloudbuild.yml? There was another post I tried to mimic, but it didn't take. Any advice would be very helpful! Thank you! cloudbuild.yml: steps: # Build the container image - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/${PROJECT_ID}/exeplore:$SHORT_SHA', './ExePlore'] # Push the image to Container Registry - name: 'gcr.io/cloud-builders/docker' args: ['push', 'gcr.io/${PROJECT_ID}/exeplore'] # Deploy image to Cloud Run - name: 'gcr.io/cloud-builders/gcloud' args: - 'run' - 'deploy' - 'exeplore' - '--image' - 'gcr.io/${PROJECT_ID}/exeplore' - '--region' - 'europe-west2' - '--platform' - 'managed' # Deploy container image to Cloud Run - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk' entrypoint: gcloud args: ['run', 'deploy', 'exeplore', '--image', 'gcr.io/${PROJECT_ID}/exeplore', '--region', 'europe-west2', '--platform', 'managed'] images: - gcr.io/${PROJECT_ID}/exeplore Here are the variables for GCR -
How to map out via Django Management command [duplicate]
The is active flag and blacklist flag have the same intention although both are available. Since with is active filtering is possible and it is seen in the overview all blacklist should be mapped to is active. def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True) -
Annotate dict data from related field Django
I have a model MyModel that contains a JSONField named calculo in MySQL and I want to annotate the value of premio to perform aggregated sum. How can I make this work? class MyModel(models.Model): ... calculo = JSONField(blank=True, null=True) ... I have tried this but got an empty dict. qs = MyModel.annotate(value=F('calculo__premio')) Fairfax field: '{"sc_ha": 2.77, "premio": 27735.84, "status": "1"}' -
Page not re-rendering when receiving post request from jquery to django backend
Jquery on HTML page in script tags $("input[type='radio']").click(function(){ var radioValue = $("input[name='filter']:checked").val(); if(radioValue){ var CSRFtoken = $('input[name=csrfmiddlewaretoken]').val(); jQuery.post("/", {filter:radioValue, csrfmiddlewaretoken: CSRFtoken }); } }); }); django view (python) def homepage(request): context = {} if request.POST: filter = request.POST.get('filter') filteredarticles = list(Article.objects.all().filter(is_draft = False, topic =filter)) context['features'] = filteredarticles print(filteredarticles) return render(request, 'homepage.html', context=context) else: allarticles = list(Article.objects.all().filter(is_draft=False)) FEATUREDQUANTITY = 7 featuredArticles = [] for i in range(FEATUREDQUANTITY): k = random.randint(0, (len(allarticles)-1)) featuredArticles.append(allarticles[k]) allarticles.pop(k) context['features'] = featuredArticles print('seen') return render(request, 'homepage.html', context=context) The thought process is as follows: Using radio buttons in HTML. Jquery listening for click actions. Sends post request to view function containing the selected radio {name:value} and the CSRF_token information. The view receives the post request and processes it through the If condition and re-renders the page with the appropriate data. Everything is working, the post request is received, the data inside filteredarticles is changing, but the website itself isn't re rendering with the new context values I am passing in. Any help would be appreicated edit: Is it because I'm not passing a success callback function in my jquery.post? -
Django - Restrict API access by geolocation
We have model and view: from django.db import models from rest_framework.decorators import api_view from rest_framework.response import Response class Store(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=100) @api_view(['get']) def get_checklist_by_store_id(request, store_id): # request.user should has access to this view only when request.user inside the store with id=store_id return Response() User can get checklist by store_id. And we need to restrict access to view get_checklist_by_store_id and allow user to have access only when user is inside the store with id=store_id. First what I thought about was to add to model Store field with geo coordinates. Then on frontend implement geolocation API. When user is trying to get access to the view to ask him turn on geolocation and at last send request with his geo coordinates. And in the view compare user's geo coordinates and store geo coordinates (with some distance error). Maybe there is another approach to solve this kind of problem? -
FullCalendar not displaying correctly in django
current Fullcalendar display Hey so I'm working with FullCalendar and I'm trying to display the calendar but it ends up displaying the way it is in the picture attached to this post. I'm not sure why it displays like this and I followed the instructions on their scripts tag page but no luck. Does anyone know why and how to fix this issue? Here's the code I'm using for this {% extends 'apisapp/base.html' %} {% load static %} {% block content %} {% block extra_css %} <style> .btn-success { background-color:#7AAF4F; } .btn { font-weight: bold; } </style> </link rel="stylesheet" href="{% static 'fullcalendar/lib/main.css' %}"> {% endblock extra_css%} <body style="background-color: #2B2B2B; color: white;"> <div class="card" style="background-color: #2B2B2B; color: white;"> <div id="calendar" class="container" ></div> </div> </body> {% block extrajs %} <script src="{% static 'fullcalendar/lib/main.js' %}"></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarUI = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarUI, { }); calendar.render(); }); </script> {% endblock extrajs%} {% endblock %} -
4 by 4 square grid for 52 random images using Django
I want to create a 4 by 4 grid of about 52 images that can randomly appear in each square of the grid. I am trying to use Django since its what im into right, but if Javascript is better than I can use it. Any suggestions to get started on this project is what i am looking for -
show products in a specific category in html
i have a products and categories Model already implemented in models.py in a django application. In an html template i want to show products of a single category that i want to define in html, like category == example or something similar. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE) title = models.CharField(max_length=255) this is the models.py snippet, below is the html snippet that i am trying to use {% for product in category.products.all %} I am already using this snippet to show products on category page, the category is going to be defined using the category url, but in this case i want to do that.