Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to recover local uncommited files that accidentally got deleted in Android Studio?
I faced a sudden issue, I have deleted some of my un revisioned files during commit to my android project but I found all of the modified and newly added files were missing from my commit (which I was going to make). I can not just remove or pull again the project from the origin because it will completely remove the VCS cache of the previous one. How do I get my files back? I have also checked this questions and answers but this didn't solve my issue. So, I have found a solution otherwise with new Android Studio update. -
Trying to get \n to work in django/html after using python for script
I created a Python script that retrieves a list of payments that go to my companies email. I thought it would be interesting to do for Cashapp/Venmo payments to compile them. However I really want the site to format the payments/details so that each payment is on a new line. In the python I put final = final + ..... + \n for the string that is to be used in the html. Yet \n will not work in HTML no matter what I try to do. In my views.py I set data=final, then call it here in the HTML. <body> <button onclick="location.href='{% url 'script' %}'" > Check new payments </button> <hr> {% if data %} {{data}} {% endif %} </body> This prints out all the necessary data yet it is in one continuous string and does not include the \n. If I print it in the terminal it includes these. It is likely because html does not recognize \n I assume, I just don't know an alternative for this. -
django-filter not showing filtered items
i used django-filter in a similiar way before and it worked fine, but now when I try to filter my posts it just returns all the items instead of filtering them, can anyone figure what I'm doing wrong? my filters.py class filtering(django_filters.FilterSet): class Meta: model = Cars fields = ['color','body'] and my views: start_date = (datetime.today() - timedelta(30)) end_date = (datetime.today() + timedelta(1)) last_month_records = Cars.objects.filter(datetime__range=(start_date, end_date),car='206') post_list = last_month_records.order_by('-datetime').values() filters = filtering(request.GET,queryset=post_list) post_list = filters.qs.values() -
Ecommerce website in Django, Order is not being saved when the client logged in an account. If not it's working well
I am working on ecommerce website and it's time to make checkout. In my website, when to order product without an account it's saving the order, but if it's with an account, it's going to another page, but not erasing a cart and isn't saving the order. What is the problem? Can you please help me to solve this problem. It's not working only when client is logged in an account. views.py def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) tel = data['shipping']['number'], address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) else: customer, order = guestOrder(request, data) total = float(data['form']['total']) order.transaction_id = transaction_id order.tel= tel order.address=address order.city=city order.state=state if total == order.get_cart_total: order.complete = False order.save() return JsonResponse('Payment submitted..', safe=False) html <form class="form" method="POST" action="#" id="form"> <div class="row"> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Имя<span>*</span></label> <div> <input type="text" name="name" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Фамилия<span>*</span></label><div> <input type="text" name="surname" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info"> <div class="form-group"> <label>Email<span>*</span></label><div> <input type="email" name="email" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" id="user-info shipping-info"> <div class="form-group"> <label>Номер телефона<span>*</span></label><div> <input type="number" name="number" placeholder="" required="required"></div> </div> </div> <div class="col-lg-6 col-md-6 col-12" … -
Delete File on S3 bucket before uploading new file with the same name
I have a model, that on save, it uploads my image to my S3 bucket. But I'm having some trouble when I want to reupload an image with the same name. (Example: when a logo updates it needs to be reuploaded) Because the image already exists, Django extends the pathname with it's own generated extention to make it unique. We don't want that, we want to delete the existing image before uploading the new image. That way, the extention is no more. I've tried removing my image first with the pre_save signal, but that just makes my imagefield empty @receiver(pre_save, sender=geo_models.Logo) def remove_file_from_s3(sender, instance, using, **kwargs): instance.png.delete(save=False) Any way of doing this? -
Filter tables contain all value in another table
i have 2 tables Product and user and each table have list of permissions i need to list to the user all product such that user have all the product permissions check the code representation: Product Model: class Product(TimeStampedModel, SoftDeletableModel): title = models.CharField(max_length=255, unique=True) permission = models.ManyToManyField(Permission, related_name="Permissions") and this is the user model: class User(AbstractBaseUser, SoftDeletableModel): display_name = models.CharField(max_length=64, blank=True) permission = models.ManyToManyField(Permission, related_name="Permissions") lets say we have the following data: user1 permissions A1,A2,C1,C2,C3 user2 permissions A1,A2,B1,B2,C1,C2,C3 product has permissions A1,B1,C1 user1 can not see the product "does not have B1 permission" user2 can see the product i tried the following: Products.objects.filter(permission__in=user.permission.values("id")) also tried this sql query: Select * from products p Inner join productspermession pp On p.id = pp.product_id Inner join userpermessions up on pp.permession_id = up.permession_id where up.user_id = 1 -
how to write File Download with django Rest framework?
I have a model with filefield with xls and xlsx and person who uploaded it i need to write api view in DRF that returns download on front end how can my view be? models.py class FileuploaderView(BaseModel): file = models.FileField( upload_to='', validators=[FileExtensionValidator(['xls', 'xlsx'])], ) uploaded_by = models.ForeignKey( 'accounts.Person', related_name= '', null=True, on_delete=models.SET_NULL, ) views.py: def DownloadView(APIView): def get(self, request, id, format=None): queryset = Model.objects.get(id=id) file_handle = queryset.file.path document = open(file_handle, 'rb') response = HttpResponse(FileWrapper(document), content_type='') response['Content-Disposition'] = 'attachment; filename="%s"' % queryset.file.name return response Is it the -
why my code is not going to try block and goes directly to except block in django
Hi there I've created a user login page with built in database in my django project. I've created a login page and make a try block to check if email id already registered in database? if data found in database then it goes to index page other wise gives an error like "ID not registered". I have double check the user id and password field, its correct but still my code goes straight forward to exception block only. what is wrong with my code ? '''def login(request): if request.method=="POST": try: user=User.objects.get( email=request.POST['email'], password=request.POST['password'] ) request.session['email']=user.email request.session['fname']=user.fname return render(request,'index.html') except: msg="Email Or Password Is Incorrect" return render(request,'login.html',{'msg':msg}) else: return render(request,'login.html')''' -
What are the step by step to Host my Django app to IBM cloud
I created a Blog application in Django, and now I decided to hosting it in IBM Cloud, what are the step by step to host it in IBM Cloud, I get confused with the tutorials I follow in YouTube and also some Blog in Google, all i see is the tutorial with Flask. what are the libraries and file do I needs before hosting it in IBM CLOUD. Is some body who can help me ? -
Need to display the hours spent in the date from one model to another
model 1 class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) model 2 class Consolidated(models.Model): emp_name=models.ManyToManyField(Users,related_name="employee_name+") proj_name=models.ManyToManyField(Project) custom_name=models.ManyToManyField(Client) Cons_date=models.ManyToManyField(Add_Timelog) bill_no_bill=models.ManyToManyField(Users,related_name="billable_and_non_billable+") hours_spent = models.ManyToManyField(Add_Timelog,related_name="Hours+") def __str__(self): return str(self.id) I need to update the value from "Hours" field in Add_Timelog model to display it in the "hours_spent" field in Consolidated model. As I am already doing it for "Date" field I need to do it for this also. But I don't know whether it can be possible, kindly help me with this code. (ex: if I enter a Date as today and Hours as 4 hr's in Add_Timelog model, I need to display it in Consolidated model as for today 4 hr's has been spent by this employee.) -
How can I display image in admin.py and one of my field in employee table is not appearing correct in admin.py?
I am working on creating Employee monitoring system. I have 3 models right now. Here they are class User(models.Model): username= models.CharField(max_length=256, verbose_name='Username') first_name = models.CharField(max_length=256, verbose_name='First Name') last_name = models.CharField(max_length=256, verbose_name='Last Name') email=models.EmailField(max_length=256, verbose_name='Email') def __str__(self): return self.first_name + self.last_name class Departments(models.Model): department_name= models.CharField(max_length=256, verbose_name='Departments') def __str__(self): return self.department_name class Designation(models.Model): department_name= models.ForeignKey(Departments, on_delete=models.CASCADE) designation_name=models.CharField(max_length=256, verbose_name='Designation') def __str__(self): return '{} {}'.format(self.department_name, self.designation_name) class Employee(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True,) department_name= models.ForeignKey(Departments, on_delete=models.CASCADE) designation_name= models.ForeignKey(Designation, on_delete=models.CASCADE) salary= models.FloatField(null=False, default=0.0, verbose_name='Salary') image = models.ImageField(upload_to = 'employee_images', null=True, blank=True) def __str__(self): return '{} {} {}'.format(self.user.first_name + self.user.last_name, self.department_name.department_name, self.designation_name.designation_name) def image_tag(self): return mark_safe('<img src="/employee_images/%s" width="150" height="150" />' % (self.image)) image_tag.short_description = 'Image' my return self.first_name +self.last_name in def __str__(self) of employee table is not giving me any gap between these two names. I don't know how to do it. and I have tried every method suggested by everyone on this website to display image on admin.py but I am unable to display them. Here is my admin.py admin.py @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display= ('first_name', 'last_name', 'designation_name', 'department', 'salary', 'image_tag') def first_name(self, obj): return obj.user.first_name def last_name(self, obj): return obj.user.last_name def designation_name(self, obj): return obj.designation.designation_name def department(self, obj): return obj.department_name.department_name and one last thing my designation_name … -
postman authentication credential not provided - Django
postman request I have provided my complete code that I was using to achieve JWT authentication in my django app. I am able to register user, log in but even after providing the token in header, I am having this error in postman. I have tried multiple options from internet to resolve this issue but nothing is helping, I tried replacing Bearer to Token but that also didn't work. models.py import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils import timezone from .managers import CustomUserManager # Create your models here. class User(AbstractBaseUser, PermissionsMixin): # These fields tie to the roles! ADMIN = 1 USER = 2 ROLE_CHOICES = ( (ADMIN, 'Admin'), (USER, 'User'), ) class Meta: verbose_name = 'user' verbose_name_plural = 'users' # Roles created here uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4, verbose_name='Public identifier') email = models.EmailField(unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=50, blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, null=True, default=2) avtar = models.FileField() date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email serializers.py from .models import User from rest_framework import serializers from rest_framework_simplejwt.tokens import … -
How do I resolve this? I am trying to run my django app and am getting this error
myapp.AuthPermission.content_type: (fields.E300) Field defines a relation with model 'DjangoContentType', which is either not installed, or is abstract. myapp.AuthPermission.content_type: (fields.E307) The field records.AuthPermission.content_type was declared with a lazy reference to 'myapp.djangocontenttype', but app 'myapp' doesn't provide model 'djangocontenttype'. -
how to use StreamingHttpResponse in django rest framework?
i have a simple django rest framework and i want to know how can use StreamingHttpResponse in my project. my model is like this: class Article(models.Model): user = models.CharField(max_length=100) title = models.CharField(max_length=200) description = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title and serializer for this model is like this: class ArticleSerializers(serializers.ModelSerializer): class Meta: model = Article fields = ['id', 'user', 'title', 'description', 'date'] i think my problem is in mu view or url. so i wrote code in view like this: class StreamPost(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializers def get_queryset(self): stream = event_stream() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response that the event_stream is like this: def event_stream(): initial_data = '' while True: list_article = list(Article.objects.all()) data = json.dumps(list_article, cls=DjangoJSONEncoder) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1) the url is like this: router = DefaultRouter() router.register('stream', StreamPost, basename='stream') urlpatterns = [ path('', include(router.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i can't track the error and so i don't know where is my problem but when run my project with this codes the problem is like this: Object of type Article is not JSON serializable when i change the event_stream function the … -
Django-filter -- How to create a date Filter for 2 different models
I have 2 models; Invoice and Expense. Both have a date field. I want to create a django-filter where I put a start-date and end-date and get the result on 2 differents table in the same HTML page. So far I need to use 2 different filters and if I put the date in the Invoice Filter it clears the Expense Filter. Same if I put the date in the Expense Filter it clears the Income Filter. Here is my filters.py class InvoiceFilter(django_filters.FilterSet): inv_start_date = DateFilter(field_name = "invoice_date", lookup_expr='gte', label='Start Date') inv_end_date = DateFilter(field_name = "invoice_date", lookup_expr = 'lte', label = 'End Date') class Meta: model = Invoice fields = '__all__' exclude = ['invoice_slug', 'invoice_date','customer', 'invoice_no', 'price', 'quantity', 'total', 'payment', 'balance'] class ExpenseFilter(django_filters.FilterSet): exp_start_date = DateFilter(field_name = "expense_date", lookup_expr='gte', label='Start Date') exp_end_date = DateFilter(field_name = "expense_date", lookup_expr = 'lte', label = 'End Date') class Meta: model = Expense fields = '__all__' exclude = ['expense_date','description','amount'] Than on my dashboard.html {% block content %} <center><h3>DASHBOARD</h3><br/> <h3>Todays Date: {{ month }} {{ current_day }}, {{ year }} @ {{ current_time }}</h3><br/> <div class="row"> <div class="col"> <div class="card card-body"><h4>Incomes Filter</h4><br/> <form method="get"> {{ ResultFilter.form }} <button class="btn btn-primary" type="submit"> Search...</button> <a class="btn btn-primary" href="{% … -
Rest django post update if existing othserwise create new data
how can i add both create and update in same api using rest django, when we are adding a data if the same id have data in database only want to update, there is no id existing in the data base create a new row while resubmitting the button -
How to authorize user in Django testing REST framework APIClient post method
can somebody help me. I can't authorize my test user in unittests class APIGameTestCase(APITestCase): def setUp(self): self.user = User.objects.create_user(username='testuser', password='123') self.token = Token.objects.get(user=self.user) self.api_authentication() def api_authentication(self): self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_create_game(self): url = reverse('game-list') payload = { 'name': 'testgame', 'game_category': 'testgamecategory', 'played': False, 'release_date': '2016-06-21T03:02:00.776594Z', } response = self.client.post(url, payload) self.assertEqual(response.status_code, status.HTTP_201_CREATED) Assert error AssertionError: 401 != 201 models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) -
TypeError: _prepare_related_fields_for_save() missing 1 required positional argument: 'self'
models.py When i want to create test data i get an error TypeError: _prepare_related_fields_for_save() missing 1 required positional argument: 'self' and i dont know how to solve this issue .Can someone help me? from django.utils import timezone class Worker(models.Model): fullname = models.CharField(max_length=255, verbose_name='ФИО') position = models.CharField(max_length=155, verbose_name='Должность') start_date = models.DateField(default=timezone.now, verbose_name='Дата создания') salary = models.CharField(max_length=20, verbose_name='Зарплата') parent = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True, related_name='childrens', verbose_name='Начальник') def save(self, *args, **kwargs): max_indent = 3 lvl = self.parent.id if self.parent else 0 if lvl < max_indent: super().save(*args, **kwargs) else: raise ValueError("Максимальная вложенность: 3") class Meta: verbose_name = 'Сотрудник' def __str__(self): return self.fullname test_data.py import random import string from django.core.management.base import BaseCommand from tree_app.models import Worker class Command(BaseCommand): help = 'Filling with data' def handle(self, *args, **options): worker = [Worker for i in range(1,30)] for i in worker: i.fullname = ''.join([random.choice(string.ascii_lowercase) for i in range(16)]) Worker.objects.bulk_create(worker) #this is line 14 self.stdout.write(self.style.SUCCESS('Successfully created')) ERROR docker-compose exec web ./manage.py test_data Traceback (most recent call last): File "/app/./manage.py", line 22, in <module> main() File "/app/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 417, in execute … -
Django model choice field: Difference between list of pair and list of string
In Django model lots of time I see to use a list of pair for choices some thing like this: class RuleUpdateTrack(models.Model): Id = models.IntegerField() operationChoice = [ ('insert', 'insert'), ('update', 'update'), ('delete', 'delete'), ('initial', 'initial'), ] operation = models.CharField(max_length=50, choices=operationChoice, default='none') Now I have some query why we should use ('insert', 'insert') in this array instead of something like this: operationChoice = [ 'insert', 'update', 'delete', 'initial', 'none'] Please told me the differences. -
How to pass '+' in an url? [duplicate]
I have this url that i am passing to backend https://hello.com/calendar/?class_id=15+PTWes003&class_number=7 which after encoding become this https://hello.com/calendar/?class_id=15%20PTWes003&class_number=7 I am unable to pass this + symbol to my django backend. -
__call__() got an unexpected keyword argument 'force_insert'
My programming was originally working, but then it stopped working and I can't figure out the issue. I was trying to save the form data to my "listing" models.py: class User(AbstractUser): pass class listing(models.Model): tittle = models.CharField(max_length=64) description = models.CharField(max_length=64) price = models.DecimalField(max_digits=64, decimal_places=2) image = models.URLField() category = models.CharField(max_length=64) seller = models.ForeignKey(User, on_delete = models.CASCADE) view.py: def add(request): category_choices=[ ("fashion","Fashion"), ("toys", "Toys"), ("electronics", "Electronics"), ("hone", "Home"), ("baby", "Baby"), ("others", "Others") ] class create(forms.Form): tittle = forms.CharField(label="tittle", max_length=100) description = forms.CharField(label = "Description", widget=forms.Textarea) price = forms.DecimalField(label="price in USD", max_digits=64, decimal_places=2, min_value=0) image = forms.URLField(label="Image URL", required=False) category = forms.CharField(label = "Category", widget=forms.Select(choices=category_choices)) if request.method=="POST": form = create(request.POST) if form.is_valid(): description=form.cleaned_data["description"] tittle = form.cleaned_data["tittle"] price=form.cleaned_data["price"] image=form.cleaned_data["image"] category=form.cleaned_data["category"] seller = request.user l = listing.objects.create(tittle=tittle, description=description, price=price, image=image, category=category, seller=seller) l.save() return render(request, "auctions/index.html") Error Message: Exception Type: TypeError at /add Exception Value: call() got an unexpected keyword argument 'force_insert' -
Download dataframe as pdf using Django
@api_view(["GET"]) def practice2(request): try: db = client["my_db"] col = db["my_report"] sdate= date(2021,5,1) edate= date(2021,5,5) delta = edate - sdate # as timedelta a=[] for i in range(delta.days + 1): day = sdate + timedelta(days=i) a.append(day) b=[] df = pd.DataFrame(np.random.random((10,3)), columns = ("col 1", "col 2", "col 3")) fig, ax =plt.subplots(figsize=(12,4)) ax.axis('tight') ax.axis('off') the_table = ax.table(cellText=df.values,colLabels=df.columns,loc='center') pp = PdfPages("region.pdf") pp.savefig(fig, bbox_inches='tight') pp.close() except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) I have got this code from django documentation , but when i am trying "df=my custom df " then it is not working. -
Use logger for django as module
I am trying to set the logger for django project. I use MyLogger.py to initialize logger myproj/myproj/helper/MyLogger.py import sys import logging from logging import getLogger,StreamHandler,WARNING,INFO logger = getLogger(__name__) logger.setLevel(logging.DEBUG) logger.debug("MyLogger init") // it is shown and try to import logger in my views.py then in my views.py myproj/defapp/views.py from myproj.helpers.MyLogger import logger as _logger def index(request): print("get near start") // it is shown _logger.debug("get near start from logger") //but nothing appears in console. Where should I fix?? -
django orm prefetch_related latest data
Reference: django - prefetch only the newest record? Hi I want to bring only the latest message among the messages I wrote. Models class Room(models.Model): host = models.ForeignKey(Company, related_name="room_host", on_delete=models.CASCADE) member = models.ForeignKey(Company, related_name="room_member", on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Message(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, related_name="message") sender = models.ForeignKey(USER, on_delete=models.CASCADE, related_name="sender") content = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) My code last_msg_pk = Message.objects.filter( sender__company_code=user.company_code ).values("id") room = Room.objects.filter( member=request.user.company_code ).prefetch_related( Prefetch( "message", queryset=Message.objects.filter(pk__in=last_msg_pk), to_attr="msg" ), ) for i in room: for j in i.msg: print(j.id) 167 136 89 3... I brought all the messages... I just want to bring a message that I wrote recently. What should I do? -
add instances to a manytomany field in django rest framework
I have a very simple question and I'm surprised it hasn't been asked before on this website. I have the two following models: # models.py class Film(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=150) genre = models.ManyToManyField(Genre) class Genre(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) I need to make an API that gets 2 integers, id of movie and id of genre, and adds the said genre to the movie. seems very simple but I don't know how I could do this. I could really use the help.