Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Styling the custom user registration forms in django
I have created custom user registration. I would like to style them using input placeholders and class names. models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): username=models.CharField(max_length=30, unique=True) email=models.EmailField() password1=models.CharField(max_length=30) highestQualification=models.CharField(max_length=50) def __str__(self): return self.email This is how I want to style my signup.html with the input fields styling and placeholders. <!DOCTYPE html> <html> <head> <style> .container { position: relative; } input{ padding: 12px; border: 1px solid gray; } input:hover{ opacity: 1; } </style> </head> <body> <div class="container"> <form method="post"> <div class="row"> <div class="col"> <input type="text" name="username" placeholder="Username" required> <input type="email" name="email" placeholder="Email" required> <input type="password" name="password1" placeholder="Password" required> <input type="text" name="highestQualification" placeholder="Highest qualification" required> <input type="submit" value="Sign up"> </div> </div> </form> </div> </body> </html> The basic version of the signup form (without styling) looks like this. signup.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block title %}Sign Up{% endblock %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} </head> <body> </body> </html> Wanted to know where to mention the styling class names and placeholders of the input field. -
Multiple render in 1 function in views.py Django?
I am very new to Django... Using submit button i want to run a python file in background and display content on next page... But my python file takes some time to take out the result so in between i wanted to put a loading html page in between.... I have written some code which correctlty runs the python file but i am not able to incorporate the loading page in between... Take a look at my function in views.py def submit(request): info = request.POST['info'] print('value is ', info) filename = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #result = run(['python', filename, info], stdout= PIPE ) return render_to_response("loading.html") run(['python', filename, info], stdout= PIPE ) return render(request, 'python_output.html', context) ACTUAL RESULT: return render_to_response("loading.html") works but then the control does not shifts to run command... I want to run the loading html page and run the python file in background and when python file run finishes it should move to python _output.html page where output is displayed... Expected: Loading page should work and after that control should shift to run command and then it should go to python_output.html page.../ -
django can not recognize # in URL
I am creating a search bar and I want use "#" in my searchbar everything is ok until "%23" is in url but when I change it with "#" view won't get any query string this is for django 2.2.1 my view: class SearchGalleryView(generic.TemplateView): ... def get_context_data(self,*args,**kwargs): print(self.request.GET) first url: http://localhost:8000/gallery/search/?gallery_search=%23sometag first result: <QueryDict: {'gallery_search': ['#sometag']}> second url: http://localhost:8000/gallery/search/?gallery_search=#sometag second result: <QueryDict: {'gallery_search': ['']}> -
Django Leave Management System
I'm trying to make a Django Leave Management System, in which each user can login and apply for leave and receive an email notification about it's approval or rejection. The admin has the option to alter the profiles, accept and reject and may stop someone from applying for leaves. I want you guys to look through my code and tell me if I am going on the right path and help me out with some models and code. Also in request leave I want to pass the request along with the current logged in user through forms. and how can I use the email option to send and receive emails. Thanks in advance Views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from .forms import Leave_Form, RegistrationForm, userReg_Form # Form Name from . models import Employee, Leave # Class Name from django.shortcuts import render, redirect, render_to_response from django.contrib import messages from django.contrib.auth import login, logout, authenticate, update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm, UserCreationForm from django.http import HttpResponseRedirect, JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.utils.translation import ugettext as _ def home(request): # To view contents of the home page return render(request, "projectfiles/HomePage.html") @login_required(login_url='LoginPage') def request_leave(request): form = … -
How can I manage forms with ForeignKey and ManytoMany Relation
I have one model with ManytoMany relation chained with a ForeignKey. I want a CreateView, How can I get chained choices or something better thant the generic form ? The problem with the generic form, is that I get all the "Need[NeedValue]" options. class Project(models.Model): [....] needs = models.ManyToManyField("NeedValue", related_name="project_item") class NeedValue(models.Model): [....] attribute = models.ForeignKey('Need', verbose_name="Unité", on_delete=models.CASCADE) class Need(models.Model): [....] name = models.CharField(max_length=100) I mean, I my example, When I create a Project, I want to choose one need, and then one value linked to the need. Or maybe, list all the Needs (with a {% For %}) and ask for the values. -
Django Simple History - History Diffing
So I'm using django-simple-history for one of my projects. I'm using it on one of the models called "Address" to show the history of the records. I've created a DetailView to show the information about the address and added context['history'] to show changes of the record. This works all fine. I would be interested in what field changed, and I read the following; History Diffing So I somehow need to loop through all the fields from the last two records and find the field which has changed... I couldn't find any examples on how to achieve this so I tried adding the context to the view #views.py class Address(DetailView): ''' Show details about the address ''' model = Address ''' Add history context to the view and show latest changed field ''' def get_context_data(self, **kwargs): context = super(Address, self).get_context_data(**kwargs) qry = Address.history.filter(id=self.kwargs['pk']) new_record = qry.first() old_record = qry.first().prev_record context['history'] = qry context['history_delta'] = new_record.diff_against(old_record) return context And a simple model #models.py class Address(models.Model) name = models.CharField(max_length=200) street = models.CharField(max_length=200) street_number = models.CharField(max_length=4) city = models.CharField(max_length=200) Template #address_detail.html <table> <thead> <tr> <th scope="col">Timestamp</th> <th scope="col">Note</th> <th scope="col">Edited by</th> </tr> </thead> <tbody> {% for history in history %} <tr> <td>{{ history.history_date }}</td> … -
Django startapp workflow with docker
I am confused with how to work with Django apps (create/using) when using Docker. Some of the tutorials suggest using command startapp after starting the web docker container (I'm using docker-compose to up the containers). But since the files are created inside that container, how do I go about adding code to that from my local dev machine? and moreover, this does not seem right to create apps like this to edit code... I've been using this following structure as is so far which starts up the container and works fine. But with just one "app" which is todo (taken from https://github.com/realpython/dockerizing-django) . ├── README.md ├── docker-compose.yml ├── nginx │ ├── Dockerfile │ └── sites-enabled │ └── django_project ├── production.yml ├── tmp.json └── web ├── Dockerfile ├── Pipfile ├── Pipfile.lock ├── docker_django │ ├── __init__.py │ ├── apps │ │ ├── __init__.py │ │ └── todo │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── models.py │ │ ├── static │ │ │ └── main.css │ │ ├── templates │ │ │ ├── _base.html │ │ │ ├── dashboard.html │ │ │ └── home.html │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── … -
Possible to compose a large transaction in Django then commit to DB later?
I have a long set of model creations which are going slowly due to remote DB access. Is it possible to set some kind of transaction start and end and then commit? -
how to fix no null contraint in django
am creating a user using onetoone relationship , when i want to enter data in the form and submit , i get no null constraint error view.py def registerUser(request): if request.method=='POST': form=UserCreationForm(request.POST) form_class=ProfileForm(request.POST) if form.is_valid() and form_class.is_valid(): form.save() form_class.save() return redirect('/home/') else: form=UserCreationForm() form_class = ProfileForm() return render(request,'register.html', {'form':form,'form_class':form_class}) form.py class Registerform(UserCreationForm): class Meta: model=User fields= ['username','first_name','last_name','password1','password2'] def save(self, commit=True): user=super(Registerform, self).save(commit=False) user.first_name=self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() return user class ProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = [ 'location'] models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) salary=models.CharField(max_length=120) def __str__(self): return self.location -
How to allow Nginx with iptables (django)
I am making a site with django so I followed this tutorial but I have an error in /var/log/nginx/error.log when I type my domain name in browser (502 bad gateway): 2019/05/15 11:13:05 [error] 1860#1860: *12 connect() to unix:/home/username/MYPROJECT/myproject.sock failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx, server: myproject.net, request: "GET / HTTP/1.1", upstream: "http://unix:/home/username/MYPROJECT/myproject.sock:/", host: "myproject.net" I think the problem is because my iptables rules block nginx. So my question is: What is the IPTABLES equivalent of ufw allow 'Nginx Full' ? -
Dajngo: How to add a user as a foriegn key in a model
I am new to Django. I want to add user as a foreign key in the manager model and i have no idea how can i do this. this is my manager model class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) I have to add user as a foreign key in the manager. -
I wanto copy text in tag in list with js
step 1 get id form button step 2 copy text in td for same id codepen) https://codepen.io/terecal/pen/LoxmbP?editors=1010 <table> <tr> <td>code</td> <td colspan="122" id="my_code_{{comment.id}}"> hello world </td> </tr> </table> js $(".copy_code").click(function(e){ e.preventDefault(); var id = this.id alert("id : ", id) // var copyText = document.getElementById("my_code"); // copyText.select(); // document.execCommand("copy"); // alert("Copied the text: " + copyText.value); }); is it possible? -
i have problem with css in django ,css affect don't show in browser
i'm new in django i have no errors in code but css affect don't show in browser this my codes and my project folders this is base.html <!DOCTYPE html> {% load static %} <html lang ="en"> <head> <title>Investissement | Home</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap /4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/ iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" herf="{% static 'css/styles.css' %}"> </head> <body>..... this is home.html {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> <div class="col"> <div id="home-content"> <h1>Investissement @2019</h1> <h3>Your voice Matter!</h3> </div> </div> </div> </div> {% endblock %} this is styles.css h1 { color :red; } body{ background-image: url('../img/p.jpg'); } #home-content { text-align:left; padding-top:20%; } in settings file i do this : # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL =' /static/' STATIC_ROOT = "/home/p-amc-dgps-er/Bureau/investissement/static/" STATICFILES_DIRS =[os.path.join(BASE_DIR, "static"),] note: the static folder and templates are in same repertory with manage.py the result no css affect are show and no code error -
How to call a model route (inheriting from RoutablePageMixin) withing another model?
I have two models Foo and Bar: class Foo(RoutablePageMixin, Page): . . @route(r'^(?P<regex>[-\w]+)/$', name='route_one') def route_one(self, request, regex, *args, **kwargs): class Bar(RoutablePageMixin, Page): . . @route(r'^(?P<regex>[-\w]+)/$', name='route_two') def route_two(self, request, regex, *args, **kwargs): within route_one i want to call route_two how this can be done? I already checked the wagtail docs but i couldn't figure out how this can be done. -
how to login with email/username in django?
Here i want to login user with email or username and password combination.I have write this code.But this code is not working properly.It is only working for username and password.How can i enable email feature while sign in with this code.Can anyone help me to edit this code ? views.py def loginuser(request): if request.method == "POST": form = LoginForm(request.POST) username = form['username'].value() password = form['password'].value() user = authenticate(username=username, password=password) if user and user.is_superuser: login(request, user) redirect_url = request.GET.get('next', 'students:home') messages.info(request, 'You are logged in as an admin .') return redirect(redirect_url) elif user and user.is_staff: login(request, user) redirect_url = request.GET.get('next', 'students:home') messages.info(request, 'You are logged in as a staff member.') return redirect(redirect_url) elif user and not user.is_active: messages.info(request, 'Your account is not active.') else: messages.error(request,'Invalid Username and Password') else: form = LoginForm() return render(request, 'students/login.html', {'form': form}) forms.py class RegisterForm(UserCreationForm): def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError('Email Already Exists') return email class Meta: model = User fields = ['username', "email", "password1", "password2",'is_superuser','is_staff','is_active'] class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) template <form method="post" class="form-signin"> {% csrf_token %} Username or Email:<input type="text" name="username" class="form-control mb-2" placeholder="Username or Email" > Password:<input type="password" name="password" class="form-control mb-2" placeholder="Password" > <button class="btn btn-lg btn-primary … -
Django : 'QuerySet' object has no attribute 'group_by'
I want to make this query to django SELECT * FROM diagnosis_penyakit_gejala where id_organ = 1 group by gejala and i make it to django like this queryset = Gejala.objects.all().filter(id_organ=1).group_by('gejala') and returned error 'QuerySet' object has no attribute 'group_by' Why this happen? And anyone can help me to solve this? My Gejala model structure class Gejala(models.Model): penyakit_id = models.IntegerField() gejala = models.CharField(max_length=150) id_organ = models.IntegerField(null=False) status = models.CharField(max_length=150, default='Tetap') def get_absolute_url(self): return reverse('gejala:gejala_detail', kwargs={'pk':self.pk}) def __str__(self): return self.gejala I am newbie in Django. Hope anyone can help me -
What is the cause of the error NoReverseMatch
I make a basket on my site, each product should have a button to add to the basket, it is there until I use {% url 'add_cart' product_headline = product.headline%} in the template, otherwise it gives an error Reverse for 'add_cart' with keyword arguments '{' product_headline ':' Lord Rings '}' not found. I am a beginner in yes and on the web too. Explain why it happens and if so how it works[enter image description h[ere][1]1 enter image description here -
How to set objects unique for each User in django?
i have a question about django-models that how i can set field to unique=True of Table in django for each User. I have Table Token below, and when i added new token, it't auto create tokenprofile by signals django built-in, i want to unique uid of ProfileToken for each User. Show me how. Thanks from django.db import models from accounts.models import CustomeUser from django.db.models.signals import post_save import facebook # Create your models here. class Token(models.Model): access_token = models.CharField(max_length=255) user = models.ForeignKey(CustomeUser, related_name='tokens', on_delete=models.CASCADE) def __str__(self): return self.access_token class TokenProfile(models.Model): token = models.OneToOneField(Token, on_delete=models.CASCADE) name = models.CharField(max_length=50) uid = models.CharField(max_length=50, unique=False) profile_picture_link = models.CharField(max_length=255) profile_link = models.CharField(max_length=255) def __str__(self): return '{0} - {1}'.format(self.name, self.uid) def create_profile_token(sender, instance, created, **kwargs): if created: access_token = instance.access_token graph = facebook.GraphAPI(access_token=access_token) info = graph.get_object('me') name = info['name'] uid = info['id'] profile_picture_link = 'https://graph.facebook.com/v3.1/{0}/picture?type=small&amp;redirect=true'.format(uid) profile_link = 'https://www.facebook.com/{0}'.format(uid) profile_token = TokenProfile.objects.create(token=instance, name=name, uid=uid, profile_picture_link=profile_picture_link, profile_link=profile_link) post_save.connect(create_profile_token, sender=Token) -
Django viewset action does not see request's added data in the middleware
I have a very strange problem. I have written a middleware which patches a request object with custom property. And it works perfectly in the whole project except 1 action. Here they are: Middleware: class AssignSelectedProfileMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): headers = request.META if not request.user.is_anonymous: if headers.get(HEADER_PROFILE): profile = Profile.objects.filter(pk=headers.get(HEADER_PROFILE), archived=False, user=request.user).first() else: profile = Profile.objects.filter(user=request.user).first() if not profile: raise MyProfileAuthorizationError("You are not allowed to use this profile.") setattr(request.user, "profile", profile) response = self.get_response(request) return response Action: @action( methods=['get', 'patch'], detail=False, permission_classes=(IsAuthenticated,), serializer_class=SafeProfileSerializer, ) def me(self, request): return Response(self.get_serializer(self.request.user.profile).data, status.HTTP_200_OK) When I make a response - I see that request is patched successfully in the middleware, Profile object exists, but when I debug request in the view - self.request.user.profile throws AttributeError: 'User' object has no attribute 'profile'. Note - another actions in the save viewset work perfectly and user.profile exists. Why this happens? -
How can I connect myself as an other user?
Hello I am a developper of a django project and I have to check that my dev is okay. To do this, I have to connect myself as a user but I have just his email not his password. I found in the table User this the email and the password but the passwotrd begins by this : pbkdf2_sha256 ... So I guess the password is encrypted. Is there a way easier to do this ? Thank you for your help ! -
How to use django template {% load static %} in html passed in url parameter of ajax request using javascript
I am loading new_question_element.html from Ajax request on button click in Django. How should i use the {% load static %} functioning in the loaded HTML. I have tried passing the {% load static %} tag in the new_question_element.html and tried to call the {% static "image path" %} but it is not processing the tags. It is working fine on calling from Django urls but it is not working on calling from Ajax request in java script external file which i have loaded in my index.html index.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> ... ... <script src="{% static 'letssurvey/test/vendor/script.js' %}"></script> </body> </html> script.js $(document).on('click','.j_add-new-question-btn',function(){ $.ajax({ type: "GET", url: "Path to new_question_element.html", success: function(data) { new_question_area.html(data); new_question_area.find(".j_new-question-number").text(g_question_number); add_btn.fadeOut(); } }); }); new_question_element.html {% load static %} .... .... <button class="col-xs-12 bg-subtle text-color question-type--button text-center qtype-item waves-init-wrapper j_select-element-type select-type" id="ele_single_choice_id" data-name="Single Choice"> <div class="pointer d-flex align-items-center justify-content-between"> <div class="lv-title d-flex align-items-center"> <div class="question-type--icon vertical-align"> <img src="{% static 'data/image/mcq_single.svg' %} alt="Single Choice" class="qtype-icon"> <i class="fa fa-spinner fa-spin"></i> </div> <div class="question-type--title--wrapper"> <span title="" class="question-type--title"> <span class="m-b-0">Single Choice</span> <span class="text-muted text-sm"> </span> </span> </div> </div> </div> </button> The template is rendering and everything is working but the src attribute of the … -
how to remove multiple tuples from a template
I try to delete several data presented in database using the checkboxes from a template. I have a table where after checking the items, I pass them to a "supprimer_ue" view. My table is out of the form, will it cause problems at the time of validation? how to pass a list of items to a view to delete them? Here is code: # Views # La view qui supprime les UE def supprimer_ue(request, code): ue = get_object_or_404(UE, code_ue=code); ue.delete(); return redirect('liste_ue', filiere=request.session.get('filiere')); # template <form class="form-inline" action="{% url 'supprimer_uue code=ue.code_ue %}" method="post"> <div class="form-group mx-sm-3 mb-2"> <label for="action">Action : </label> <select name="matricules" id="matricules" class="form-control"> <option value="rien">----------</option> <option value="supprimer">Supprimer les UEs sélectionner</option> </select> </div> <button type="submit" class="btn btn-primary mb-2">Envoyer</button> </form> </br> <table class="table table-striped"> <caption class="">Liste des UEs de la filière {{ filiere }}</caption> <thead> <!-- En-tête du tableau --> <tr> <th><input type="checkbox" id="checkall"/></th> <th>Code</th> <th>Intitulé</th> <th>Type</th> <th>Niveau</th> <th>Filière</th> <th>Semestre</th> <th> </th> <th> </th> </tr> </thead> <tbody> <!-- Corps du tableau --> {% for ue in ues %} <tr> <th><input type="checkbox" class="checkbox" value=ue.code_ue/></th> <td>{{ ue.code_ue }}</td> <td>{{ ue.intitule_ue }}</td> <td>{{ ue.type_ue }}</td> <td>{{ ue.niveau }}</td> <td>{{ ue.filiere }}</td> <td>{{ ue.semestre }}</td> <td><a href="{% url 'supprimer_ue' code=ue.code_ue %}">Supprimer</a></td> <td><a href="{% url … -
django-celery receive task but do not excute it
I'm using django-celery library, it's receive tasks probably but when I read the log its show me this message every time it's receive the task. [2019-05-15 07:43:25,408: INFO/Beat] Writing entries... [2019-05-15 07:46:30,327: INFO/Beat] Writing entries... [2019-05-15 07:49:35,245: INFO/Beat] Writing entries... [2019-05-15 07:52:40,155: INFO/Beat] Writing entries... [2019-05-15 07:55:45,065: INFO/Beat] Writing entries... [2019-05-15 07:58:49,967: INFO/Beat] Writing entries... [2019-05-15 08:01:54,891: INFO/Beat] Writing entries... [2019-05-15 08:04:59,804: INFO/Beat] Writing entries... [2019-05-15 08:08:04,720: INFO/Beat] Writing entries... after search on internet no useful solutions I found, can some body guess what is the reason of this message and why it appear when the queue is arrived ? -
How to send/receive json using restful API in Django
I've been trying to get my head around this, What I intend to do is create a simple restful-api in django that will accept and send a response in JSON. What I've tried: Index.html: <select id = "some-list"> <option value="" disabled="disabled" selected="selected">Please select an item</option> <option value = "1">L 1</option> <option value = "2">L 2</option> </select> <script type="text/javascript"> $("#some-list").on("change", function(){ var selectedValue = $(this).val(); alert(selectedValue) $.ajax({ url : "someSelect/", type : "POST", data : {"name" : selectedValue}, contentType: "application/x-www-form-urlencoded", success : function(){ console.log('Success'); }, error : function() { console.log('Failure'); } }); }); </script> urls.py: path(r'^someSelect/', some_select_handler), views.py # @api_view(["POST"]) @csrf_exempt def some_select_handler(request): if request.is_ajax(): some_id = request.POST["name"] print(questionnaire_id) else: print("Not ajax req") some_id = request.POST["name"] # return JsonResponse("The request was not an AJAX call", safe=False) return render(request, 'Index.html', context) Problem: I gave the csrf in the AJAX and it worked okay in the web but not in the Postman, exempted it and it throws erro: Forbidden: /someSelect/ What I am looking for: I only intend to understand where am I messing up: Trying to send a value from dropdown to a method via restful API Upon some manipulation a JSON response is sent back Repeat until a response that I … -
getting list of company along with employee count from another model
I have two model Company and Employee and have to display records like below Company Name, Number of Employee ```python class Company(models.Model): name=models.CharField(max_length=20) est=models.IntegerField(max_length=4) class employee(models.Model): name=models.CharField(max_length=20) company=models.ForeignKey(Company) ``` How to write Django ORM Model to fetch the detail ?