Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not redirecting
Here is a short snippet of my code that should redirect to sw_app:hub whenever a user post something: if test.is_valid(): test.instance.user = user test.save(commit=True) return redirect('sw_app:hub') else: response['result'] = 'failed' response['message'] = test.errors return JsonResponse(response) My urls.py: app_name = 'sw_app' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^hub/', views.hub, name='hub'), ... It registers the post successfully, but it doesn't redirect to the hub page. I already tried: return HttpResponseRedirect(reverse('sw_app:hub')) But still doesn't work. Any ideas? Thanks a lot! -
Is logging available for Zappa Lambda hosted Django sites?
I'm looking at moving a personal site from Heroku to Lambda using Zappa. Will persistent logs be available once I've deployed using Zappa? I've seen the Zappa tailing logs command but I'm talking about persistent logs. -
How to display menuin Django according to Group base permission?
I am trying to display menu according to group permission, but I am getting errors, Suppose if a user exist in another group and another user exist in seller group then i want to display only seller menu in my HTML design, rest all menus will be hide from my admin panel. Here is my code... {% if request.user.is_authenticated %} {% if request.user.groups.name == 'seller' %} <div>Seller Menu</div> {% else %} <div>Other Menu</div> {% endif %} Not if I login with another user which do not ahve seller group permission then he/she can see Other Menu option. Please let me know how I can display menu according to Group base permission. -
Change help_text position using as_crispy_form templatetag
I have a field which is rendered using as_crispy_field templatetag {{ form.field|as_crispy_field }} I want to change the help text position to be beside the label with red color This is the current output: I want it to be something similar to this: -
'function' object has no attribute 'get' Error [closed]
api_endpoint = "http://127.0.0.1:8000/employees/" headers = {'Content-Type': 'application/json; charset=utf-8'} api_data = requests.get(api_endpoint,headers=headers) print(api_data) json_data = json.loads(api_data.text)` -
Why FormSet saves the data of only one form
When I submitted formset, my FormSet saves the data of only one form and other form data is lossed. view.py: def employadd(request): employ_academic_forms = EmployAcademicFormSet() if request.method == 'POST': employ_academic_forms = EmployAcademicFormSet(request.POST) if employ_academic_forms.is_valid(): instances = employ_academic_forms.save(commit=False) for instance in instances: instance.employ_id=employ_pass_obj instance.save() context = { 'employAcademicFormSet':employ_academic_forms, } return render(request, 'admins/employ/add_employ.html', context) -
how django will behave if i call object save method in pre_save method of this object?
I've two models A and B. class A(models.Model): a_name = models.Charfield(max_length=100) relate_to_b = models.Charfield(max_length=100) class B(models.Model): b_name = models.Charfield(max_length=100) a = OneToOne('A', on_delete=models.SET_NULL, null=True, default=None, related_name='b_a' when i save object A in pre_save_a method i change something in object B and in pre_save_b change A object and save it. question: is django call save method object A twice or doing all in first method? -
Upload image with DRF from react frontend
I want to upload image from react frontend. I tested the api from DRF browsable API, it worked as expected. #views.py class CreatePost(CreateAPIView): permission_classes = (permissions.AllowAny, ) queryset = BlogPost.objects.all() serializer_class = BlogCreateSerializer #serializers.py class BlogCreateSerializer(serializers.ModelSerializer): class Meta: model = BlogPost fields = ('id', 'title', 'category', 'thumbnail', 'excerpt', 'content', 'author') On the react side const onChange = (e) => setFormData({ ...formData, [e.target.name]: e.target.value }); <div className="form-group"> <label htmlFor="exampleFormControlFile1">THUMBNAIL</label> <input type="file" className="form-control-file" name="thumbnail" value={thumbnail} onChange={(e) => onChange(e)} required /> </div> headers: { "Content-type": "multipart/form-data", }, I am new to both DRF and react. Please see how can I upload "thumbnail" field for my blog posts. If you need any other details please comment. -
How to write pagination in Django without page reload?
This is for online exams. The code is working fine, but the problem is when i click on next the selected radio button is unchecked because of page reload. How to go to next question without page reload. <form name="answer" id="answer" action="answer" method="POST"> {% csrf_token %} {% for question in ques %} <table cellspacing="15"> <tr> <td>{{ question.qs_no }}</td><td><input type="hidden" name="question" value="{{ question.questions }}">{{ question.questions }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_a}}"></td><td> {{ question.option_a }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_b}}"></td><td>{{ question.option_b }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_c}}"></td><td>{{ question.option_c }}</td> </tr> <tr> <td><input type="radio" name="answer" value="{{question.option_d}}"></td><td>{{ question.option_d }}</td> </tr> </table> {% endfor %} </form> <br><br> {% if ques.has_previous %} <button><a href="?page={{ques.previous_page_number}}">Previous</a></button> {% endif %} {% if ques.has_next %} <button><a href="?page={{ques.next_page_number}}">Next</a></button> {% endif %} <button>submit</button> If any script needed for this please post that script. Thank you -
Return location header in Django
I am writing an API for shortening URL and I have to return the following response. request: GET /:shorten_url Content-Type: "application/json" Expected Response: 302 response with the location header pointing to the shortened URL HTTP/1.1 302 Found Location: http://www.example.com # original url I tied: # shortcode is the shorten url of original url def get(self, request, shortcode): if shortcode: try: shortUrl = UrlShort.objects.get(shortcode=shortcode) originalUrl = shortUrl.url response = HttpResponse(status=status.HTTP_302_FOUND) response['Location'] = shortUrl.url return response except UrlShort.DoesNotExist: raise Http404() Rather than getting 302 status code with location header, I'm redirected to the url with status code 200. Whar is wrong in my code? -
TypeError: perform_create() does not have 1 required positional argument'serializer' I am getting an error like this
view.py from rest_framework import viewsets, permissions, generics, serializers from .serializers import PlayerSerializer from .models import PlayerList from rest_framework.response import Response class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def perform_create(self, request, serializer): d_code = request.data.get('h_code') + 'test' #do something with d_code new_code = d_code + 'someSampleValue' serializer.save(d_code=new_code) TypeError: perform_create() does not have 1 required positional argument'serializer' I am getting an error like this. Any idea why I am getting this error? Let me know what I am missing now. This is an example of perform_create -
Update the ranks to django model records based on the respective fields
I have a Django model in which the records are created on a weekly basis. Each record will have the decimal values calculated for monthly, 1 yearly, 3 yearly and so on. This input data is available in the form of a queryset. These records are then created in the Ranks model record by record. The input data is available in this below format as a queryset. Input Data item_code | ason_date | v_monthly | v_yearly_1 | --------------------------------------------------- 1 | 2020-10-05 | 9.05 | 7.43 | 2 | 2020-10-05 | 7.05 | 9.43 | 3 | 2020-10-05 | 4.05 | 2.43 | 4 | 2020-10-05 | 6.05 | 5.43 | 5 | 2020-10-05 | 1.05 | 8.46 | Am ordering the queryset in descending order w.r.t. v_monthly and then creating the records in my Ranks model as below. rank_obj = [] rank = 1 for rec in input_data: rank_kwargs = {"item_code" : rec["item_code"], "ason_date" : rec["ason_date"], "v_monthly" : rec["v_monthly"], "r_montlhy" : rank, "v_yearly_1": rec["v_yearly_1"] } rank_obj.append(Ranks(**rank_kwargs)) rank+=1 Ranks.bulk_create(rank_obj) I've tried to update the other Ranks but it is highly time-consuming because of the huge number of records. all_vals = Ranks.objects.filter(ason_date = datetime(2020,10,5)) cal_vals = ["yearly_1","yearly_2", "yearly_3", .......] for field in … -
Upgrading to Django 3.1.2
Just upgraded from Django version 3.0.3 to 3.1.2. When trying to run the server, I am now presented with the following: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/Users/turbz/work/newmarkets/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 200, in __init__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive. I have neither if those aforementioned settings set in my own settings.py, since they are coming from venv/lib/python3.8/site-packages/django/conf/global_settings.py Any ideas? -
Destroy access token manually
How can the token that are built using djangorestframework _ simplejwt can be invalid after an operation such as password change. I don't want to use the methods like building a database to make the blacklist. I use django version 3 and drf version 3.11. Thanks. -
Minimum number of points one should pick to reduce all the points to minimum number of points
I am new in python, need a help to write a program in python. Suppose There are many sets of points on the horizontal axis of a co-ordinate plane. If a point is plotted in between any set, that set is reduced to that point. Given X sets, find the minimum number of points one should pick to reduce all the points to minimum number of points. Input Specification: input1: X, number of sets input2: Array consisting of X pairs, each pair indicating start and end of a set. Output Specification: Return an integer number as per the question. Example1: input1: 3 input2: {{1,3},{2,5},{3,6}} output:1 Explanation: Check image for description Example 2: input1: 3 input2: {{1,3},{2,5},{6,9}} Output: 2 Explanation: Check image for description I am looking for the code of this format. Can anyone help me out. Class userMaincode(obeject): @classmethod def minPoints(cls, input1, input2): input1: int input2: int[-] Expected return type: int #Enter code here pass -
RTSP stream to HTTP live stream using python
I am getting a RTSP camera stream, and i want to convert it in to a Http URL and need to play I need to do this using python how can I do this I tried OpenCV to read the RTSP stream , and how can I convert it into a http stream ? I am using python and django i want to generate the url and need to play the video using the url (for testng using VLC) -
Running a C++ program from Django
I have a Django web application where a user can upload a file. I have a C++ program that should read the uploaded file, do some processing and create a new output file. I then want to allow the user to download this output file from the Django web application. I am having problem figuring out how to send the path of the uploaded file to the C++ Program and then running the C++ program from within Django. -
Django: Implementation of an API and determining errors
For the communication between the client (js) and server I would like to create an API. The API should be accessible by all client requests (js functions). I would say that it is elegant when the response of the server is standardized. So that the interpretation at the client side can be also standardized. For instance, my API module (Python) returns a JSON object with the default settings: responseData = { "action_success": False, "data_container": None, "error": { "code": 0, "message": "", } } Let's have a look at a example function login of the module api. def login(request): # Get post data post = json.loads(request.body) # Get username and password username = post.get('username', None) password = post.get('password', None) # Initialize response data responseData = { "action_success": False, "data_container": None, "error": { "code": 0, "message": "", } } if username == '' or username is None: responseData.action_success = False responseData.error.code = 1 responseData.error.message = "login.no_username" return JsonResponse(responseData) elif password == '' or password is None: responseData.action_success = False responseData.error.code = 2 responseData.error.message = "login.no_password" return JsonResponse(responseData) # Check if username/password combination is correct user = authenticate(username=username, password=password) if user is not None: # User login login(request, user) responseData.action_success = True responseData.error.code … -
set attribute error while trying to open admin panel in django
i am new to django and building a app when i added api app after creating api app i could not access the admin panel and i could not find how to slove this error any help would be appreciated, whene ever i try opening admin panel it shows the following error in command prompt: Internal Server Error: /admin/ Traceback (most recent call last): File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 499, in index app_list = self.get_app_list(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 482, in get_app_list app_dict = self._build_app_dict(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 449, in _build_app_dict model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\urls\base.py", line 55, in reverse app_list = resolver.app_dict[ns] File "C:\Users\Ganesh … -
How to download file from file field in django framework
I want to download a file from the file field through Django views. I tried al lot but didn't get it. Now if I click on the media link it will show in the browser and I want to download it. Thanks in advance. models.py class Question(models.Model): title = models.CharField(max_length=254) file = models.FileField(upload_to='exam/question') def __str__(self): return self.title -
MAX_ENTRIES is not working in django-redis
I am using Redis for caching in my multi-tenant system. And for testing purpose of the MAX_ENTRIES, I put 'MAX_ENTRIES': 2 in Both filebased.FileBasedCache and cache.RedisCache. Filebased is working fine ( it doesn't save more than 2 items as expected) But Redis is saving all the data and it is not deleting after reaching the limit. My 2 caches- 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'BACKEND': 'django_redis.cache.RedisCache', Here is the Screenshot of the Redis db:2 where values are not being deleted -
bad operand type for unary +: 'list' - Django Error
I deployed a django application a while ago and I just checked the website today and it gave me this error: bad operand type for unary +: 'list' Kindly let me know what might be the probelm -
why are arguments passed in dictionary falling into args in python 3?
My understanding according to, https://realpython.com/python-kwargs-and-args/ args getting mapped to kwargs in python is if you pass dictionary as an argument to the function, we receive it in kwargs. I'm trying to do it in a following way, views.py uniqueurl_extra_form = UniqueUrlExtraFieldsForm(request.POST or None, request.FILES or None, {"store_id" : store_details['store_id']}) forms.py class UniqueUrlExtraFieldsForm(forms.Form): def __init__(self, *args, **kwargs): store_id = kwargs.get("store_id", None) super(UniqueUrlExtraFieldsForm, self).__init__(*args, **kwargs) print(args, kwargs) but what I'm getting is (None, None, {'store_id': 41141}) {} Why is my dictionary getting received in args instead of kwargs? and kwargs returning empty? What am I doing wrong here? -
Unable login using google social login
I used to login using same query i have written for my project but since few days i am unable to login using google social login. def google_login(request): if "code" in request.GET: params = { "grant_type": "authorization_code", "code": request.GET.get("code"), "redirect_uri": request.scheme + "://" + request.META["HTTP_HOST"] + reverse("social:google_login"), "client_id": settings.GP_CLIENT_ID, "client_secret": settings.GP_CLIENT_SECRET, } info = requests.post("https://accounts.google.com/o/oauth2/token", data=params) info = info.json() if not info.get("access_token"): return render( request, "404.html", { "message": "Sorry, Your session has been expired", "reason": "Please kindly try again to update your profile", "email": settings.DEFAULT_FROM_EMAIL, "number": settings.CONTACT_NUMBER, }, status=404, ) I am getting the error messages as above mentioned because I think it's not taking the tokens. Can someone help me. -
How to fix required field error on Django's ImageField?
I'm trying to take an image as input from user. Eventhough I'm selecting an image it gives this field is required error. When I change required to False I encounter a different problem. After I select an image and post the form I don't see any file in request.FILES. When I check request.POST I see the file name but if I check form.cleaned_data the field returns none value. I added "method=multipart/form-data" to html and my forms.py and views.py is as below. I appreciate if you tell me what I am doing wrong. forms.py views.py