Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django – Disabling ModelForm fields
How is it possible to disable certain ModelForm fields to indicate that they're not editable? The docs seem to suggest setting the widget to disabled should do the trick, including making it tamper-resistent, however doing that form validation fails as the disabled fields POST as empty. (also trying to use the has_changed method, but doesn't seem to work for ModelForms and no equivalent is provided...) I alternatively tried setting the clean_<fieldname> method on ModelForm level, to set the field to the referenced instance's value, but validation fails before that's reached. Some sample code: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' widgets = { 'slug': forms.TextInput(attrs={ 'disabled': True }) } def client_form(request, slug: str=None): instance = get_object_or_404(MyModel, slug=slug) form_myform = MyForm(request.POST or None, instance=instance) if request.method == 'POST': if form_myform.is_valid(): # fails, because slug is empty in POST request pass -
django.db.utils.IntegrityError: (1062, "Duplicate entry '15-delete_comment' for key 'auth_permission_content_type_id_codename_01ab375a_uniq'")
I encountered this problem when changing the database from Squillight to MySQL. I cant do migrate. Im using django-comments-dab -
Pass request user to modelform in Django
I have a model where is save one of the groups of the user in my model. Because user can be member of different groups i need to update the Selection field in my Form depending on the request.user.groups.all() queryset. I tried to pass the initial variable to my form but this was ignored. Any hint how to deal with this problem? -
I want to add link to some path (path is added in urls.py) in my Django Admin main interfae
This is where I need to add the link (HTML <a> tag or <button>) in the admin site. The location of the link can be anywhere on the page. I just want a link which can redirect me from that page (i.e. my_domain/admin/) to another path (i.e. my_domain/admin/extension_logs/) I think I need to extend some base templates of Django But I have no idea which one to extend and how to extend! -
NoReverseMatch at / Reverse for 'course_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['course/(?P<slug>[-a-zA-Z0-9_]+)/$']
I am trying to make a site that has a learning area so that instructors can upload courses for users to look at. i am trying to add a url to the home page to link to te course overview page and I keep getting a NoReverseMatch error when i try to add the url. Here is the urls.py file from django.urls import path from . import views urlpatterns = [ path('content/order/', views.ContentOrderView.as_view(), name='content_order'), path('subject/<slug:subject>/', views.CourseListView.as_view(), name='course_list_subject'), path('<slug:slug>/', views.CourseDetailView.as_view(), name='course_detail'), ] views.py class CourseDetailView(DetailView): model = models.Course template_name = 'courses/course/detail.html' class CourseListView(TemplateResponseMixin, View): model = models.Course template_name = 'courses/course/list.html' def get(self, request, subject=None): subjects = models.Subject.objects.annotate(total_courses=Count('courses')) courses = models.Course.objects.annotate(total_modules=Count('modules')) if subject: subject = get_object_or_404(models.Subject, slug=subject) courses = courses.filter(subject=subject) return self.render_to_response({'subjects': subjects, 'subject': subject, 'courses': courses}) template <div class="module"> {% for course in courses %} {% with subject=course.subject %} <h3> <a href="{% url 'course_detail' course.slug %}"> {{ course.title }} </a> </h3> <p> <a href="{% url 'course_list_subject' subject.slug %}">{{ subject }}</a>. {{ course.total_modules }} modules. Instructor: {{ course.owner.get_full_name }} </p> {% endwith %} {% endfor %} -
500 Internal Server Error when sending django ajax post form
html file <form method="post" id="send_sms_form"> <input type="submit" value="Send code" id="sendCodeSms" class="col btn btn-secondary btn-block mb-2" style="max-width: 30rem"> {% csrf_token %} </form> views.py @login_required def send_verification_code(request): if request.is_ajax and request.method == "POST": form = SendSmsForm(request.POST) sms = mainsms.SMS(settings.SMS_PROJECT, settings.SMS_API_KEY) Profile.objects.filter(user=request.user).update(verification_code=randomize_verification_code()) sms.send_sms(request.user.username, f'Your code: {request.user.profile.verification_code}') if form.is_valid(): instance = None ser_instance = serializers.serialize('json', [instance, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": ""}, status=400) forms.py class SendSmsForm(forms.Form): class Meta: widgets = {'any_field': HiddenInput(), } script.js function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); Error: Internal Server Error: /account/send-verification-code/ Traceback (most recent call last): File "C:\Users\user\Desktop\django-eshop\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\Desktop\django-eshop\venv\lib\site-packages\django\core\handlers\base.py", line 179, in … -
Does django-cors-headers prevent CORS latency issues?
I am developing a web application with Django backend and NextJS frontend. I am trying to have the frontend and the backend talk to each other and I am having some CORS issues. Reading about CORS I learned that it can introduce latency in large-scale apps because most requests basically have to be "processed" twice instead of once (correct me if I am wrong). To solve my CORS issues, I stumbled upon django-cors-headers and I was wondering whether this solution prevents latency among backend and allowed origins all together or not? Thanks. -
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 …