Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SyntaxError: f-string expression part cannot include a backslash
I have this api call. payload = "{\\"weight\\":{\\"value\\":\\"85.00\\",\\"unit\":\\"kg\\"},\\"height\\":{\\"value\\":\\"170.00\\",\\"unit\\":\\"cm\\"},\\"sex\\":\\"m\\",\\"age\\":\\"24\\",\\"waist\\":\\"34.00\\",\\"hip\\":\\"40.00\\"}" I want to use a f string to change those values but I get a syntax error saying I can't use backslash for f strings. What can I do? -
How to replicate Django auth.admin groups and permissions admin page forms?
Anyone know how I can create a form with the exact M2M form used in the admin page for the auth.user model where it has two multiple select boxes with right and left arrows and a search filter for the left select box? Any help is much appreciated! -
Many-To-Many - Too much data in admin page
My authors can have pseudonyms so I added a Many-To-Many relationship. class Name(models.Model): name = models.CharField(max_length=30, unique=True) ... class Author(models.Model): name = models.ManyToManyField(Name) sex = models.CharField(max_length=6, choices=[('m', 'male'),('f', 'female')]) birthday = models.DateField() birthplace = models.CharField(max_length=30) .... After adding many names it quickly becomes cumbersome to scroll and select through thousands of names when adding new author datasets via the admin page. Is there a better way to design the model, so that I can just add those few pseudonyms without this hassle? -
python: 'bool' object is not callable
C:\Users\Republic Of Computer\Desktop\Cirriculum\CvMaker\home\decorators.py, line 6, in wrapper_func from django.shortcuts import redirect def notLoggedUsers(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated(): … return redirect('candidat') else: return view_func (request, *args, **kwargs) return wrapper_func -
Django: Obtaining a QuerySet from a model of two OneToOne fields
I have the following set of models: from django.db import models from django.db.models import CASCADE class Battle(models.Model): idBat = models.UUIDField(primary_key=True) # other attributes... class Participant(models.Model): idPar = models.UUIDField(primary_key=True) # other attributes... class Event(models.Model): participant1 = models.OneToOneField(Participant, CASCADE, related_name='%(class)s_par1') participant2 = models.OneToOneField(Participant, CASCADE, related_name='%(class)s_par2') battle = models.ForeignKey(Battle, CASCADE, related_name="%(class)s_battle") # other atributes... However from a view I wish to get all Participants from a said Battle I obtained from a form. As such, I know I can obtain all Events from a Battle in this way: battle = form.cleaned_data['selected_battle'] events = battle.event_set participants = # now what?? As seen above I don't know how to correctly obtain said participants from each event of the battle. To be clear I can guarantee there will be repeated participants since an event consists of a fight between participant1/2 where one of them kills the other, and a battle is a succesion of said events until one participant remains victoriuos, thus every survivor of an event will appear again in another event in the battle. I wish to obtain all participants without said repetitions and possibly reorder and slice them using QuerySet.order_by(...)[0:N], hence the mention of QuerySet in the title. -
Django REST permission classes don't work together inside an OR but work as expected independently
I'm having troubles putting two permissions together using an OR operator. The documentation says: Doc Provided they inherit from rest_framework.permissions.BasePermission, permissions can be composed using standard Python bitwise operators. For example, IsAuthenticatedOrReadOnly could be written: ... permission_classes = [IsAuthenticated|ReadOnly] So I have created the permissions: permissions.py class IsFullUserOrReadOnly(permissions.BasePermission): """ This class defines the permission to only allow the request to certain users with a certain role.""" def has_permission(self, request, view): """ This function overrides the default has_permission method to allow the writing methods only to full users or admin users """ if request.method in permissions.SAFE_METHODS: return True is_full_user = False queryset = User.objects.get(email=request.user) if queryset: user = UserSerializer(queryset) if 'roles' in user.data: for role in user.data['roles']: if role == ADMIN or role == FULL_USER: is_full_user = True print('IsFullUserOrReadOnly') print(is_full_user) print(request.method) print(request.method =='POST') return is_full_user or request.method =='POST' class IsOwnerOrReadOnly(permissions.BasePermission): """ This class defines the permission to only allow the POST and PUT methods to the creator of the item.""" def has_object_permission(self, request, view, obj): """ This function overrides the default has_object_permission method to allow the writing methods to the owner of the object """ if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `created_by`. print('IsOwnerOrReadOnly') print(obj.created_by … -
Django print different user profile page from the current connected profile
I have a problem with my code. I would like to add the possibility to access to another profile page. I think my problem is in my html page. what i'm doing is {% with profile=user.profile %} but what i want is showing the profile page corresponding with the username described in the url. For example, if the url contains "profile/toto.html" it will give me the profile page of toto. With my current code, whatever username i put in the url, it shows my own profile page :( Can anyone help me please ? -
Google calendar in Django
I'm a nobbie in Django (actually i'm a nobbie in code) and i've a question for anyone who can help me. I want to create a event in Html input (type="datetime") and send it to my google calendar. With the quickstart of Google Calendar I made it, but only with Static data, hardcoded in the code. I've already search and found a lot of guides but any of them shows how to send dynamic data from my template to the calendar. from datetime import timedelta import pytz from googleapiclient.discovery import build from oauth2client.service_account import ServiceAccountCredentials service_account_email = "INSERT_HERE" SCOPES = ["https://www.googleapis.com/auth/calendar"] credentials = ServiceAccountCredentials.from_json_keyfile_name( filename="FILENAME.json", scopes=SCOPES ) def build_service(): service = build("calendar", "v3", credentials=credentials) return service def create_event(): service = build_service() start_datetime = datetime.datetime.now(tz=pytz.utc) event = ( service.events() .insert( calendarId="CALENDARID@group.calendar.google.com", body={ "summary": "Foo", "description": "Bar", "start": {"dateTime": start_datetime.isoformat()}, "end": { "dateTime": (start_datetime + timedelta(minutes=15)).isoformat() }, }, ) .execute() ) print(event) create_event() With this code when i run it in the console the event was created, but now i don't know how render this in the input (datetime, text, etc). Any help will be nice. :) -
Creating form-level error in views.py for formset
I've got the following formset. Within views.py, i'd like to assign an error to one of the forms in the formset. I haven't been able to figure out how to do this EmployeeTeamFormset = modelformset_factory(EmployeeTeamMembership, form=EmployeeTeamForm, extra=0, max_num=10, can_delete=True) formset = EmployeeTeamFormset(request.POST or None, queryset=EmployeeTeamMembership.objects.filter(employee__user=user, team=team), form_kwargs={'user': user, 'team': team}) if request.method == 'POST': if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: #if some condition, assign error to form field -
Wagtail - How to add multiple blogs?
I want to create multiple blogs on same Wagtail Project. Currently I am using https://pypi.org/project/wagtail-blog/ ...and I want the same app in same project for 3-4 times. Like Blog 1 Blog 2 Blog 3 and so on.. How to achieve this ? -
Handle non-submit input types in django
Okay so I have two input tags with types as buttons. <div class="buttons-for-trade-or-sell" style="display: flex; position:relative;left: 33px; top:14px"> <div class="button-to-trade"> <input type="button" class="trade-btn" id="button-to-select-trade" name="trade1" value="Trade"></input> </div> <div class="button-to-sell"> <input type="button" class="sell-btn" id="button-to-select-sell" name= "trade2" value="Sell"></input> </div> My problem is how do I send to the server side code which button is selected. For example, if the trade-btn is selected i want the boolean to be set to true in my view. Then from there I would handle it accordingly. Basically, how do I send which button is selected to the server-side? Thanks. -
How to show in Django queryset dict-key and -values seperately in template?
I have the this output in the browser from HTML template: {'coin__name': 'Bitcoin', 'total': Decimal('1498824')} {'coin__name': 'Ripple', 'total': Decimal('335227')} How can I show in an html template separately the key and the value(without saying Decimal)? Desired outcome: Bitcoin, 1498824 Ripple , 335227 I provide the query and the html template below: views.py: test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total') template.html <table class="table table-striped"> <tr> <th>Current dict pair</th> <th>Just the name of the crypto</th> <th>Just the price of the crypto</th> </tr> {% for item in test %} <tr> <td>{{ item }}</td> <td>{{ }}</td> <td>{{ }}</td> </tr> {% endfor %} -
Creating Model of Users and Posts Django
I am trying to learn Django by creating something similar to Reddit. I have models for Post and User, and now I want to create one for "Community". I have looked at this post: How to store an array of users in django? However, I am unsure if the ManyToMany relationship is right here (perhaps it is). I want the Community Model to contain Posts and Users registered with the Community. Each Community can have many posts, and each user can belong to multiple communities. When a Community is deleted, only delete the posts in that community, not the users. Similarly, when a User is deleted or a Post deleted, just remove that aspect from the Community. If anyone has done this before or knows of a resource to learn this please let me know. -
Django DRF test API with extra configuration
I have a question about app testing with django DRF. I have this url with an extra argument. url(r"^api/search/$", views.ApiSearch.as_view(parameter=True), name="search") I'm building its test but now I need to pass that argument as False. I'm trying something like this: url = reverse("search", kwargs={"parameter": False}) But this is not working, since kwargs pass parameters on url. Anyone have any idea of how that extra configuration or extra parameter is called, and how do I test it? -
ImproperlyConfigured DetailView is missing a QuerySet
I'm trying to use a generic DetailView for my model and I'm getting the error: ClassroomDetailView is missing a QuerySet. Define ClassroomDetailView.model, ClassroomDetailView.queryset, or override ClassroomDetailView.get_queryset(). I've seen other people with a similar error and the solution is typically that their url pattern didn't properly reference their view name. I can't find any typos like that for mine though. My understanding is that the generic DetailView does not require a querset. models.py class Classroom(models.Model): classroom_name = models.CharField(max_length=10) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.classroom_name views.py class ClassroomDetailView(generic.DetailView): model: Classroom urls.py app_name = 'gradebook' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('signup/', SignUpView.as_view(), name='signup'), path('courses/', views.courses, name='courses'), path('classroom/', views.classroom, name='classroom'), path('classroom/<int:pk>/', views.ClassroomDetailView.as_view(), name='classdetail'), path('addstudent/<int:classroom_id>/', views.addstudent, name='addstudent'), path('addmultistudent/<int:classroom_id>/', views.addmultistudent, name='addmultistudent'), path('objective/<int:course_id>/', views.addobjective, name='addobjective'), path('addassessment/<int:course_id>/', views.addassessment, name='addassessment'), ] -
How to use a different unique identifier of Django ForeignKey field in ModelForm
I have the following Models: class Book(models.Model): name = models.CharField(max_length=128) isbn = models.CharField(max_length=13, unique=True) available = models.BooleanField(default=True) class Borrow(models.Model): date = models.DateTimeField(auto_now_add=True) book = models.ForeignKey(Book) and the following ModelForm: class CreateBorrowForm(forms.ModelForm): class Meta: model = Borrow fields = ['book'] def clean_book(self): book = self.cleaned_data['book'] try: return Book.objects.get(id=book, available=True) except Book.DoesNotExist: raise ValidationError('Book does not exist or it is unavailable') I would like to have a form that expects the isbn field of the Book model, instead of id. As the isbn field is unique, it does make sense. In the clean_book method I would need to do a little change to have the following line: return Book.objects.get(isbn=book, available=True) The problem is that I cannot find an approach to force the form to use a different unique identifier. In my specific case, this is required to avoid brute force enumerating over numerical IDs. -
I tried to iterate a nested dictionary with another dictionary in another definition and Django does not render it
My template receives following the nested dictionary of general projects list with another dictionary of tags in another definition, together with a definition of a page view: from django.views import View class ProjectsView(Mixin, View): def get(self, request, id = None, *args, **kwargs): template = "pages/projects.html" context = { 'title': "Projetos", } return render(request, template, context) def general_projects_list(self, request, id = None, *args, **kwargs): template = "pages/projects.html" projects = { 0: { "Name": "Suru++ Pastas", "Description": "Um executável em Bash de Unix e de BSD para substituir a cor das pastas dos temas de ícones Adwaita++, Suru++ e Yaru++", "Colaboration": "Clonei o projeto o qual desenvolvi a fim de torná-lo compatível com os temas de ícones", "Link": "https://github.com/gusbemacbe/suru-plus-folders", "Tags": ["Makefile", "Shell"] }, 1: { "Name": "Icons Missing Request", "Description": "Um executável que lê o tema de ícone utilizado e os arquivos de desktop de Linux para localizar se os ícones dos arquivos de desktop não existem no tema de ícone e gera uma lista de solicitação de ícones perdidos", "Colaboration": "Colaborei com o projeto, traduzindo o executável em diversas línguas estrangeiras para facilitar os usuários não familiares com a língua inglesa no terminal", "Link": "https://github.com/gusbemacbe/icons-missing-script", "Tags": ["Shell", "Vala"] }, 2: { … -
How to add a functional contact form at my home page in django by using {% include %} or any other method?
I am fairly new at django and i'm trying to make a blog website. I want the blogsite to have a contact page in it so users can send email to the author. I created a contact.html and made a contact function in views and added the path in urls.py (/contact.html). If I go to (/contact.html) and fill the form it works as intended and sends the email. But when I use the {%include %} tag and add it to my homepage it stops working from home and submitting the form doesn't do anything. contact.html: {% if message_name %} <h1>{{ message_name }} Your message has been submitted. We will get back to you soon..</h1> {% else %} <form action="#" method="POST"> {% csrf_token %} <input type="text" name='message-name' placeholder="Your Name"><br><br> <input type="text" name='message-lname' placeholder="Your Name"><br><br> <input type="email" name='message-email' placeholder="Your Email"><br><br> <textarea name='message' placeholder="Your Message"></textarea> <br/><br/><br/> <button type="submit">Send Message</button> <br><br><br> </form> {% endif %} views.py: def contact(request): if request.method == 'POST': message_name = request.POST['message-name'] message_lname = request.POST['message-lname'] message_email = request.POST['message-email'] message = request.POST['message'] #send mail send_mail( 'message from ' + message_name + ' ' + message_lname + ' their email ' + message_email , message, message_email, ['myemail@gmail.com'], ) return render(request, 'blog/contact.html', {'message_name':message_name}) else: … -
How to make follow-following system in django for different three different models?
I have started learning Django about a month ago and I am trying to add a follow-following system for three models: Student, Teacher, and School but I am a little stuck. I have very little idea on how to a user A to the follower's list of user B when user B starts following user A because the user can be from any of the three mentioned models. How can I solve this or what would be the best way to go around this? Here are my Django models: student/models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) father_name = models.CharField(max_length=30) mother_name = models.CharField(max_length=30) dob = models.DateField() address = models.TextField() contact = models.CharField(max_length=10) roll_no = models.IntegerField() about = models.TextField() following = models.ManyToManyField(User, related_name='student_following', blank=True) followers = models.ManyToManyField(User, related_name='student_followers', blank=True) class_name = models.ForeignKey(Classes, null=True, on_delete=models.SET_NULL) school_id = models.ForeignKey(School, on_delete=models.CASCADE) teacher/models.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) dob = models.DateField() started_teaching = models.IntegerField() joining_date = models.DateTimeField() qualification = models.CharField(max_length=10) about = models.TextField() contact = models.CharField(max_length=10) following = models.ManyToManyField(User, related_name='teacher_following', blank=True) followers = models.ManyToManyField(User, related_name='teacher_followers', blank=True) school_id = models.ForeignKey(School, on_delete=models.CASCADE) school/models.py class School(models.Model): school_id = models.OneToOneField(User, on_delete=models.CASCADE) principal = models.CharField(max_length=50) name = models.CharField(max_length=50) address = models.CharField(max_length=50) contact = models.CharField(max_length=10) … -
How to add a try except blocks in this django-import-exportview?
I can't get it right on how to appropriately add a try except block here. My aim is to capture and display the particular errors that might be experienced during import i.e the particular invalid rows etc. I believe a try except block can help but I don't know how to implement it in this view. class upload(LoginRequiredMixin,View): context = {} def post(self, request): form = UploadForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportResource() result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,result.invalid_rows) self.context['result'] = result return redirect('/') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Successfully.') else: self.context['form'] = UploadForm() return render(request, 'home.html', self.context) -
Passing perameters into model formset
I'm trying to pass some variables into a model formset. I've looked at the official django documentation and they talk about doing this with a regular, non-model formset. I can't get this to work for a modelformset though. views.py EmployeeTeamFormset = modelformset_factory(EmployeeTeamMembership, form=EmployeeTeamForm(), extra=0, max_num=10, can_delete=True) formset = EmployeeTeamFormset(request.POST or None, queryset=EmployeeTeamMembership.objects.filter(employee__user=user, team=team), kwargs={'user': user, 'team': team}) forms.py class EmployeeTeamForm(forms.ModelForm): class Meta: model = EmployeeTeamMembership fields = ('employee', 'team_lead',) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) self.team = kwargs.pop('team', None) I get the following error: name 'user' is not defined Thanks for your help! -
unable to get the drop down menu in same row and it write once only when form is submitted
can't make a code that functions on the same line as others. want below line to third if statement where contact.save() line appear. please refer original block. appreciated your help if request.POST.get('program'): savevalue = Contact() savevalue.program=request.POST.get('program') savevalue.save() original block def index(request): if request.method == 'POST': name = request.POST.get('name', '') contact = request.POST.get('contact', '') address = request.POST.get('address', '') # program2 = request.POST.get('program2', '') # bba = request.POST.get('bba', '') # bhm = request.POST.get('bhm', '') email = request.POST.get('email', '') w3review = request.POST.get('w3review', '') if request.POST.get('program'): savevalue = Contact() savevalue.program=request.POST.get('program') savevalue.save() if name and contact and address and email and w3review: contact = Contact(name=name, contact=contact, address=address, email=email, w3review=w3review) contact.save() else: return HttpResponse("Enter all details") return render(request, 'index.html') -
How to upload files using FTP server and django rest api....How to do that?
am new to django...please be patient if it is basic thing..till i could't acheive this.. I am developing one django rest api for uploading files(ex.image,videos)using FTP server. I thought of use django ftp server library..but am not sure how to connect the FTP server(am using winscp)with django server.. -
Django 3.1.7 model custom constraint
class Connection(models.Model): source = models.OneToOneField(Interface, related_name="source", on_delete=models.CASCADE) destination = models.OneToOneField(Interface, related_name="destination", on_delete=models.CASCADE) notes = models.TextField(blank=True, null=True, help_text="Add any additional information about this connection here.") def __str__(self): return f"{self.source} : {self.destination}" With the model above, it is possible to create a "connection" in the Django admin from A-B and from B-A. I am trying to find a way to only allow one or the other. I've looked at Meta constraints, but I'm either not getting my mind around it, or it's not possible. 'm sure there is something simple that I'm just not aware of yet. Any advice? -
How to create a pick up email field in django
I am creating a Mails System Management Application. So I would like, based on the attachment figure, in the field A when the customer's email address to whom I want to send an email exists already in the system, to display their emails from this field. Otherwise, we will type the email address entirely, and then submit the form. Here is the models.py. class Contacts(models.Model): type_Contact_choice=( ('Agent','Agent'), ('Association','Association'), ('Autre','Autre'), ('Collectivité','Collectivité'), ('Conseil minicipal','Conseil minicipal'), ('Elu','Elu'), ('Particulier','Particulier'), ('Précture','Précture'), ('Société','Société'), ) civilite_choice=( ('Monsieur','Monsieur'), ('Madame','Madame'), ('M. et Mme','M. et Mme'), ('Monsieurs','Monsieurs'), ('Mesdames','Mesdames'), ) category_choice=( ('Personnel','Personnel'), ('Externe','Externe'), ) nom = models.CharField(max_length=200, null=False) type_contact = models.CharField(_('Type'), choices=type_Contact_choice, max_length=200, null=True, ) category = models.CharField(_('Catégorie du contact'), choices=category_choice, max_length=50, null=True, blank=True) prenom = models.CharField(_('Prénom'), max_length=200, null=False) civilite = models.CharField(_('Civilité'), choices=civilite_choice,max_length=200,null=True, blank=True) fonction = models.CharField(max_length=200, null=True, blank=True) telephone = models.CharField(blank=True, null=True, max_length=16) adresse = models.TextField() mobile = models.CharField(blank=True, null=True, max_length=16) email = models.EmailField(blank=True, null=True) divers = models.TextField(blank=True, null=True) service = models.CharField(max_length=300, blank=False, null=False) def __str__(self): return self.nom + ' '+self.prenom class Actions(models.Model): statut_action_choice=( ('Encours','Encours'), ('En attente','En attente'), ('Terminée','Terminée'), ('Annulé','Annulé') ) action_date =models.DateTimeField(auto_now_add=True) action_modification = models.DateTimeField(auto_now=True) de = models.ForeignKey(User, on_delete=models.CASCADE, null=True) a = models.ForeignKey(Contacts, on_delete=models.CASCADE, null=False) cc = models.EmailField(max_length=254,null=True,blank=True) file = models.FileField(_('Document joint'),upload_to='action/%Y/%m/%d', blank=True) statut = models.CharField(max_length=30, choices=statut_action_choice, default='Encours') action …