Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django looking for template that doesn't exist
I made some major changes to my site and now when I click a specific link, it tries to go to a page that doesn't exist (rightfully so) but I can't find any reference to that non-existent page in my code so I can't direct it properly. views.py from django.shortcuts import render from .models import BakingPost from django.views import generic def index(request): num_posts = BakingPost.objects.all().count() context = { 'num_posts': num_posts, } return render(request, 'food_blog/index.html', context=context) class BakingListView(generic.ListView): model = BakingPost # paginate_by = 10 class BakingDetailView(generic.DetailView): model = BakingPost urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('bakes/', views.BakingListView.as_view(), name='bakes'), path('bake/<int:pk>/', views.BakingDetailView.as_view(), name='bake_detail'), # path('post/new/', views.post_new, name='post_new'), # path('post/<int:pk>/edit/', views.post_edit, name='post_edit'), ] navbar.html <nav> <div id="div_navbar"> <ul class="ul_navbar"> <li class="li_navbar"> <a class="a_navbar" href="{% url 'index' %}">Home</a> </li> <li class="li_navbar"> <a class="a_navbar" href="{% url 'bakes' %}">Baking List</a> </li> </ul> </div> </nav> bake_list.html {% extends 'food_blog/base.html' %} {% block content %} <h1>Baking List</h1> {% if bake_list %} <ul> {% for bake in bake_list %} <li> <a href="{{ bake.get_absolute_url }}">{{ bake.title }}</a> ({{bake.author}}) </li> {% endfor %} </ul> {% else %} <p>Nothing in the oven</p> {% endif %} {% endblock %} When I click on "Baking … -
A URL of a Hyperlinked Model Serializer returns '{"detail": "not found."} for a model with custom PK
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) website = models.URLField(max_length=30, null=True, blank=True) class ProfileViewSet(viewsets.ModelViewSet): lookup_field = 'user' serializer_class = ProfileSerializer queryset = Retailer.objects.all() class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['website', 'user', 'url'] extra_kwargs = { 'url': {'view_name': 'profile-detail', 'lookup_field': 'user'}, 'user': {'lookup_field': 'username', 'view_name': 'user-detail'} } The code above lists all profiles and their URL's in JSON format. However, when a URL is clicked, it returns '{"detail": "not found."} instead of showing the details of the profile. Any idea? Thanks! Django version: 3.0.4 Django Rest Framework version: 3.11.0 -
python timer decorator with outputting classname
I am creating a little helper tool. It is a timer decorator (not so special) for measuring the execution times of any method. It prints the calculated execution time on the console with useful informations. def timer(func): """@timer decorator""" from functools import wraps from time import time def concat_args(*args, **kwargs): for arg in args: yield str(arg) for key, value in kwargs.items(): yield str(key) + '=' + str(value) @wraps(func) # sets return meta to func meta def wrapper(*args, **kwargs): start = time() ret = func(*args, **kwargs) dur = format((time() - start) * 1000, ".2f") print('{}{}({}) -> {}ms.'.format( func.__module__ + '.' if func.__module__ else '', func.__name__, ', '.join(concat_args(*args, **kwargs)), dur )) return ret return wrapper This gives me the modelname, and the functionname like that: user.models.get_matches(demo) -> 24.09ms. I want to have the class name in the output, too: user.models.User.get_matches(demo) -> 24.09ms. How can I get the class name of the function ('func') from inside the wrapper? Edit: Great thanks to Hao Li. Here is the finished version: def timer(func): """@timer decorator""" from functools import wraps from time import time def concat_args(*args, **kwargs): for arg in args: yield str(arg) for key, value in kwargs.items(): yield str(key) + '=' + str(value) @wraps(func) # … -
How to transform a list of dictionaries in Django view to return it as JSON?
I am calling the Giphy API using another wrapper API which returns a list of dictionaries. I am having hard times to transform the data to return it to AJAX. The data is returned as InlineResponse200 with three properties. According to the docu the dict consists of strings mainly. def get_gifs(request): # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = 'NGSKWrBqtIq1rFU1Ka11D879Y1u4Igia' # Search term q = request.POST.get('query') # Query parameters limit = 2 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) pprint(api_response) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) response = api_response.data JsonResponse(response) return render(request, response) # Returns: TypeError: Object of type Gif is not JSON serializable [...] response = api_response.data return render(request, response) # Returns: TypeError: join() argument must be str or bytes, not 'Gif' [...] response = api_response.data serialized_obj = serializers.serialize('json', response) return render(request, serialized_obj) # Returns: AttributeError: 'Gif' object has no attribute '_meta' [...] response = api_response.data[0] serialized_obj = serializers.serialize('json', response) return render(request, serialized_obj) # TypeError: 'Gif' object is not iterable Going nuts.. -
Display fields based on previous dropdown
On Django site have model "Worksheet" and it has several types (for instance Driver/Cook/Housekeeper) When adding WS 1st step is choise field called "Worksheet type" and regarding the choosed type display related fields Flow: Add worksheet Form show dropdown list called "Choose worksheet type" (Driver for example), click next Form display fields specified for driver (e.g driving experience and vehicle type) I thought it is simple but a long time cant find the solution I have a lot of experience with different cms e.g Drupal/Joomla/Wordpress but I'm new in Django and I'll be very grateful if you provide your answer in details Thks!!! -
Bookmark Implementation methods in Django
I am trying to add a bookmarking system to my website however, I am kinda stuck on how to implement this: My approach following the link: https://evileg.com/en/post/244/ is class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(Profile,on_delete=models.CASCADE, verbose_name="User") def __str__(self): return self.user.username class BookmarkPost(BookmarkBase): class Meta: db_table = "bookmark_post" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey(Post,on_delete=models.CASCADE, verbose_name="Post") class BookmarkBlog(BookmarkBase): class Meta: db_table = "bookmark_blog" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey(Blog,on_delete=models.CASCADE, verbose_name="Blog") However, I was also wondering if the approach of creating a many to many relationships inside my user model with each object is also correct or not: so I will have : class Profile(AbstractUser): ''' Custome fields ''' bookmark_blog = models.ManyToManyField(Blog, blank=True, related_name='b_blogs') bookmark_post = models.ManyToManyField(Post, blank=True, related_name='b_posts') -
Field 'id' expected a number but got <QueryDict: >error in django
I have this form: class addMeal(forms.Form): name = forms.CharField( max_length=40, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'}) ) foods = forms.ModelMultipleChoiceField( queryset=Food.objects.none(), widget=forms.SelectMultiple(attrs={'class':'form-control'}) ) def save(self,request): data = self.cleaned_data meal = Meals(name=data['name'],user=request.user,foods=data['foods']) meal.save() def __init__(self, user=None,*args, **kwargs, ): super().__init__(*args, **kwargs) if user is not None: self.fields['foods'].queryset = Food.objects.filter(user=user) class Meta: model = Meals and this view: @login_required def addmeal(request): if request.method == 'POST': form = addMeal(request.POST) if form.is_valid(): form.save(request) return redirect('food:index') else: form = addMeal(user=request.user) return render(request,'addmeal.html',{'form':form}) when i fill out form and press submit django give me error(Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['C2B8y3kLCa5IQ0S5Mvk7Tw0NTU4pNlYicppWlsIL1LCrcc8AuCQzjJkqWNUot4z6'], 'name': ['شام'], 'foods': ['1']}>.). what should i do to fix it? -
TypeError: join() argument must be str or bytes, not 'InlineResponse200' - How to return API data via Django view to AJAX?
I am calling an async AJAX function to trigger a view which itself requests API data. Everything works fine and the API data is returned properly. But then the view function crashes with the following error. I use this wrapper for the API requests. I assume something is messy with my return method in the view. Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py", line 229, in get_gifs return render(request, api_response) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\ntpath.py", line 109, in join genericpath._check_arg_types('join', path, *paths) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\genericpath.py", … -
Django modelformset with customized model initialization
I have a model in django with a foreign keya to another modela as follows: TAG: user=ForeignKey() name=CharField() shop=ForeignKey() It is being used to assign a tag to a given user and chosen shop. For this purpose, shop field is being filtered based on the user instance. Now I need to create a modelformset that will allow me to store bunch of different tags per user. What I am looking for is a way to initialize such formset with a shop field filtered out. Any ideas are very welcome! Thanks -
NoReverseMatch at /v2/search/SARS_CoV_2/GID1716
I am developing a django application in which I am trying to send a value of the variable to the backend on click of a button through javascript. javascript code: $(document).on("click", "#filter", function (e) { IUPredscorethreshold = 0.4 $("#ksNetwork").empty(); ksInteractionNetwork('{% url "camkinetv2:newinteractors_intnet" tab1.caMKipedia_Id IUPredscorethreshold %}'); }); urls.py path( "dataJson/newinteractors_intnet/<str:geneId>/<str:IUPredscorethreshold>", views.newinteractors_intnet, name="newinteractors_intnet", ), views.py @csrf_exempt def newinteractors_intnet(request, geneId, IUPredscorethreshold): print("IUPredscorethreshold:" + IUPredscorethreshold) . . . . . some computation graphData = {"nodes": uniquenodesdata, "links": linksdata} response = JsonResponse(graphData) return response when I execute this code i am getting following error: NoReverseMatch at /v2/search/SARS_CoV_2/GID1716 Reverse for 'newinteractors_intnet' with arguments '('GID1716', '')' not found. 1 pattern(s) tried: ['v2/dataJson/newinteractors_intnet/(?P<geneId>[^/]+)/(?P<IUPredscorethreshold>[^/]+)$'] Exception Value: Reverse for 'newinteractors_intnet' with arguments '('GID1716', '')' not found. 1 pattern(s) tried: ['v2/dataJson/newinteractors_intnet/(?P<geneId>[^/]+)/(?P<IUPredscorethreshold>[^/]+)$'] what am I doing wrong? how can I solve this issue. I am still at learning stage of django and I am not able to figure out how to solve this error. -
when I execute the python manage.py runserver, CMD throws AttributeError:
I am new to Django! So I built a simple blog application using python/Django, MySQL as the back end using the XAMPP control panel. It was running as expected on http://localhost:8000. However, at the end of project when I added a Button functionality & restarted(python manage.py runserver) the server using the CMD. The CMD threw: AttributeError: module 'posts.views' has no attribute 'details'. Your help wold be appreciated! -Attached is the project on GitHub. urls.py file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<id>\d+)/$', views.details, name='details') ] views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def index(request): # return HttpResponse('HELLO FROM POSTS') posts = Posts.objects.all()[:10] context = { 'title': 'Latest Posts', 'posts': posts } return render(request, 'posts/index.html', context) def details(request, id): post = Posts.object.get(id=id) context = { 'post': post } return render(request, 'posts/details.html', context) details.py file: {% extends 'posts/layout.html' %} {% block content%} <h3 class="center-align red lighten-3">{{post.title}}</h3> <div class = "card"> <div class="card-content"> {{post.body}} </div> <div class="card-action"> {{post.created_at}} </div> </div> <a href="/posts" class="btn">Go Back</a> {% endblock %} Error stacktrace: (py1) C:\Users\Ajmal .M\Google Drive\GitHub\Projects\djangoproject>python manage.py runserver Watching for file changes with StatReloader Performing system … -
The system cannot find the path specified: error returned when changing field in admin page Django
Hi guys I was just following this tutorial (https://realpython.com/get-started-with-django-1/) to integrate a projects application for my Django portfolio-site project. Everything was going well with the set up until I tried to log in to admin page of Django to add more objects to my Project model in the database. After I click add, it return me an error page and it says like this: Error return page [1]: https://i.stack.imgur.com/co1Cy.png Traceback Traceback (most recent call last): File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1638, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1555, in _changeform_view ModelForm = self.get_form(request, obj, change=not add) … -
Django saving data to wrong fields
When I create an object in Django it saves the data to the wrong fields. When I make the following postman request: The return serialized data is correct. But the data saved to the db is not which looks like: The first two fields are correct but the rest are not. It saves the price as the rating, the weight_unit as the price, the user id as the weight and the rating as the user_is. View class CoffeeViewSet(viewsets.ViewSet): def create(self, request): serializer = CoffeeSerializer(data=request.data) if serializer.is_valid(): c = Coffee.objects.create( company = serializer.validated_data.get('company'), rating = serializer.validated_data.get('rating'), weight = serializer.validated_data.get('weight'), weight_unit = serializer.validated_data.get('weight_unit'), blend = serializer.validated_data.get('blend'), price = serializer.validated_data.get('price'), user = request.user ) print(c) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_401_BAD_REQUEST) Serializer class CoffeeSerializer(serializers.ModelSerializer): class Meta: model = Coffee fields = ['company', 'blend', 'rating', 'price', 'weight_unit', 'weight'] also when I print validated_data is correct so my assumption is something with how the object is saved is not correct but I can not figure out. validated data OrderedDict([('company', 'Stumptown'), ('blend', 'Hair Bender'), ('rating', 7), ('price', Decimal('16.00')), ('weight_unit', 'OZ'), ('weight', Decimal('12.00'))]) What is going on here? -
How to call an API endpoint async via Django view
I want to make an async API request to get gifs from the Giphy API. The user triggers the AJAX call and therefor the related view by clicking the submit button. I then want to populate the DOM with the returned GIFs. Right now when I click the submit button, the page reloads and nothing happens. I don't even see the print within the view function. Where do I mess up? Does it even make sense to set up a view for this or just call the API within the AJAX directly? html <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <form> <label for="search">Search</label> <input placeholder="Search gif" id="search" type="search" name="q" action="{% url 'get_gifs' %}"/> <button type="submit" id="btnSearch">Go</button> </form> urls.py from blog.views import get_gifs urlpatterns = [ # Gyphy Search path('get_gifs', get_gifs, name='get_gifs'), ] Ajax (function($) { $('#btnSearch').on('click', function() { var query = $('#search').text(); e.preventDefault(); $.ajax({ type: 'get', async: true, url: '/get_gifs/', data: { 'query': query, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { // shit happens friends! } }); }); }(jQuery)); Views.py def get_gifs(request, query): print('fired') # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = … -
CSS not working on django password form field
I downloaded a css template from the web. I was able to link everything to my Django code execpt for the password fields and button styling. What step am I missing missing? I have read the Django documentatin and I am using the attr metthod to add css attributes to my django form fields. In my python code their seems to be a missing form attribute for password fields when implementing css. #My Forms.py code class CreateUserForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2'] #applying form css rules where the item is a call to the css name or form attribute widgets={ 'username': forms.TextInput(attrs={'class':'un', 'type':'text', 'align':'center', 'placeholder':'UserName'}), 'email':forms.TextInput(attrs={'class':'un', 'type':'text', 'align':'center', 'placeholder':'Email'}), 'password1':forms.PasswordInput(attrs={'class':'pass', 'type':'text', 'align':'center', 'placeholder':'password'}), 'password2': forms.PasswordInput(attrs={'class':'pass', 'type':'password', 'align':'center', 'placeholder':'password'}), } #My View function def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect('login') context = {'form': form} return render(request, "testingapp/signup.html", context) #My css code body { background-color: #F3EBF6; font-family: 'Ubuntu', sans-serif; } .main { background-color: #FFFFFF; width: 400px; height: 400px; margin: 7em auto; border-radius: 1.5em; box-shadow: 0px 11px 35px 2px rgba(0, 0, 0, 0.14); } .sign { padding-top: 40px; color: #8C55AA; font-family: 'Ubuntu', sans-serif; font-weight: bold; font-size: … -
Ajax request returns `Page not found (404)` result
I know what that error means. I need your help to see my code, what I am doing wrong. I want to create an add to wishlist button, here is the tag: <a href="{% url 'listing:wishlist' %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> urls.py path('wishlist/', wishlist, name='wishlist'), Ajax code in template: $(document).on('click', '#wishlistbtn', function (e) { let el = $(this); $.ajax({ type: 'GET', url: "/wishlist/", data: { title_slug: el.attr("data-slug"), }, success: function () { alert('added to wishlist'); } }) }) and here is the view: def wishlist(request): slug = request.GET.get('title_slug') obj = get_object_or_404(Listing, slug=slug) profile = Profile.objects.all().filter(user=request.user).first() profile.wishlist.add(obj) return HttpResponse('true') Kindly help me find the error and solve it. -
use request in form class in django
I have a form just like this: class addMeal(forms.Form): name = forms.CharField(max_length=40,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'})) foods = forms.ModelMultipleChoiceField(queryset=Food.objects.filter(user=1),widget=forms.SelectMultiple(attrs={'class':'form-control'})) class Meta: model = Meals i need write a queryset to get user id with request(see the queryset=Food.objects.filter(user=1) ) what should i do to fix it? -
How does the code use the regex to match the info in the URL here?
class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value from django.urls import path, register_converter from . import converters, views register_converter(converters.FourDigitYearConverter, 'yyyy') urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<yyyy:year>/', views.year_archive), ... ] How does the regex variable is used to match the year info in the URL? It is just a class variable. It is from Django docs so I think it must work somehow. Anybody knows how this snippet works? Thanks in advance! -
Django session variable gets deleted when back button is clicked
I am new to django. I want a page (lets say page X) to be accessible by the user only once (that too by a redirect). So what I did is used session variables to do this: This is the view for the page from where I want to redirect the user to X - def MainPageView(request): //Some code which doesn't use or modify session variables request.session['seen_status'] = False redirect ("url_of_X_%d" % some_int) This is the view of X - def Status(request,id): if request.session['seen_status'] == False: //some code which shows the page content request.session['seen_status] = True return render(page) //page contains a button 'A' to go to the next page else: //page to display if user has already seen the page. This works fine if I go to X and refresh (that is, the else block gets executed). But, if the user goes to the next page by clicking the button 'A' and comes back using the back button of the browser, he can see the page again! I tried to debug this by using print statements, that is by printing request.session['seen_status'] but I get an error: Not Found: /favicon.ico Further, on clicking the back button, I don't get anything like: … -
How to assign task to group in django viewfloe
Im looking for a solution to assign task to group in viewflow I Assigned task to user by .Assign(username='employee') -
How to associate a comment with a parent comment in Django models
I have built an application with comments that are commented on a parent comment. I have the following comment model. How can I associate the comment with a parent comment ? class Comment(models.Model): uuid = models.UUIDField(max_length=255, default = uuid.uuid4) description = models.CharField(max_length=5000, default="") likes = models.PositiveIntegerField(default=0) dislikes = models.PositiveIntegerField(default=0) uploaded_at = models.DateTimeField(null=True, blank=True) commentinguser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) video = models.ForeignKey(Video, on_delete=models.CASCADE) -
Encrypt the uploaded file and then store it
I am trying to encrypt the user uploaded file and then save them to the machine. but i am getting error , Its mainly because my code for algorithm looks for file in given path, but here the uploaded file is in upload memory so any ideas to directly encrypt file and then store it. Request Method: POST Request URL: http://127.0.0.1:8000/user/UploadToCloud/ Django Version: 3.0.6 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admins', 'user', 'login'] Installed 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'] Traceback (most recent call last): File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Programming\python\Django\CryptoCloud\user\views.py", line 78, in UploadToCloud if(Aes.encrypt_file(file_temp,'out.enc')): File "E:\Programming\python\Django\CryptoCloud\user\algorithms.py", line 64, in encrypt_file file_size = os.path.getsize(in_file_name) File "C:\Users\PMD\AppData\Local\Programs\Python\Python37\lib\genericpath.py", line 50, in getsize return os.stat(filename).st_size Exception Type: TypeError at /user/UploadToCloud/ Exception Value: stat: path should be string, bytes, os.PathLike or integer, not _TemporaryFileWrapper here is my code: ///// view.py ///// def UploadToCloud(request): if request.method == "POST": print('POST Method Works Fine') usremail = request.session['email'] form = UserFileUploadForm(request.POST, request.FILES) if form.is_valid(): print(form.cleaned_data['algorithms']) ipfile = form.cleaned_data['userfile'] # accesskey = form.cleaned_data['accesskey'] accesskey = … -
vendors.min.js:2 Uncaught RangeError: Maximum call stack size exceeded using AJAX with django
I'm trying to make an ajax request in the Django project, using Django Ajax, here is my code : the HTML code where the call is made function addRecipe() { const recipeSize = document.getElementById('recipeSize'); const recipeItem = document.getElementById('autocomplete-input'); const recipeQuantity = document.getElementById('recipeQuantity'); alert(recipeSize.value); alert(recipeItem.value); alert(recipeQuantity.value); $.ajax({ url: "{% url 'add_recipe_item' %}", data: { 'the_size_id': recipeSize, }, dataType: 'json', success: function (data) { console.log(data); } }); } URL.py path('ajax/add/recipe/item/', products_views.add_recipe_item, name="add_recipe_item"), views.py @ajax def add_recipe_item(request): size = get_object_or_404(Size, id=request.GET.get('the_size_id')) print(size.name) data = { 'the_size': size.name, } return data When I run the function in HTML, It gives back this error after lagging for a few seconds vendors.min.js:2 Uncaught RangeError: Maximum call stack size exceeded -
Django - How to create multiple users for a single app
myproject ---myapp I have created a django project which has an app in it that does viewing , adding data to database etc. Now I want to create multiple users who can use this app with their own data. What is the best way about it. Lets say there are 3 users user1, user2, user3 Currently I am planning to do this. I copy the myapp code and create 3 apps corresponding to each user. So the project directory looks something like this myproject ---myapp ---myappuser1 ---myappuser2 ---myappuser3 So I now have 3 apps with similar functionality and each of the user has their own data. Now, the hurdle is how do I restrict access so that each user can see his own app. For instance, user1 should be able to only see myappuser1 contents and user2 should only see myappuser2 contents. How can I do this ? I tried creating groups in django admin but that only gives me permissions to edit the items under the myapp. It doesn't restrict user to not allow other user pages. Option 2: Create seperate django project for each user. This solves the user restriction but to deploy in heroku I should register … -
list object has no attribute "values"
In Django, this is my code and it is working fine. from myapp.models import Users user = Users.filter(organization ="abc").order_by("-created_at")[offset:offset+limit] user.values("id") But when I try to break the code into smaller parts, it throws an error on the third line saying: attribute error: list object has no attribute "values" from myapp.models import Users user = Users.filter(organization ="abc").order_by("-created_at") user = user[offset:offset+limit] user.values("id") I was just wondering why it is happening?