Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get two distinct objects from the same view function in django according to the requirements?
I have 3 models in Django which are like: class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) class Subcategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True) category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, related_name='products') slug = models.SlugField(max_length=150, unique=True) The view function which I want to modify currently looks like this: def product_list(request, category_name): subcategory = get_object_or_404(Subcategory, slug=category_name) subcategory_name = subcategory.name product_list = subcategory.products.all() context = { 'name':subcategory_name, 'product_list':product_list, } return render(request, 'products/product_list.html', context) In one of my html templates each category is displayed along with the subcategories under it. If anyone clicks on the category name instead of the subcategory under that category name, I want the views function to display all the products which come under that category and not just one subcategory under that given category. I can create a separate view to do that but I want to know if there's a way to do that in the same view function. -
django get model help pls by raxim
I have 3 Profil Stimul_Slov and OTVET model inside Stimulus_words there are questions, the participant must answer questions and questions must be saved on the OTVET model how can I put out Stimulus_words questions and save answers to OTVET models.py from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=100, blank=True) age = models.DateField(blank=True) specialite = models.CharField(max_length=100,blank=True) language = models.CharField(max_length=100,blank=True) def __str__(self): return self.fullname class Stimul_slov(models.Model): stimulus = models.CharField(max_length=200, blank=True) def __str__(self): return "%s" % ( self.stimulus) class Otvet(models.Model): answer = models.CharField(max_length=200, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) stimul = models.ForeignKey(Stimul_slov, on_delete=models.CASCADE) def __str__(self): return "%s: %s ----> %s" % (self.user ,self.stimul, self.answer) -
No ID assigned to objects when created in Django
I have a Class in my models.py named Order class Order(models.Model): customer_name = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer_name', ) order_individual_price = models.IntegerField(default=1) order_name = models.CharField(max_length=200) order_quantity = models.IntegerField(default=1) order_total_price = models.IntegerField(default=1) def __str__(self): return self.order_name In my views.py I create a new instance of order when a button is pressed def ordering(request): latest_order = Order.objects.all() menu = Menu.objects.all() if request.method == 'POST': if request.user.is_authenticated: menu_instance = request.POST.get('add') if menu_instance: get_order = Menu.objects.get(id=menu_instance) get_price = get_order.Menu_price new_order = Order.objects.create(customer_name=request.user, order_name=get_order, order_individual_price=get_price) return redirect('shop-ordering') order_instance = request.POST.get('delete') else: messages.info(request, f'Please Sign In First') return redirect('login') return render(request, 'shop/ordering.html', {'title':'Ordering', 'latest_order': latest_order, 'menu':menu}) However, when I try to get the ID of the object it throws this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/query.py", line 415, in get raise self.model.DoesNotExist( shop.models.Order.DoesNotExist: Order matching query does not exist. I didn't touch any of the init files and since django creates the ID automatically, I'm really confused on why its not assigning each order a ID. -
I want to make multi step form using django form wizard so if anyone has done a project on it please do share
I am doing a project on multi step form in django and i need to make 5 step multi form with different details in it so if anyone has made it do share it with me. Thanks -
Django query based on another query results
I have 4 models in my simplified design class modelA(models.Model): name = models.CharField() class modelsUser(model.Model): username = models.CharField() class bridge(models.Model): user = models.ForeignKey(modelUser, on_delete=models.CASCADE, related_name='bridges') modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='bridges') class subModelA(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelAs') value = models.IntegerField() class subModelB(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelBs') text = models.TextField() What I am trying to to is to get all subModelBs and subModelAs that are for modelAs for which given modelUser have bridge. I've started with this: user = modelUser.objects.get(pk=1) bridges = user.bridges.all() What I've been thinking is something like this: subModelBs = modelB.objects.filter(modelA__in=bridges__modelA) but unfortunately it doesn't work because of error that __modelA is not defined. Is there any proper way to do this? -
How exactly does CASCADE work with ManyToMany Fields in Django
Im Wondering how exactly does CASCADE work with ManyToMany Fields in Django. A short example: class Project(Model): name = TextField(null=False) class Job(Model): projects = ManyToManyField(Project, on_delete=CASCADE, null=False) name = TextField(null=False) As you can see I have a ManyToManyField here. So basically a Project can have mutiple Jobs and a Job can belong to Multiple different Projects. What I want is that a Job is automatically deleted only when all Projects it belongs to are deleted. Does CASCADE work like that in this scenario? -
Can you tell me where is my mistake? I am continuously getting FALSE form.is_valid()
can you look at my code and tell me where is my mistake? I have a form class AddEditTaskForm, which has several fields and it is getting tasks_list in order to get task.list id. forms.py class AddEditTaskForm(ModelForm): def __init__(self,user,*args,**kwargs): super().__init__(*args,**kwargs) task_list=kwargs.get('initial').get('task_list') self.fields['task_list'].value=kwargs['initial']['task_list'].id due_date=forms.DateField(widget=forms.DateInput(attrs={'type':'date'}),required=False) title=forms.CharField(widget=forms.widgets.TextInput()) description=forms.CharField(widget=forms.Textarea(), required=False) completed=forms.BooleanField(required=False) def clean_created_by(self): return self.instance.created_by class Meta: model = Task exclude = [] After rendering a form. I am getting form is not valid error. views.py @login_required def list_detail(request,list_id=None,list_slug=None,view_completed=False): task_list=get_object_or_404(TaskList,id=list_id) tasks=Task.objects.filter(task_list=task_list.id) form=None if view_completed: tasks=task.filter(completed=True) else: tasks=tasks.filter(completed=False) if request.POST.getlist("add_edit_task"): form = AddEditTaskForm(request.user,request.POST,initial={'task_list':task_list}) if form.is_valid(): new_task = form.save(commit=False) new_task.created_by = request.user new_task.description = bleach.clean(form.cleaned_data["description"], strip=True) form.save() messages.success(request, 'New task "{t}" has been added.'.format(t=new_task.title)) return redirect(request.path) else: messages.success(request,'form is not valid') context={ 'list_id': list_id, 'list_slug': list_slug, 'task_list': task_list, 'tasks':tasks, 'form':form, 'view_completed':view_completed, } return render(request,'todo/list_detail.html',context) -
Django: How to fetch data from two models and display it i template?
There are two models Product and ProductImage my code is as follows: models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) models.py from django.db.models.signals import post_save, pre_save from django.dispatch import receiver _UNSAVED_IMAGEFIELD = 'unsaved_imagefield' def upload_path_handler(instance, filename): import os.path fn, ext = os.path.splitext(filename) return "images/{id}/{fname}".format(id=instance.product_id, fname=filename) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) image = models.ImageField(upload_to=upload_path_handler, blank=True) @receiver(pre_save, sender=ProductImage) def skip_saving_file(sender, instance, **kwargs): if not instance.pk and not hasattr(instance, _UNSAVED_IMAGEFIELD): setattr(instance, _UNSAVED_IMAGEFIELD, instance.image) instance.image = None @receiver(post_save, sender=ProductImage) def update_file_url(sender, instance, created, **kwargs): if created and hasattr(instance, _UNSAVED_IMAGEFIELD): instance.image = getattr(instance, _UNSAVED_IMAGEFIELD) instance.save() views.py def products(request): products = Product.objects.all() context = { 'products' : products } return render(request, 'products/products.html', context) products.html {% if products %} {% for product in produucts %} <div class="col-sm-5 col-lg-5"> <div class="equipmentbox"> <div class="equipmentimgbox"> <img src="{{"**IMAGE URL HERE**"}}"> </div> <a href="">{{ product.product_name }}</a> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Products Available</p> </div> {% endif %} Product table contains product details and ProductImage contains images related to particular product. I have a listing page where I wan to display ProductTitle and Image. How can I fetch image from the other table and display it with product title. Thanks in advance. -
Visualize link has been clicked or not
I'm currently working on a web app in which I would like to display to the user whether they have visited the link already or not. The code that displays the links is fairly simple, as seen below. <ul> <li><a href="http://google.com">google</a></li> <li><a href="http://facebook.com">facebook</a></li> <li><a href="http://amazon.com">amazon</a></li> </ul> What I would like is to visualize that a link has been clicked by just adding a checkmark, or something along those lines, to the right of the link. How would I go about doing that? I'm working with Django for this project so a Django-specific solution would be great. -
npx create-react-app command does not work, returns ES module error instead
Here is the command that I ran to try to create a React app and the resulting error log. I have been able to successfully run it three times before with the command $ npx create-react-app, but now every time that I run it, it does not work and instead returns an error related to ES modules. I have been experimenting with many ways to integrate React with Django, but I don't think that I edited any core files in doing so that would have caused this error. I am completely new to React and Node.js so any advice would be greatly appreciated. npx: installed 99 in 7.591s Must use import to load ES Module: /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js require() of ES modules is not supported. require() of /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/run-async/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/package.json.``` -
using form valid method to acess objects from requests made in django
i'm creating a small web application where users can review cars in my web app i made reviews to be relatable objects to cars and as such each review has a car attribute as a ForeignKey. I went on to make a createview for reviews though with a urlpattern containing a car object id . my goal is to find a way of the review form to know which car i am reviewing just like how i used form valid method to enable the form to grab current user making requests to server my models from django.db import models from django.urls import reverse from categories.models import Category # Create your models here. class Car(models.Model): image = models.ImageField(upload_to='images/cars/') make = models.CharField(null=False, blank=False, max_length=30) model = models.CharField(null=False, blank=False, max_length=30) year = models.IntegerField(null=False, blank=False) transmission = models.CharField(null=False, blank=False, max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('car_detail', args=[str(self.id)]) from django.db import models from django.urls import reverse from users.models import CustomUser from cars.models import Car # Create your models here. class Review(models.Model): title = models.CharField(max_length=20) description = models.TextField(max_length=160) date_added = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('review_detail', args=[str(self.id)]) views from … -
Efficient way of avoiding adding duplicate entries to Django model
I've read quite a few posts on how to make a Database/Model unique in Django and it all seems to work. However, I do not see any posts discussing an efficient way of avoiding adding duplicate entries to a database. My model looks like this: # from app.models class TestModel(models.Model): text = models.TextField(unique=True, null=True) fixed_field = models.TextField() The way I currently avoid adding duplicate entries without getting an error is as follows. # from app.views posts = ["one", "two", "three"] fixed_field = "test" for post in posts: try: TestModel(text=post, fixed_field = fixed_field).save() except IntegrityError: pass If I would not do this I would get an IntegrityError. Is there any way I could make this more efficient? -
Parse user input to show as html code. Python + Django
I have Publication class with field for input tags. I capture it with POST method. The problem is that I can not parse it correctly to be able to use those tags as follows {% for item in tags_string %} {{ item.tag }} {% endfor %} How do I format this tags_string so django understands it. I tried to make a QuerySet using next method, and building a list of dictionaries result = [] for a in tags.split(): tag_entry = { 'tag' : a, } result.append(product_entry) As a result I receive a line [{'tag': 'sky', 'tag': 'mountain'}] But my page doesn't show anything using mentioned code block. -
Selenium Webdriver is closing after a while when using Celery
i am new here, im doing an whatsapp bot with django that should be keep running forever to wait for clients chats. The application seems to be running normal when I only use python and run the script. The script starts when I run it by clicking a button on the html form, it gets the interaction preprogrammed from database and start the script to keep waiting new interactions from clients. For this reason, i chose celery to make the script run forever in the backend. The problem is that when sometime pass, it suddenly closes selenium webdriver. PS: i run celery with: celery -A WhatsappBot worker --pool=solo -l info PS2: Im using redis PS3: Im using WINDOWS the logic chain of the app is as follows: 1 - get input from html button. 2 - get interaction information from database. 3 - start a synchronous selenium just to show qr code, when it is scanned, this script ends and it returns the webdriver session and url. 4 - starts the interaction script, connecting remotely to the session got from previous step. after that, when some time pass the celery cmd returns: [2020-04-25 13:47:22,235: WARNING/MainProcess] Retrying (Retry(total=2, connect=None, read=None, redirect=None, … -
How to to access the folder /img in virtual environment with django project?
in virtual environment : virtuelenv, I created a Django project, but when I want to integrate an image in a Template the image doesn't appear. {% extends "base.html" %} {% block title %}Ma page d'accueil{% endblock %} {% block content %} {% load static %} <h2>Bienvenue !</h2> <p> <img src="{% static 'blog/crepes.png' %}" alt="Mon image" /> </p> <a href="/blog/addition/45/52"> Lien vers mon super article N° 42 </a> {% endblock %} please I need your help. Thank you -
Cannot generate django.po files from docker-compose
I'm using Django 3.0.5 inside of a docker-container, linked to an Postgres-container. I would like to generate django.po files but when I'm trying to use this command: docker-compose run web python3 manage.py makemessages -l en I got this error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. Meanwhile, when I directly access to my container, it works: (Here, ad2b13f2fe87 is the ID of my django-container) docker exec -it ad2b13f2fe87 bash root@ad2b13f2fe87:/code# gettext --version gettext (GNU gettext-runtime) 0.19.8.1 ... root@ad2b13f2fe87:/src# python3 manage.py makemessages -l en processing locale en Can someone explain me what the issue is? Thank you. -
Django query for many to many relationship to find a user
this is my model: class Student(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) frist_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) father_name = models.CharField(max_length=250) national_code = models.CharField(max_length=12) date_of_birth = models.DateField() phone_regex = RegexValidator(regex=r'(\+98|0)?9\d{9}', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.",) phone_number = models.CharField(validators=[phone_regex], max_length=13, blank=True,help_text='Do like +98913.......') # validators should be a list CHOICES = ( ('male','Male'), ('female','Female') ) gender = models.CharField(choices=CHOICES,max_length=6) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return (self.frist_name) class Classes(models.Model): book = models.CharField(max_length=250) grade = models.CharField(max_length=250) teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) student = models.ManyToManyField(Student,related_name='student') date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.grade how can i make query to find a user book and grade for a specific student? like : the frist name is mohammad and last name is kavosi and username is 0605605605 i want to find the grade and book of this user is my model True or not? -
Serializers validation - TypeError... 'UniqueTogetherValidator' object is not iterable
I have a model called 'following' where one user can follow another, using the Django rest framework. I am trying to implement a validation so that you can't follow someone twice, and trying the built-in UniqueTogetherValidator. Here are the relevant parts of my models.py class Following(models.Model): user = models.ForeignKey('User', related_name='user', on_delete=models.CASCADE) follower = models.ForeignKey('User', related_name='follower', on_delete=models.CASCADE) And serializers.py: class FollowingSerializer(serializers.HyperlinkedModelSerializer): user = serializers.CharField(source='user.username') follower = serializers.CharField(source='follower.username') class Meta: model = Following fields = ['user', 'follower'] validators = UniqueTogetherValidator( queryset = Following.objects.all(), fields = ['user', 'follower'], message = "You are already following that person!" ) I have some existing data: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 2, "next": null, "previous": null, "results": [ { "user": "mike", "follower": "chelsea" }, { "user": "mike", "follower": "chloe" } ] } When I try to add any new following object using the API interface, I get this error: TypeError at /followings/ 'UniqueTogetherValidator' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/followings/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: 'UniqueTogetherValidator' object is not iterable ... Where did I go wrong? Thanks in advance! -
Filtering in Django ModelViewSet
I don't think I'm doing this correctly. What I'm trying to do is prevent data from being returned if it doesn't match my criteria. Here are the criteria: User should be able to see the project if: If the object is private and they are the owner -- OR -- The project is not private If the user is the owner, or they are a member of the assigned group As far as I can tell, it's not getting the data into the is_private and owner variables I set. Every tutorial I read online though seems to do it in this way. So I'm pretty lost right now. class ProjectListViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by('name') serializer_class = ProjectLightSerializer authentication_classes = [TokenAuthentication, ] permission_classes = [IsAuthenticated, ] def get_queryset(self): queryset = super().get_queryset() is_private = self.request.data.get('is_private') owner = self.request.data.get('owner') print(is_private) print(owner) if is_private: if owner == self.request.user.id: queryset = queryset.filter(owner__exact=self.request.user) else: if owner == self.request.user.id: queryset = queryset.filter(owner__exact=self.request.user) else: queryset = queryset.filter(groups__in=self.request.user.groups.all()) return queryset Any assistance would be greatly appreciated. Thanks in advance. -
How to work with external API from Django admin
I have a problem to solve with Django. I need in some way from the admin area to be able to use an external API to do some HTTP requests, GET and POST. I'm not sure how a good approach would be to solve this. I have only handled this on the frontend before. I should be able to get a list of orders from the API, update an order, get a specific order with details, post a new order etc. I'm thinking such as when you register a model and then registering it with ModelAdmin, would that be possible to use the API to load it in similar way there and handle the API? Should I store the API data in a model to a database? Should I create create a custom made Django admin page? Other ideas? -
Error during template rendering: 'ManyToOneRel' object has no attribute 'attname'
I try to render a form in html but I raise an error and I have got no idea about its trigger. Here is the traceback error: Template error: In template /Users/usr/Projets/your-query-master/src/core/templates/core/base.html, error at line 18 'ManyToOneRel' object has no attribute 'attname' 8 : 9 : <title>{% block title %} Your-Query {% endblock title %}</title> 10 : <!-- Latest compiled and minified CSS --> 11 : <link rel="stylesheet" href='{% static "css/base.css" %}'> 12 : <link rel="stylesheet" href='{% static "css/bootstrap.min.css" %}'> 13 : <link rel="stylesheet" href='{% static "css/bootstrap-theme.min.css" %}'> 14 : <link rel="stylesheet" href='{% static "css/contest.css" %}'> 15 : 16 : <script src="{% static 'contest_bet.js' %}"></script> 17 : 18 : <link rel="styleshee t" href="htt ps://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 19 : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> 20 : </head> 21 : <body> 22 : {% include "core/navbar.html" %} 23 : <div class="container" style="padding-top: 80px;" > 24 : {% block content %} 25 : 26 : {% endblock content %} 27 : </div> 28 : {% include "core/footer.html" %} Traceback (most recent call last): File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/usr/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
Djoser return access and refresh token when registering user
I am trying to get access and refresh tokens when the user registers using the /auth/users/ endpoint. I have already extended the serializer and it is showing all custom fields. It registers the user successfully and returns the result as follows: { "mobile": "12345", "driving_id": "478161839", "full_name": "John Doe", } This is where I would want to have an access and refresh token. I read that djoser uses django simple jwt library to provide access and refresh tokens. This is the function to create the tokens manually which I am able to do but the only thing I am not understanding is where to return the data with other details. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } -
Cannot query "": Must be "" instance
I am pretty new to django as well as python, in my app i have two models one is MyProfile and One is MyPost, users will have a profile and users can create a post, it's all working but i wanted to show posts created by a user in their profiles. for that i tried creating a get_context_data inside my generic Detailview. But it gives me this error Cannot query "ahmy": Must be "MyProfile" instance. ahmy is my logged in username. My models from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.core.validators import MinValueValidator, RegexValidator # Create your models here. class MyProfile(models.Model): name = models.CharField(max_length = 500) user = models.OneToOneField(to=User, on_delete=CASCADE) address = models.TextField(null=True, blank=True) gender = models.CharField(max_length=20, default="Male", choices=(("Male", 'Male'), ("Female", "Female"), ("LGBTQ", "LGBTQ"))) phone_no = models.CharField(validators=[RegexValidator("^0?[5-9]{1}\d{9}$")], max_length=15, null=True, blank=True) description = models.CharField(max_length = 240, null=True, blank=True) pic = models.ImageField(upload_to = "image\\", null=True) def __str__(self): return "%s" % self.user class MyPost(models.Model): main_pic = models.ImageField(upload_to = "image\\", null=True) amount_spend = models.IntegerField(null=True, blank=True) total_donars = models.IntegerField(null=True, blank=True) title = models.CharField(max_length = 200) body = models.TextField(null=False, blank=False) cr_date = models.DateTimeField(auto_now_add=True) uploaded_by = models.ForeignKey(to=MyProfile, on_delete=CASCADE, null=True, blank=True) def __str__(self): return "%s" % self.title My View @method_decorator(login_required, name="dispatch") class … -
How to insert a django user's username in the path via a view?
I am a naive Django user. I have implemented a sign-in functionality with the Django user model. Here's my project's urls.py file: from django.contrib import admin from django.urls import path,include from django.conf.urls import url from signin import views as viewsignin urlpatterns = [ path('',include('signin.urls')), path('dashboard/',include('dashboard.urls')), path('admin/', admin.site.urls), ] Here's my dashboard app's urls.py, which gives a path to the dashboard view once a user logs in. from django.urls import path from . import views urlpatterns = [ path('dashboard/',views.dashboard,name='dashboard'), ] Here's a snippet of views.py of my signin app: def signin(request): message={} if request.method=='POST': user =authenticate(username=request.POST['email'],password=request.POST['pwd']) print(user,request.POST['email'],request.POST['pwd']) if user: print("User exists") if user.is_active: login(request, user) USER = User.objects.get(email=request.POST['email']) return redirect('dashboard)#I HAVE A PROBLEM HERE else: message['cred_err']=True return render(request,'signin/signin.html',context=message) What I want is that when signing in is successful, the path of dashboard shows the username of the user who logged in. Please help! -
Amazon SNS topic,subscription and geo-localized push notifications management for mobile devices
I have one Django application with some REST-services. I store mobile devices geo-location and I have to send a push notification (the same push notification) to all devices that they are into a specific location (with a certain radius). I'm using AWS-SNS service and I already registered the mobile on SNS. I would like to not use some asynchronous architectures (for example Celery) to retrieve all devices, that they are into the location to send, for each of these, the push notification (one request to SNS for each device). For example, I'm searching for a way to register all retrieved devices on a topic-subscription in bulk and, after this, on request to send the push notification to all devices that they are registered to this topic. My goal (best case) can be: Retrieve all devices by geo-location; Create an SNS topic dedicated for this request; One request to store in bulk these devices for this topic; One request to send the push notification for this topic; This is a possible approach for example. I would like to reduce the request to SNS and I would like to not use (for example) Celery to create different async steps for this. Is …