Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django default Authenticaiton form shows username rather than email
I implemented my own user login form with django like below from django.contrib.auth.forms import AuthenticationForm class CustomUserLoginForm(AuthenticationForm): class Meta: model = CustomUser fields = ('email', 'password') then as a view this is what I have: from rest_auth.views import LoginView from users.forms import CustomUserLoginForm class CustomLoginView(LoginView): def get(self, request): form = CustomUserLoginForm() return render(request, "api/test_template.html", context={"form": form}) in my template then, I am calling {{form.as_p}} in <form> tag to show the form input details. However, by default, this shows the username and password forms. How can I replace the username with the email? in the rest-auth, browserable api, both the username and the email are present so I know that I can do this since I am using the rest-auth LoginView as backend. Can I manually unpack {{form}} since later I would still like to style this form. How can I do this? -
Django drf_yasg POST with input parameters produces error - cannot add form parameters when the request has a request body
I'm trying to use Django drf_yasg to create a POST api with input parameters like below: x_param = openapi.Parameter('x', in_=openapi.IN_FORM, description='string', type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) pass however it produces this error in $ python manage.py runserver raise SwaggerGenerationError("cannot add form parameters when the request has a request body; " drf_yasg.errors.SwaggerGenerationError: cannot add form parameters when the request has a request body; did you forget to set an appropriate parser class on the view? How can I solved this ? -
how to specify in django form that we want certain value to be inserted in database via dropdown list
I am trying to save the name of the students in the database. Right now, it is saving the ID of the student instead of the name. I am using django form and i am not sure hw to tell the django form that i want to insert the student name in the database. Below is my forms.py code: class studentAttendanceForm(forms.ModelForm): class Meta: model = MarkAtt fields = ['studName'] def __init__(self,*args, **kwargs): class_group = kwargs.pop('class_group') super(studentAttendanceForm, self).__init__(*args,**kwargs) self.fields['studName'].label = "Select your name:" self.fields['studName'].queryset = Namelist.objects.filter(classGrp=class_group) Template: <h6 style=" display: inline;"> Lab Group: {{group.classGrp}} </h6> <h6 style="padding-left:70px; display: inline;">Day: {{group.day}} </h6> <h6 style="padding-left: 70px;display: inline;">Time: {{group.time}} </h6> <h6 style="padding-left: 70px;display: inline;"> Today's date: {{date.today}}</h6> <br> <br> {{ form.as_p }} <button type ="submit" class="btn btn-outline-success" >Mark Attendance</button> right now is saving as: id att studName classId week date 42 1 1 1 0 2019-09-15 i want to save as 42 1 testName 1 0 2019-09-15 -
PYTHON - DJANGO - 'ImageFieldFile' object has no attribute 'replace'
The error message is: AttributeError at /projects/ 'ImageFieldFile' object has no attribute 'replace' Request Method: GET Request URL: http://localhost:8000/projects/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'ImageFieldFile' object has no attribute 'replace' Exception Location: .../js-portfolio/venv/lib/python3.6/site-packages/django/utils/encoding.py in filepath_to_uri, line 252 Python Executable: .../js-portfolio/venv/bin/python Python Version: 3.6.8 Python Path: ['.../js-portfolio', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '.../js-portfolio/venv/lib/python3.6/site-packages'] I have a Project MODEL, that takes an image. I added the model to my admin page, and I created an object from admin and can add an image no problem. The problem happens when I try to display my views. I am not even making a reference to the image in base.html. I have been stuck on this for hours, so I figured it's time to get some help. Any hints would be greatly appreciated. Thanks! My Project model(models.py): from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.ImageField(default='default.jpg', upload_to='img') def __str__(self): return self.title My settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' base.html: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="{% url 'project_index' %}">JS Portfolio</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> … -
Django how to use request data as form in an html template
I am using Django rest framework rest-auth for login and sign up. But I do not want to use the browseable API as my UI. I am building my own form. so I am using a custom login url like so: path('rest-auth/customlogin', CustomLoginView.as_view(), name='rest_login'), where CustomLoginView is defined as : class CustomLoginView(LoginView): def get(self, request): return render(request, "api/test_template.html") now in test_template.html, I would like to have 2 input fields: email and password. the same fields that are shown in the browserable API if I did not overwrite with the template. I am not sure how to get the request data into the template. (if email and password fields reside in the request data, is this correct?) test_template.html {% block content %} <div class="row"> <h3>Login</h3><hr/> {# I am not sure how to use input fields here where the data inputted goes in the email and password rest-auth fields#} </div> {% endblock %} -
Django background task set Creator content type and creator content id
Using "Django Background Tasks" module. It just set schedule time. Need to set content type and id. @background(schedule=60) def notify_user(user_id): # lookup user by id and send them a message user = User.objects.get(pk=user_id) user.email_user('Here is a notification', 'You have been notified') How to do that -
How to use parse_qs in redirecting from view to another?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. You can check the actual project in applypro.co and applypro.co/programs . please see that how get and … -
Please help - converting html5 into Django2.2.5 template, all worked except JS based img carousel that accepts URL as input parameter
I'm trying to convert an html5 code into django template, using best practices, such as {% static 'url/img.jpg' %} but the function is not getting triggered. I'm not very strong at JS or at css3 transitions. (Below is the actual HTML code that works correctly, calls javascript function and creates a sliding slider gallery): <section id="main-slider"> <div class="owl-carousel"> <div class="item" style="background-image: url(images/slider/bg1.jpg);"> <div class="slider-inner"> </div> </div> <!--/.item--> <div class="item" style="background-image: url(images/slider/bg2.jpg);"> <div class="slider-inner"> </div> </div> <!--/.item--> </div> <!--/.owl-carousel--> </section> (After converting to django template, the code looks like this): (So, the part of the code that successfully resolves into url is this: So, the structure is correct. The original template can be seen at this url: https://themehunt.com/item/1524960-multi-free-responsive-onepage-html-template and the javascript responsible for this image carousel is here: demo.themeum.com/html/multi/js/owl.carousel.min.js So the browser just doesn't show the section with images at all. -
how to add hyperlink href in pandas dataframe table when calling to_html() method using django template
i am using pandas dataframe to pass table to django template html , my python code : def my_get_method(request): q = "SELECT id,data from table" df = pd.read_sql(q,connection) df['id'] = df_products['id'].apply(lambda x: '<a target="_blank" href=' '"https://link_to.com/manage/inside_my_website/{id}/">{id}</a> return render(request,'manage/my_template.html', {'df':df.to_html(index=False,table_id="table-id",escape=False),) my_template.html: ... {% autoescape off %} {{ df }} {% endautoescape %} ... and table does shown but the id column has only one row(where if i don't apply the link it shows multiply rows) and the id is something i don't understand : '); $('input', this).on('keyup change', function () { if (table.column(i).search() !== this.value) { table .column(i) .search(this.value) .draw(); } }); }); var table = $('#table-id').DataTable({ orderCellsTop: true, fixedHeader: true, aLengthMenu: [ [10, 25, 50, 100, 200, -1], [10, 25, 50, 100, 200, "All"] ], iDisplayLength: -1 }); }); and in the python code the link in the dataframe seems ok. -
Converting sqlite db to rest api for android app using django rest framework
I have a sqlite db which consists images and descriptions now how can I create rest api from it using django rest framework. -
How to use form.save(commit=false) with ManyToManytoMany Field
Views.py @login_required def Movies_create(request): form=Create_Movies_form( data=(request.POST), files=(request.FILES or None), ) url=request.path[1:-5] if form.is_valid(): if request.user.is_active: obj = form.save(commit=False) obj.movies_user_id = request.user obj.save() messages.success(request, f'Movies has been created!') else: messages.warning(request, f'Please Login to create movies!') else: print(form.errors) context={ "form":form, "form_name":url } return render(request,'movies_list/list_create.html',context) forms.py class Create_Movies_form(forms.ModelForm): class Meta: model=Movies_list fields=['name','genre','cast','director','writer','awards','country','story_line','cost','release_date','language','imdb_rating','imdb_link','trailer_link','tags','Quality','movies_type',] models.py class Movies_list(models.Model): movies_id=models.AutoField(primary_key=True) name=models.CharField(max_length=50) genre=models.ManyToManyField(Genre_list) cast=models.ManyToManyField(Cast_list) director=models.ManyToManyField(Director_list) writer=models.ManyToManyField(Writer_list) awards=models.ManyToManyField(Award_list) country=models.ForeignKey(Country_list, on_delete=models.PROTECT) story_line=models.TextField(default='') cost=models.PositiveIntegerField(default=0) release_date=models.DateTimeField( blank=False,null=False) created_at=models.DateTimeField(default=timezone.now) language=models.ManyToManyField(Language_list) imdb_rating=models.FloatField() imdb_link=models.TextField() trailer_link=models.TextField() views=models.PositiveIntegerField(default=0) likes=models.PositiveIntegerField(default=0) dislike=models.PositiveIntegerField(default=0) ratting=models.FloatField(default=0.0) tags=models.TextField() Quality=models.ForeignKey(Quality_list,on_delete=models.PROTECT) movies_user_id=models.ForeignKey(User, on_delete=models.PROTECT) movies_type=models.ForeignKey(Movies_type_list,on_delete=models.PROTECT) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural='movies' It work just fine but didn't know why using obj = form.save(commit=False) didn't save ManyToMany modelform field in the sqlite database. It work fine with Foreignkey ,textfield,integerfield,datetimefield. I test it on multiple times to check whether it save the data or not by using update(instance) and template .html file. -
Datetime Field does not displayed on the page?
why does not datetime field error message not display on the page ? validation datetime message error not display on the page like other validation of other clean methods ? at models.py class Todo(models.Model): title = models.CharField(max_length=255) due_date = models.DateTimeField() description = models.TextField(max_length=255) is_done = models.BooleanField(default=False) duedate = models.DateField(default=timezone.now) def __str__(self): return self.title at forms.py class TodoModelForm(forms.ModelForm): class Meta: model = Todo # fields = ['title', 'description', 'due_date'] fields = '__all__' def clean_title(self): print('in title') title = self.cleaned_data['title'] words = title.split() if len(words) > 5: raise ValidationError('Must be Just 5 Words at Max') return self.cleaned_data['title'] def clean_description(self): print('In des') desc = self.cleaned_data['description'] words = desc.split() if len(words) > 5: raise ValidationError('Not Correct') return desc -
DRF, consistent api for foreignkey relations
Suppose you want to show nested data when reading. Also suppose that you want to only allow changing the id of the foreign key. Hence the following definition arises, but the problem is they use the same variable order_case and I get when updating via {"order_case": 477}. ValueError: Cannot assign "477": "OrderCaseRevision.order_case" must be a "OrderCase" instance. class OrderCaseRevisionSerializer(serializers.ModelSerializer): order_case = OrderCaseSerializer(read_only=True) order_case = serializers.IntegerField(write_only=True) I could do the following to mitigate the problem, but I don't like the fact that you usually use foreign key name like order_case to update the foreign key field and here you are making an exception that you have to use order_case_id. class OrderCaseRevisionSerializer(serializers.ModelSerializer): order_case = OrderCaseSerializer(read_only=True) order_case_id = serializers.IntegerField(write_only=True) -
Axios send request twice, 301 and 401 results in Django Rest Framework
I tried to call a REST api endpoint in my Django project. So far its working when using curl, postman. I have the problem when I tried calling it in my django template frontend with Axios. As I inspected network tab, I noticed it calling the api twice, first return 301, sending params and token successfully, and the second request return 401, sending params but not the token. axios.get(url,{headers: {'Authorization': 'Token 0ca677330f947335a72572bdbdfe305ae7dd8ba6'},params:params}) I also noticed the change in url in second request first request(301) - endpoint?param_a=value&param_b=value second request(401) - ?param_a=value&param_v=value I tried to prevent reload by adding modifiers in my form like .prevent, stop, etc nothing works. Any idea? -
Why django go on to clean datetime or date field?
when i use debugger, it does not go on this method, why ? def clean_duedate(self): import datetime date = self.cleaned_data['due_date'] try: date = datetime.datetime.strftime(date, '%m/%d/%Y') except Exception as error: print(error) raise ValidationError('not date') return date -
DRF, how to communicate interface parameters for api endpoints to other programmers?
For instance I have the following endpoint, and want to let our client programmers know that he needs to send email/password1/password2 and he would get UserSerializer format data. How can I effectively let others know the api specification without forcing him to drill down the code? @list_route(methods=['post'], permission_classes=[permissions.AllowAny]) def register(self, request, *args, **kwargs): from django.contrib.auth import get_user_model from django.contrib.auth import login as login_base User = get_user_model() email = request.data.get('email') password1 = request.data.get('password1') password2 = request.data.get('password2') ... user.send_activation_email(request=request) # login_base(request, user) serializer = self.get_serializer(user) return Response(serializer.data) -
Website creation, should I use existing services?
I have some experience with website creation in Django and Wordpress. And I would like to make my first website and deploy it to a webserver. I prefer creating a site from zero, so I know what is where and what should I edit to make changes and so on. So I prefer Django over Wordpress, because I have not so deep-image of the site movements and I'm not very good in php. But when I look at people that knows Django, or other frameworks and despite it their sites are created in Wordpress, I'm little bit confused. Is it because Wordpress is fine-tuned by professionals and makes all that security stuffs for you, so it easier or why? -
Django: forms how to safe gaurd hidden fields from any malicious user modifying
I want to have a form with hidden field and whose value will be initialized. forms.py class SampleForm(forms.Form): email = forms.EmailField(widget=forms.HiddenInput()) otp = forms.CharField(widget=forms.HiddenInput(),help_text='Please Enter valid OTP sent to your Email', label='Otp', max_length=6) in the views.py form= SampleForm(initial={'email': someemail} I want to have email as hidden. When the form is submitted, i will need the email so that i can verify the otp sent to mail and otp entered by user. I heard that some malicious user try to modify the hidden field it when you don't want them to. So what is the best way to save from such situations. -
Django model_mommy model instance isn't saved in Ajax test
I'm trying to test an django ajax view that saves a field. Here's the test: def test_ajax_save_draft(self): sub = mommy.make(QuestSubmission, quest=self.quest2) draft_comment = "Test draft comment" # Send some draft data via the ajax view, which should save it. ajax_data = { 'comment': draft_comment, 'submission_id': sub.id, } self.client.post( reverse('quests:ajax_save_draft'), data=ajax_data, HTTP_X_REQUESTED_WITH='XMLHttpRequest', ) self.assertEqual(draft_comment, sub.draft_text) # sub.draft_text = None, as if the ajax view was never called! And here's the view: @login_required def ajax_save_draft(request): if request.is_ajax() and request.POST: submission_comment = request.POST.get('comment') submission_id = request.POST.get('submission_id') sub = get_object_or_404(QuestSubmission, pk=submission_id) sub.draft_text = submission_comment sub.save() response_data = {} response_data['result'] = 'Draft saved' return HttpResponse( json.dumps(response_data), content_type="application/json" ) else: raise Http404 When I run the test, I get into the if block, and it can retrieve the comment and submission object, but when it returns to the test at the end, it's like it never happened. What am I doing wrong here? -
Django drf_yasg swagger - apiview - how to define POST input param
I am trying to using drf_yasg - swagger to achieve this kind of call: curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' --header 'X-CSRFToken: sM48rRw0j1YHB2mMA9L7c7QPkwBfikHqA3TlNRg2lWtVdO23IHtzgOUjIOoPcZPf' -d 'username=testingdata&password=mypassword' 'http://localhost:8000/api/another' I have attempted this way, but noticed its a query param not a POST input param. x_param = openapi.Parameter('x', openapi.IN_QUERY, description="x param", type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) I believe it should be something to change in this value openapi.IN_QUERY. The question is how to create an API using the following apiview method with drf_yasg to create POST input parameters ? -
django how to redirect url after remove item from cart redirect url
this is my url where I want to redirect after post : path('edit/<int:blerje_id>/produkti/add/', views.add_choice, name="add_choice"), url remove: path('clear/<int:prod_id>/', views.clear, name='clear'), this is my view: def clear(request,prod_id): prod= get_object_or_404(Prod, id=prod_id) prod.delete() return redirect('polls:add_choice', blerje_id=blerje.pk) name 'blerje' is not defined -
TypeError: __init__() missing 1 required positional argument: 'on_delete' (Django Filer, Python3, Django 2)
I need to add the required argument: "on_delete = models.CASCADE" to the following code. Otherwise, I get the following TypeError: TypeError: init() missing 1 required positional argument: 'on_delete'. How and where should I do this? Any help is much appreciated. class FilerFileField(models.ForeignKey): default_form_class = AdminFileFormField default_model_class = File def __init__(self, **kwargs): # We hard-code the `to` argument for ForeignKey.__init__ dfl = get_model_label(self.default_model_class) if "to" in kwargs.keys(): # pragma: no cover old_to = get_model_label(kwargs.pop("to")) if old_to != dfl: msg = "%s can only be a ForeignKey to %s; %s passed" % ( self.__class__.__name__, dfl, old_to ) warnings.warn(msg, SyntaxWarning) kwargs['to'] = dfl super(FilerFileField, self).__init__(**kwargs) def formfield(self, **kwargs): # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = { 'form_class': self.default_form_class, } try: defaults['rel'] = self.remote_field except AttributeError: defaults['rel'] = self.rel defaults.update(kwargs) return super(FilerFileField, self).formfield(**defaults) -
drf-yasg - api_view post - query param - MultiValueDictKeyError
In drf-yasg, I am trying to achieve something simple that I have been doing in django-rest-swagger (now deprecated). x_param = openapi.Parameter('x', openapi.IN_QUERY, description="x param", type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) However, when I try to read the param with x_param = request.POST['x'] It causes this error: MultiValueDictKeyError at /another 'x' As I am migrating Django 1.11 -> 2.2, I'd like to stick to reading param this way (request.POST['x']). Firstly, I'd like to understand what is the problem reading the param and how to solve it. Secondly, if I can stick with request.POST['x'] and what modifications needs to be done for this (as I dont want to break any current API in this migration) By the way, I'ved seen this post, is there anyway to do similar for this issue. https://medium.com/@arjunsinghy96/customised-api-documentation-for-django-rest-framework-projects-using-drf-yasg-d6db9ba5cff3 -
How to create a http url for a json file?
I am an andrroid developer. I need to use some json files created using django in my app as database. For that I need to get a url. But the whole django is in another computer. How do I get a url to access the files on that computer from the android device? I get it that we need to be on the same network. But how? What kind of network? -
Django: Gzip and Whitenoise not compressing
I have a Django app with whitenoise for static files. But when I test the app with Google Lighthouse I get asked to enable text compression for my static .js and .css files. I read a lot of related posts but couldn´t find an answer. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'django_user_agents.middleware.UserAgentMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When testing in Lighthouse, this files are requested to be compressed. They come from the Static folder and I understand they should be compressed when I run Manage.py collectstatic …css/bootstrap.min.css(afternoon-wildwood-39943.herokuapp.com) …js/jquery-3.2.1.min.js(afternoon-wildwood-39943.herokuapp.com) …js/bootstrap-table.min.js(afternoon-wildwood-39943.herokuapp.com) …css/Fran%20Style.css(afternoon-wildwood-39943.herokuapp.com) …js/popper.min.js(afternoon-wildwood-39943.herokuapp.com) Debug setting I read that maybe debug should be set to False to make it work. The example above was done with Debug = True. DEBUG = bool(os.environ.get('DJANGO_DEBUG', True)) The app works fine in this case, but if If turn debug to False, I get and error 500 page. I´m hosting in Heroku. You can try an example in: http://afternoon-wildwood-39943.herokuapp.com/website/ Any clues? Thanks in advance!