Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cookiecutter-django - DB doesn't seem to have project's tables
I initialized a project with cookiecutter-django according to the instructions in the docs, including setting up a PostgreSQL DB under the same name as the project slug. I can't seem to find any project-related tables in the DB. It contains 3 schemas: information_schema - no project-related tables there, obviously. pg_catalog (it's my first time working with Postgre, but I'm assuming no project-related tables would be there. Currently, nothing is.) public - it's empty. Some DB actions I can still make from the Django admin page, but I'd rather have direct access to the DB tables (mostly for self-verification). Thanks for any help. -
How to add a button near to each object in django 3.0 admin
I am developing a project which includes feature like sending mail. There will be different providers eg : amazone ses, sengrid etc. I have to test a provider by sending a test mail. SO how can i add a button to each provider object in model list page. There will be a button (send test mail) for each object in the model list also After sending a mail it should give success response in the page like we get after saving a model. Thanks in advance. -
Is it possible to add fields to the table "account_emailaddress"?
I want to add a new field to an existing table account_emailaddress (preserving this table), from allauth. But I can't figure out how to do it. Is it possible to customize the model? Thank you very much! -
Why am I getting this error when installing daphne?
First time attempting to run py -m pip install daphne from my django project directory: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file specified: 'C:\\Python39\\Scripts\\automat-visualize.exe' -> ' C:\\Python39\\Scripts\\automat-visualize.exe.deleteme' Second attempt: WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not install packages due to an OSError: [WinError 2] The system can not find the file specified: 'C:\\Python39\\Scripts\\cftp.exe' -> 'C:\\Python39\ \Scripts\\cftp.exe.deleteme' Where am I supposed to get these files from? -
Django djsonfield Decimal stored as string in expressions
I have a JSONField with some financial data. I cannot store it as a float, because I need precision, so I store it as a string. My model looks like this class Finance(models.Model) bill_data = JSONField( verbose_name=_("Bill data"), default=dict, blank=True, ) then I save bill_data = dict(paid=str(some_decimal_amount)) Finance.objects.create(bill_data=bill_data) I try to use Cast to convert it back to Decimal, because I need to use expressions, Finance.objects.all().annotate(paid=Cast('bill_data__paid', DecimalField())) I get an error return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for integer: "none" LINE 1: ...der"."bill_data", ("myapp_finance"."bill_data")::numeric(No... Does anyone know how to use str from JSONField in expressions or how to handle Decimal in JSONField correctly? -
How to retrieve these lines from postgres JSON-field based on key value pair with Django filter
In Django I have a model: class NewModelItem(models.Model): model = models.ForeignKey(to=NewModel, on_delete=models.CASCADE, related_name='new_model_item') field_data = models.JSONField() link_data = models.JSONField(null=True) and like to retrieve: 3 {"name": "105000-001-001", "customer_name": "belangrijk sample"} 4 {"index": 4, "project": [1]} 6 {"name": "105000-001-002", "customer_name": "nog een belangrijk sample"} 4 {"index": 4, "project": [1]} based on the last field (that's the link_data field) and specifically when project contains 1. I tried it as an integer instead of an array, but the filter below does not retrieve them either way. I would kindly ask for any help or suggestions. lookup = 'link_data__project' related_model = 4 # this is the field before link_data id = 1 data = NewModelItem.objects.filter(**{lookup: id, 'model': related_model}) -
Update data mismatching in Modal(pop-up) - Djanago Rest Framework
I'm practicing Django Rest Framework. I'm using data from API URL in the front end using JavaScript created by serializing the models. Furthermore, I have two models To-do and Task. Where Task is the subcategory of Todo. Task comes under Todo. The problem I'm facing was I was able to create a Task item under a particular Todo. But I was unable to update Todo, , update Task, delete Task and mark Task as completed. I was able to update first Todo item that displayed at the top of the list. If I want to update second item I couldn't do it. Task item was created under a Todo. Let's take a scenario, If I have two Todo items and two Task items under each Todo. If I delete 1st Task item from 1st Todo, but the 1st task element from both the Todo gets deleted. But I want to delete the 1st task from 1st todo item only. I know it's quite confusing for you to understand. Let me share the code and some images for the better understanding of the problem I'm facing. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, … -
Creating Signature and Greeting SMTP email setting Django
Anyone can help me, I want to add signature and greeting on email. I am using Django SMTP service to send the email but the default signature do not added while sending email. def form_valid(self,form): subject="Thank you" message = 'I hope.' from_email = settings.EMAIL_HOST_USER to_list = [form.cleaned_data.get('email')] send_mail(subject,message,from_email,to_list,fail_silently=True) return super(SignupPageView, self).form_valid(form) Here I want to add signature also because default signature does not work. Can anyone help me to add signature or there is any other way to add default signature so I can include it. I sending email via Gmail SMTP service -
Is it safe to dump django data and remake migrations?
I'm not entirely sure if this question belongs on SO or on some discussion board (I would appreciate any pointers) but I'm gonna put it here first. If it turns out to be out of place I'll delete it. I have a Django app in production with a few users and maybe about 20k records. The models have undergone so many changes over 3+ years and I want to tidy it up. I know about squashing migrations but that is not exactly what I'd like to achieve (though it could be a good compromise). My plan now is this dump the data delete all migration files and run manage.py makemigrations to generate new and fewer migration files create a new db and use manage.py loaddata to load the data back. I do this fairly regularly when I want to work with production db on my local and so far I haven't encountered any issues. Usually takes about 15 minutes to complete data dump and re-upload. I want to get more opinions on whether its safe to go this route. If there's anything I need to watch out for. For contentTypes, I do delete unused contenttypes using django admin interface. My … -
Django DRF: Restricting PUT options in ViewSet
I want to restrict my ViewSet so that it allows for different inputs based on permissions: My models: class Link(models.Model): name = models.CharField("name", max_length = 128) page = models.PositiveIntegerField("page", default = 1, choices = [(1, 1), (2, 2), (3, 3)]) layouts = models.ManyToManyField(Layout) class Layout(models.Model): name = models.CharField("name", max_length = 32) Serializer: class LinkSerializer(serializers.ModelSerializer): test = serializers.SerializerMethodField("get_layouts") def get_layouts(self): return ... class Meta: model = Link fields = ["name", "page", "test",] I have a helper class that provides a all_pages permission for example. in the restframework API I now have a dropdown from page 1-3, but if the user does not have the right to use all pages, I want to only show page 1 for selection (or make it a text field witout input field). Same problem applies for the ManyToMany field: How can I restrict the layouts dropdown options to the ones I selected in the admin-planel for that user? Right now I manually check everything in the PUT method of the ViewSet and return a "user is not allowed ... -> BAD REQUEST". -
How do I correct capitalization of Django's `verbose_name_plural`?
I have a Django (3.0) model ExtraCategory. Because, like a large chunk of the English language, this does not pluralize regularly, I have to spend time fixing Django's insistence on unnecessarily pluralizing it by specifying an inner Meta class with a verbose_name_plural: # models.py class ExtraCategory(models.Model): class Meta: verbose_name_plural = "extra categories" In the main Admin page, this model is listed as "Extra categories". I would like to maintain a consistent capitalization and have this listed as "Extra Categories". Even if I specify it in this manner, however, # models.py class ExtraCategory(models.Model): class Meta: verbose_name_plural = "Extra Categories" it still shows up as "Extra categories". Does the "Framework for Perfectionists with Deadlines" provide me a mechanism to display a string with a capital letter in the right place? -
Is there way to add style in UserCreateFrom in django
when i add style to UserCreationForm in forms.py and pass it to signup html page and test it , it don't work fine i mean it don't check username and email if it exist or not and password don't check if it good or no my q can't check username and email and password using UserCreationForm - Django -
How to display top 5 user list in Django?
I created a system with Django. In this system, users do some analysis. I keep the information of these analyzes in a model named "ApprocalProcess". How can I display the top 5 users who made the most analysis in "ApprovalProcess"? models.py class ApprovalProcess(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter') doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True) ... customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) views.py def approval_context_processor(request): approval_list = ApprovalProcess.objects.filter(user_id__company=current_user.company) context = { 'approval_list ': approval_list, .... } return context -
How do I add an image in a bootstrap card?
I am trying to a attach an image in a specific area in a card, but I don't know how to. I am sorry if it's a very silly question, I am a total beginner in terms of html. So can anyone please show me how to do it? It would have been really useful. Thanks in advande! I am using Django. For example, If I want to add an image in that specific blue outlined area, what should I do? My code {% for fixture in fixtures %} <div class="card bg-light"> <div class="card-header" style="color:red;" > Featured </div> <div class="card-body"> <h5 class="card-title" style="color:black;">{{ fixture.home_team }} vs {{ fixture.away_team }}</h5> <p class="card-text" style="color:black;">{{ fixture.description }}</p> <form style="color:black;"> <h5><label for="watching">Watching?</label> <input type="checkbox" id="watching" name="watching" value="watching"> </h5> </form> </div> </div> {% endfor %} -
Why filter() doesn't invokes in angular 11+Django rest framework?
In my current project which is using angular11 and Python Django+django rest framework so i was trying to create a filter feature in department component but it doesn't woeks as expected. when i am trying to filter so department table doesn't shows filtered record as o/p. before filter search [![enter image description here][1]][1] after filter serach result [![enter image description here][2]][2] this is my humble request that plzz review my code and if possible then help me to solve this problem asap. component.ts import { Component, OnInit } from '@angular/core'; import { SharedService } from "src/app/shared.service"; @Component({ selector: 'app-dep-show', templateUrl: './dep-show.component.html', styleUrls: ['./dep-show.component.css'] }) export class DepShowComponent implements OnInit { constructor(private service:SharedService) { } DepartmentList:any=[]; DepartmentIdFilter:string=""; DepartmentNameFilter:string=""; DepartmentListWithoutFilter:any=[]; ngOnInit(): void { this.refreshDepList(); } refreshDepList(){ this.service.getDeptList().subscribe((data)=>{ this.DepartmentList=data; }); } FilterFn(){ var DepartmentIdFilter1=this.DepartmentIdFilter; var DepartmentNameFilter1=this.DepartmentNameFilter; console.warn("filter called") // console.warn(el) this.DepartmentList=this.DepartmentListWithoutFilter.filter(function (el:any){ return el.DepartmentId.toString.toLowerCase().includes( DepartmentIdFilter1.toString().trim().toLowerCase() )&& el.DepartmentName.toString.toLowerCase().includes( DepartmentNameFilter1.toString().trim().toLowerCase() ) }); } }``` ``` <thead> <tr> <th scope="col"> <div class="d-flex flex-row"> <input [(ngModel)]="DepartmentIdFilter" class="form-control" (keyup)="FilterFn()" placeholder="filter"> </div> Department Id</th> <th scope="col"> <div class="d-flex flex-row"> <input [(ngModel)]="DepartmentNameFilter" class="form-control" (keyup)="FilterFn()" placeholder="filter"> </div> Department Name</th> <th scope="col">Options</th> </tr> </thead> ``` [1]: https://i.stack.imgur.com/L7Cag.jpg [2]: https://i.stack.imgur.com/Ckvxv.jpg if anybody can tell my mistake in this code or can suggest me … -
Django order record by serializer Method Field
I am confused about how can I order records by serializer method here Is my serializer serializer.py here is my data from API data from api here is my viewset kindly tell me is there any way I can order record by avg which is coming from serializer method field -
Django Channels Private Chat server
I am new to Django channels and the ASGI application itself, so I am a bit confused about how to go while building a private chatting app. There isn't much tutorial for private chats all are for chat rooms and broadcasting I have few thoughts in mind about how I can make a Private chat, but I am not sure which approach to take. My first thought is to not use the channel layer and handle each connection separately. By that I mean every time a user comes to the chatting app it will open a connection with the name chat__{userid} and if user_A sends a message to user_B it will first check if user_A is authorized to send a message to user_B then call send method on user_B, after a message is sent send back the confirmation to the user_A. there is a problem with the above implementation what if a user opens a different tab, how should I handle that. To establish a connection between users using channel_layers, if both are online while they are chatting with one another, but the problem arises when the user is chatting with multiple users do I need to open multiple WebSocket … -
'datetime.datetime' object is not callable django celery beat
I have Django Celery and Beat on my Docker based setup. My settings are divided into their concerned environment. base.py holds the common configurations that are required by both staging.py and production.py. In my common.py I am initialising a variable something like this from datetime import datetime import pytz est_timezone = datetime.now(pytz.timezone('EST')) This is the traceback I get for it celery-beat_1 | [2021-04-09 10:59:46,845: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("'datetime.datetime' object is not callable") you can put the above snippet in a shell and it works well, so I have no idea what's going on. -
Django: logging: Formatter how to access request.build_absolute_uri()
I am planning to use custom logging formatter in DJango. And add the url to the record object using request.build_absolute_uri() The following is what i want to do # SQL formatter to be used for the handler used in logging "django.db.backends" class CustomFormatter(logging.Formatter): def format(self, record): record.absolute_path = request.build_absolute_uri() # <-- how to access request here return super(CustomFormatter, self).format(record) and later use as 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(absolute_path)s \n%(message)s' }, } How to access request inside the Custom logging -
how to handle multiple models in django restframework
I am a beginer in django restframework.My question is how to update profile which contain the following fields "Name, Email, Mobile, Gender, Educationalqualification, college, specialization, country,state,city" and these fields are in diffenet models ie, models.py class LearnerAddress(Address): learner = models.ForeignKey(Learner, on_delete=models.CASCADE) class Learner(BaseModel, Timestamps, SoftDelete): created_from_choices = ( ('web', 'Web'), ('ios', 'iOS'), ('android', 'Android'), ) gender_choices = ( ('male', 'Male'), ('female', 'Female'), ('other', 'Other'), ('not_specified', 'Not Specified') ) user = models.OneToOneField(User, on_delete=models.CASCADE) created_from = models.CharField(max_length=20, choices=created_from_choices, default='web', null=False) phone_verification_date = models.DateTimeField(verbose_name="Phone verification Date", null=True) email_verification_date = models.DateTimeField(verbose_name="Email verification Date", null=True) is_email_verified = models.BooleanField(default=False) is_phone_verified = models.BooleanField(default=False) is_guest = models.BooleanField(default=False) # photo = models.ImageField(upload_to=None, height_field=None, width_field=None,Learner null=True, blank=True) gender = models.CharField(max_length=20, choices=gender_choices, default='not_specified', null=False) class LearnerQualification(BaseModel, Timestamps, SoftDelete): qualification = models.ForeignKey(EducationalQualification, max_length=50, null=False, on_delete=models.CASCADE) specialization = models.ForeignKey(Specialization, max_length=50, null=False, on_delete=models.CASCADE) college = models.ForeignKey(College, max_length=50, null=False, on_delete=models.CASCADE) year = models.IntegerField(null=False) remarks = models.CharField(max_length=100, null=False) learner = models.ForeignKey(Learner, on_delete=models.CASCADE, related_name="learner_qualifications", null=True) -
Django in Python using sessions
print("Your answers") opn1 = request.session.get('no1') print(opn1) opn2 = request.session.get('no2') print(opn2) opn3 = request.session.get('no3') print(opn3) opn4 = request.session.get('n1') print(opn4) opn5 = request.session.get('no5') print(opn5) print("Correct Answers") print("1. Silicon") print("2. 1000 bytes") print("3. Microsoft Office XP") print("4. Param") print("5. 1000,000,000 bytes") So i have got answers from the users using session and i have displayed the correct answers but i wanted to know the condition to validate -
SyntaxError: invalid syntax in django
I get this error when run the code. Any help is appreciated class Logout(generics.CreateAPIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): response = self.http_method_not_allowed(request, *args, **kwargs) return response def post(self, request, *args, **kwargs): return self.logout(request) def logout(self, request): try: request.user.auth_token.delete() except(AttributeError, ObjectDoesNotExist) as e: logger.exception(e) logger.debug("Can't logout", exc_info=True) raise e response = Response({"detail": "Successfully logged out."}, status=status.HTTP_200_OK) return response except (AttributeError, ObjectDoesNotExist) as e: ^ SyntaxError: invalid syntax -
How to remove null from serializer.data when return response in django
I want to remove null from serializer.data before return final response to the end users. Here is my code: def list_order_by_status(request): order = Order.objects.all() serializer = ListOrderSerializer(order, many=True, context={"status": request.data['status']}) return Response(serializer.data) Here is my reponse: 0: {…} 1: null 2: {…} -
django: how middleware know something to execute before view is called and something after view is called
I am going through the django middle ware. I am not able to understand how does the middleware know somecode to be run before the view is called and some code to be run after the view is called. the following image will show more clearly what i am asking -
Django REST Framework - How to generalize this serizlier method?
I have a Question model in my app, as well as an Answer model. I also have a QuestionSerializer and an AnswerSerializer. I'm dealing with overriding the update method of my QuestionSerializer: since I can send both my question and answers data in a single PUT request, I need my serializer to handle nested updates. Here's the code I came up with: def update(self, instance, validated_data): # get data about answers answers_data = validated_data.pop("answers") # update question instance instance = super(QuestionSerializer, self).update( instance, validated_data ) answers = instance.answers.all() # get all answers for this question # update each answer or create it if it didn't exist for answer_data in answers_data: try: answer = Answer.objects.get(pk=answer_data["id"]) save_id = answer_data["id"] except Answer.DoesNotExist: answer = Answer(question=instance) answer.save() save_id = answer.pk del answer_data["id"] # get rid of frontend generated id used to determine whether the question already existed serializer = AnswerSerializer( answer, data=answer_data, context=self.context ) serializer.is_valid(raise_exception=True) serializer.update(instance=answer, validated_data=answer_data) # remove answer from the list of those still to process answers = answers.exclude(pk=save_id) # remove any answers for which data wasn't sent (i.e. user deleted them) for answer in answers: answer.delete() return instance Basically, for each new answer my frontend generates a random id (a very …