Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template > checking condition on button click
On my template i have a button to collect fee that takes the user to next screen. However, i want a check on this button's click event if the fee is already paid-in-full and prompts the user via message on screen. In related model i have method that checks if fee is paid in full. I had added the condition on template like this and it disabled the button <td><a href="{% url 'add_fee' student.id %}" class="btn btn-secondary btn-sm {% if student.get_remaining_fee == 0 %}disabled {% endif %}">Add Fee</a></td> but this increases the number of queries as i have a many students records on current view. In general if i want such validations before user can go to new/assigned view, what would be the best practice. -
How to Optimize Data Importing to a Django Model using django-import-export library
I have been using django-import-export library to upload my data as excel to the Django model and it has been working fine till i had to Upload an excel with 20,000 rows and it just took infinite time to get this action done. Can you please suggest the right way to optimize data Uploading to the Django model, where i can easily upload excel files and have that data saved in my Database. Please support. -
Images not Loading after Changing database from Sqlite3 to Postgres
I am working on a Django based application which has many applications in it I just thought of switching the database because there are any great software available for rescue light and also the DB browser software is really early and very less of features and is not user friendly so I thought of using postgres as it is one of the most highest rated so when I change the database everything works fine but the thing happened that most of my images didn't load some of them loaded but most of the images didn't load so please tell me what changes should I make to do to make all the images load as well as what has happened actually because all the code is working fine the the landing pages and the login and logout system but many of the images are not loading please tell me what should I do for what changes have to make in the code or if I have made any mistake -
Django Email Service
I want to send an activation Email your account is successfully created This is my views.py class UserAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin): permission_classes = [permissions.AllowAny] serializer_class = UserSerializer queryset = User.objects.all() lookup_field = 'id' filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['email', 'first_name', 'last_name', 'roles', 'id', 'contact', 'profile'] search_fields = ['email'] ordering_fields = ['first_name'] def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) # return Response("Required Id") def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) This is settings.py STATIC_URL = '/static/' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '#####@gmail.com' EMAIL_HOST_PASSWORD = '##########' Please mention where to add the email thing. -
I can get user details but I can't work out how to change them?
So, I can get data and it all works but I can't seem to work out how to update it without updating everything, just what the user wants to update, I came up with this 'update' method below but I can't seem to get it to work. Any help would be greatly appreciated. Thanks, George. views.py class UserDetailsAPIView(CreateAPIView): serializer_class = UserDetailSerializer queryset = User.objects.all() permission_classes = (IsAuthenticated,) def get(self, request): serializer = UserDetailSerializer(request.user) return Response(serializer.data) def update(self, validated_data): email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] phone_number = validated_data['phone_number'] password = validated_data['password'] user_obj = User( email=email, first_name=first_name, last_name=last_name, phone_number=phone_number ) user_obj.set_password(password) user_obj.save() return validated_data serializers.py class UserDetailSerializer(ModelSerializer): class Meta: model = User fields = [ 'first_name', 'last_name', 'email', 'phone_number', 'is_active', 'email_confirmed', 'phone_number_confirmed', 'date_joined', 'last_login', 'nick_name', 'id' ] -
In Django 3, how do I build an AND query based on an array of conditions?
I'm using Python 3.8 and Django 3. I have the following model ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_phone') email = models.ForeignKey(ContactMethod, on_delete=models.CASCADE, null=True, related_name='contact_email') web_site = models.TextField() I want to build an advanced search where I can search for one or multiple attributes, based on whether they are supplied. I have class CoopManager(models.Manager): def find(self, name, type, enabled): if name: qset = Coop.objects.filter(name=name) if type: qset = Coop.objects.filter(type__name=type) if enabled: qset = Coop.objects.filter(enabled=enabled) return qset but the above is flawed because it will only search on one attribute. How do I create an array of conditions and pass them to my query? For example, if "enabled" and "name" are supplied, then the query should only search by those two things. If "type" and "name" are supplied, ti should only search by those two things. -
Django AttributeError: 'str' object has no attribute 'pk'?
I have this error in my django project where I'm trying to connect django User model and a custom Profile model with a one to one relationship. Any help would be great and highly appreciated. Thank you! Here I have even tried WritableNestedModelSerializer, but that doesn't work either! Here is my code. Serializer class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'owner', 'title', 'body'] class ProfileSerializer(WritableNestedModelSerializer): class Meta: model = Profile fields = ['user', 'aboutMe', 'lastAccessDate'] class UserSerializer(WritableNestedModelSerializer): profile = ProfileSerializer('profile') class Meta: model = User fields = ['pk', 'username', 'first_name', 'last_name', 'email', 'profile'] def update(self, instance, validated_data): profile_data = validated_data.pop('profile') # Unless the application properly enforces that this field is # always set, the following could raise a `DoesNotExist`, which # would need to be handled. profile = instance.profile instance.pk = validated_data.get('pk', instance.pk) instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.save() profile.save() return instance Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) aboutMe = models.TextField(max_length=500, blank=True) lastAccessDate = models.DateTimeField() @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) else: instance.profile.save() I just want to update profile deails and here is my UserUpdateView, class UserUpdateView(UpdateAPIView): #authentication_classes = … -
django not recognized as internal or external command
Though I have installed django, when I run django -admin startproject projectfirst, it is showing django is not recognised as internal or external command. -
Delete from one to many field django
I am trying to do a delete request in Django from many to one field. I am trying to get the user id and delete a particular task assigned under it with foreign key. Here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Favourites(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) favourites = models.CharField(max_length=30, null =True) def __str__(self): return self.favourites Here is my views: @csrf_exempt def delete(requests): if requests.method == 'POST': username = requests.POST['uname'] fav = requests.POST['fav'] remove = Favorites.objects.filter(favourites=fav).delete() print(remove) print(all_favourites) return JsonResponse({"message": "done"}) I am new to django please help. -
Django field level permission in the admin
I have a Django project that is required to use field level permissions. Let's say I have model called books. The books model has 2 fields, title and content. I also have 2 groups of users. Group1 has the permission to only view the title field in my book model and Group2 can only view the content field in my book model. If userA is in Group1 and has the status of staff, is their a way to only show the title field when userA logs into the admin panel. I'd prefer an implementation that does not involve adding additional apps to my project. Thanks in advance. -
Running Django with Pyto on iPad
I am trying to build my first Webb app using Django. I’m using my iPad because I am on the move a lot. Anyways, I’m trying to follow Django’s instructions for building a poll application. I got the server running but when i made the changes that should have printed the Hello World but its now its giving me a ModuleNotFoundError. I’ve tried copy and pasting the lines of code from Django’s website and I’ve tried to type it in on my own. ModuleNotFoundError: No module named 'WellnessApp' import os `import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WellnessProject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) #if __name__ == '__main__': # main() if __name__ == '__main__': import background as bg with bg.BackgroundTask() as b: main()` -
Get keys and values of JSONField
I want to pass keys and values of my list of dicts from JSONField to XHR as JSON. The content of JSONField looks like: [{'q1':'12'},{'q2':'22'},{'q3':'11'}] And I want to pass them as same as list above. models.py: class User1(models.Model): history = models.JSONField(blank=True, null=True) class UserForm(ModelForm): class Meta: model = User1 fields = '__all__' views.py: class ArticleUpdateView(UpdateView): model = User1 template_name = None ... def get(self, request, *args, **kwargs): if request.headers.get('x-requested-with') == 'XMLHttpRequest': if request.headers.get('Get-History') == 'History': form = UserForm(request.POST or None) self.object = self.get_object() data = { 'history': str(form.fields['history']) } return JsonResponse(data, safe=False) Result: {"history": "<django.forms.fields.JSONField object at 0x109d03080>"} -
Django " AttributeError: 'function' object has no attribute 'as_view' "
I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error. Here is the error ; Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\berat.berkol\anaconda3\lib\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 … -
How to bind a comment form to one pot without a choice (Django)
When writing a comment under the article, it becomes possible to choose which post to bring the comment to. How to make comments automatically attach to the post under which it is written. **views.py** class AddCommentView(CreateView): model = Comment template_name = 'main/post_detail.html' form_class = CommentForm #fields = '__all__' success_url = reverse_lazy('barbers') **models.py** class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30, null=True, blank=True) description = models.TextField() def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) **forms.py** class CommentForm(ModelForm): class Meta: model = Comment fields = ( 'post', 'name', 'body') -
The way I added comments in my blog is a good programming practice?
I wanted to add comments functionality in my blog, but I also wanted to keep the ability for non logged users to add a comment. So there had to be an input for their name, which for the logged users would be useless. What I did was firstly in the Comment model to declare a 'name' as a CharField for both logged and non logged users, and then a 'auth_user' ForeignKey that was pointing to the User class, but with the parameters blank=True and null=True. The first field is filled through the form. For the non logged users with the obvious way, and for the logged users as an initial value, before the input was hidden. However for the second field, which has to be filled only when the comment was added by a logged user, I was planning to pass user to the model.py and there to have a save() method. However I didn't make it to pass the request.user to the models.py. Then I wanted to use in the views.py a self.model.objects.latest('auth_user') and a save() methods within the form_valid() method of my CommentCreateView, but I didn't make it to stracture it in a way that the save() would … -
Django Static file not loading ImageField URL
This is for an assignment, we need to store the images in the static directory and display them on a template. The images are stored through the item model ImageField and uploaded to the static/images directory. Here is the template code: {% load static %} <p><a href='..'>Home</a></p> {% block content %} <table> <tr> <th>Item Name</th> <th>Manufacturer</th> <th>Cost</th> <th>Weight</th> <th>Image</th> </tr> {% for i in name %} {% if i.name == params %} <tr> <td>{{i.name}}</td> <td>{{i.manufacturer}}</td> <td>{{i.cost}}</td> <td>{{i.weight}}</td> <td><img src="{% static i.image.url %}" alt="{{i.image.url}}"></img></td> </tr> {% endif %} {% endfor %} </table> {% endblock %} I have the following model code: from django.db import models class item(models.Model): name = models.CharField(max_length=40) manufacturer = models.CharField(max_length=255) cost = models.DecimalField(max_digits=10, decimal_places=2) weight = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='static/images/') Here are the current settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'Nice try' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite', ] … -
My comments aren't displaying on the HTML page
Hey guys I'm building an auction site and for some reason my comments (a dict called commentQuery) is not displaying on the HTML page. Anyone see why? I'm sure it's something minor I'm missing. Thanks! relevant code below: views.py: def comment(request): username = request.POST.get("username") itemID = request.POST.get("itemID") comment = request.POST.get("comment") new = Comment.objects.create(username = username, comment = comment, itemID = itemID) new.save() commentQuery = Comment.objects.all() return render(request, "auctions/post.html", { "commentQuery": commentQueries}) post.html: <form name="comment" action="/comment" method="post"> {% csrf_token %} <h2>Comments</h2> {% if user.is_authenticated %} <input autofocus class="form-control" type="text" name="comment" placeholder="Enter Comment"> <input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}> <input autofocus class="form-control" type="hidden" name="username" value={{user.username}}> <input class="btn btn-primary" type="submit" value="Add Comment"> {% endif %} </form> {% for commentQuery in commentQueries %} <li>{{ commentQuery.comment }} by {{ commentQueries.username }}</li> {% endfor %} {% endblock %} -
append dict to list without duplicate python django
i have this object data_listmedia print(data_listmedia) : [{'id': 6, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 30, 'date': datetime.date(2020, 9, 25)}, {'id': 7, 'withdegrey_id': 2, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 200, 'date': datetime.date(2020, 9, 25)}, {'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}] so now i want append this persontage dict to all dicts in this list so i use this loop : first i declared mydict ={} data = [] for l in data_listmedia: persontage = ((l["nomberhodor"] * 100) / l["nomberesteda"]) mydict.update({"percontage": persontage}) data.append(mydict) mydict.update(l) but when finsh the loop its apeend thelast dict in list print(data) = [{'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}] why when use data.append(mydict) its duplicate the last dict in the all list but when i use print(persontage) inside the loop the value come true 7.5 50.0 60.0 how i can append dict to list without duplicate -
how to list employee under loggedin manager in Django
i wanted to list employee under manager(only for manager who login) https://github.com/dineshdk13/Employeesite.git -
How do I make a custom form errors section in my Django template?
In my Django template I can show errors using this syntax {{ form.errors }}. But that evaluates to this html syntax in my template: <ul class="errorlist"> <li>password <ul class="errorlist"> <li>Ensure this value has at least 10 characters (it has 2).</li> </ul> </li> <li>confirm_password <ul class="errorlist"> <li>Ensure this value has at least 10 characters (it has 2).</li> </ul> </li> <li>first_name <ul class="errorlist"> <li>Ensure this value has at least 2 characters (it has 1).</li> </ul> </li> <li>last_name <ul class="errorlist"> <li>Ensure this value has at least 2 characters (it has 1).</li> </ul> </li> </ul> This is not the html syntax I want. I actually want to wrap them in my own elements. For example {%if form.errors %} <section class="errors-container"> {% for err in form.errors %} <p>{{err.field_name}}</p> <div> {{err.actual_error_for_field_name}} </div> {% endfor %} </section> {%endif%} That is the layout I want. I even tried passing an errors variable to the context dictionary in my view. def user_register(request): errors = {} if request.method == 'POST': form = PersonRegisterForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] == form.cleaned_data['confirm_password']: cd = form.cleaned_data new_user = Person.objects.create_user(username=cd['username'], email=cd['email'], password=cd['password'], first_name=cd['first_name'], last_name=cd['last_name']) messages.success(request, f'You are successfully registered as {new_user.username}!') return redirect("profile", new_user.id) for i in form.errors: errors[i] = form.errors[i] print(errors) else: form = … -
Django change value before save in ModelViewSet
I am new to Django (and the REST framework) but I am struggling to update a value before save. Right now I am using a simple ModelViewSet to update a record. Everything works, but the value doesnt get updated if I create an item in de admin site. Code of the view is as follows: class OauthProviderViewSet(viewsets.ModelViewSet): queryset = OauthProvider.objects.all() serializer_class = OauthProviderSerializer authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAdminUser] def perform_create(self, serializer): changed_credentials = "test" + self.request.credentials serializer.save(credentials=changed_credentials) I just want to pre-pend the word test to the credentials field. -
Django REST Framework: Creating Object and Connecting Foreign Key with Serializers
Currently, my TaskList objects are connected to my TaskItem objects by a foreign key (with the TaskItems being in a list called task_items). I am able to add items in the shell to the list fine, but when it comes to the serializer I haven't been able to figure out how to connect these two entities. The request.data object and the serializer.data object are not compatible to work with the DB API commands. Is this possible to do? If so, what would be the best way to go about this? models.py class TaskItem(models.Model): task_name = models.CharField(max_length=200) difficulty_level = models.IntegerField(default=1) def __str__(self): return self.task_name class TaskList(models.Model): list_name = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) task_items = models.ManyToManyField(TaskItem) def __str__(self): return self.list_name serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = TaskItem fields = '__all__' class TaskListSerializer(serializers.ModelSerializer): TaskItem = TaskSerializer() class Meta: model = TaskList fields = '__all__' # list_name, user, task_items views.py @api_view(['POST']) def addTask(request, pk): user = User.objects.get(id=pk) taskList = TaskList.objects.select_related().filter(user=user).first() taskListSerializer = TaskListSerializer(taskList) serializer = TaskSerializer(data=request.data) if serializer.is_valid() and taskListSerializer.is_valid(): serializer.save() return Response(serializer.data) -
How to make nested jsonb model with django / postgres?
The model I want to make is similar to the youtube api model. { "videos": [ { "id": "7lCDEYXw3mM", "snippet": { "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw", "title": "Google I/O 101: Q&A On Using Google APIs", "categoryId": "28" }, "statistics": { "viewCount": "3057", "likeCount": "25", "dislikeCount": "0", "favoriteCount": "17", "commentCount": "12" } } ] } I tried using ArrayField but when I posted a list of fields into the array I kept getting this error: "Expected a list of items but got type \"dict\"." This is the model so far class Menu(models.Model): burgers = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) beverages = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) extras = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) fries = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, default=None ) I want to make each item inside the Array to have its own fields for the name and price. { "burgers": [ 0:{ "name":"Plain patty", "price":4 }, 1:{ "name":"Cheese buns", "price":8 } ] } How can I make it with jsonb? -
How can i check if the function based view was called from another redirect function or directly from the url?
I have an online store where users pay at domain.com/pay and receive their product after paying at domain.com/done However, when I was testing it I found out that users can go to the URL and type domain.com/pay manually and all a sudden, they get their product without paying! I want someway to check whether the user accessed it manually or from a redirection, if manually then raise http403 if from redirect then the function will happen normally Here is my process_pay view def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': trade.seller.email, 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}/{}'.format(host, *reverse('payment_done', kwargs={'trade_id': trade.id})), 'cancel_return': 'http://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) my done_process view @csrf_exempt def payment_done(request, trade_id): # if user entered from a redirection: # Give product to user # elif user entered manually: raise http403 # else: messages.error(request, 'something went wrong') return redirect('home') return redirect('trade:inbox') -
Filter api view from another view result Django (REST)
I have 2 API returned in Django like this. List of apps: {"count":3,"next":null,"previous":null,"results":[ {"id":1,"user":"x","name":"app1","title":"title1","active_user":"user1"}, {"id":2,"user":"x","name":"app2","title":"title2","active_user":"user1"}, {"id":3,"user":"x","name":"app3","title":"title3","active_user":"user1"}]} This API have X ids or name (only 3 here for the example), imagine 100 or more. They must match with the second API (field id or name of list_apps). And the second has already been filtered for just the active user. User data: {"count":1,"next":null,"previous":null,"results":[ {"user":"user","email":"none","list_apps":{ "1":{"id":"1","hgt":"1","pos":"1","wth":"1","name":"hello","color":"default","visible":"true"}, "2":{"id":"2","hgt":"1","pos":"2","wth":"1","name":"dash","color":"default","visible":"true"}, So, in this case, I expected to return only the 2 first app in the first API (list of app), because the user have only access to 1 and 2. (list_apps are from a PostGre JSON field). Answer expected: {"count":3,"next":null,"previous":null,"results":[ {"id":1,"user":"x","name":"app1","title":"title1","active_user":"user1"}, {"id":2,"user":"x","name":"app2","title":"title2","active_user":"user1"}]}, Here's the view.py @permission_classes([IsAuthenticated]) class DashListCreate(generics.ListCreateAPIView): renderer_classes = [JSONRenderer] serializer_class = DashSerializer def get_queryset(self): return Dash.objects.filter(id__in=["1","2","3"]) @permission_classes([IsAuthenticated]) class UserDashListCreate(generics.ListCreateAPIView): renderer_classes = [JSONRenderer] serializer_class = UsersDashSerializer def get_queryset(self): print(UsersDash.objects.only('list_apps').values()) return UsersDash.objects.filter(user=self.request.user) The answer is maybe replace the field ["1","2","3"] in the filter by the list of "id" in the other api : list_app.api.all() but i don't know 2 things : How to call an API from Another Just select the values I need, I tried only('list_apps').values() but it does not work (no filter). Is it a good practice to filter in the view or there …