Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Nginx doesn't serve static and media with django and Docker
I need to launch my site in production, so I decided to do it with Docker container(at first time, newbie there) with Postgres, nginx and Django, everything is working inside a container, but on launched site I have in console 404 error with static and media. I did a research, but still haven't found the answer for my case. Could somebody advise what I need to fix there? There is my Dockerfile ########### # BUILDER # ########### # pull official base image FROM python:3.9.6-alpine as builder # set work directory WORKDIR /usr/src/my_shop # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 and Pillow dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev # && pip install Pillow # lint RUN pip install --upgrade pip RUN apk add build-base python3-dev py-pip jpeg-dev zlib-dev ENV LIBRARY_PATH=/lib:/usr/lib # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/my_shop/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.6-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate … -
Is there a faster way of uploading multiple files in Django?
I have a django project where the client can upload multiple files at once. My problem is that for each uploaded file I'm creating a model object - one at a time. Is there a way to do this with bulk create or some other method that is faster. Views.py: images = request.FILES.getlist('images') xmls = request.FILES.getlist('xmls') jsons = request.FILES.getlist('jsons') for image in images: img_name = (str(image).split('.')[0]) dp_name = dataset_name+'-'+img_name if [xml for xml in xmls if img_name+'.' in str(xml)]: xml = [xml for xml in xmls if img_name+'.' in str(xml)][0] else: xml = None if [json for json in jsons if img_name+'.' in str(json)]: json = [json for json in jsons if img_name+'.' in str(json)][0] else: json = None dataset.create_datapoint(image, xml, json, username, dp_name) Models.py: def create_datapoint(self, image, xml, json, username, dp_name): datapoint = Datapoint.objects.create( xml = xml, json = json, name = dp_name, uploaded_by = username, img = image, belongs_to = self, ) self.num_datapoints += 1 datapoint.parse_xml() self.datapoints.add(datapoint) self.save() return -
Logging user's device details in DJango admin
How to log the login user's device, os, ipaddress, location etc. in Django? Is there any library available for this? -
Issue deleting first row in a django_tables2 using TemplateColumn
Relatively new to Django. I am working on a project that has an existing django_tables2 table. I am trying to use TemplateColumn to add a delete button within the table. The code I currently have works for all rows within the table (the values are deleted) except for the first row within the table, which refuses to delete. I can change the table order and always the first row will not delete. When I inspect elements for the new delete button, the only difference I see is that the first row omits the form: <form method="post" action="/en/specimen/1/delete/"> ... </form> I've been trying to get the form to load for the first row, but haven't yet gotten it to work. Here is what I have so far. tables.py: from django_tables2 import tables, TemplateColumn import django_tables2 as tables class SpecimenTable(tables.Table): SpecimenLabel = tables.LinkColumn('specimen_edit', text=lambda record: record.SpecimenLabel, args=[A('id')]) Sample = tables.Column(accessor='Sample.SampleName', verbose_name='Sample') SampleType = tables.Column(accessor='Sample.SampleType', verbose_name='Sample Type') Type = tables.Column(accessor='SpecimenType.name', verbose_name='Specimen Type') Medium = tables.Column(accessor='Medium.name', verbose_name='Medium') class Meta: model = Specimen template_name = "django_tables2/bootstrap4.html" order_by = 'SpecimenLabel' attrs = {"class": "table table-hover"} fields = ['SpecimenLabel', 'Sample', 'SampleType', 'Type', 'Medium', 'delete'] delete=TemplateColumn(template_name='project/tables/specimen_delete.html', verbose_name=_('Delete'), orderable=False) specimen_delete.html <!-- Button trigger modal --> <button type="button" class="btn btn-danger … -
Can't add to ManyToManyField in Django custom task
I have two models in my Django app (Tag and MyModel). MyModel has a ManyToManyField (tags) that uses the Tag model class Tag(models.Model): CATEGORY_CHOICES = ( ('topic', 'topic') ) tag = models.CharField(max_length=100, unique=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) class MyModel(models.Model): id = models.CharField(max_length=30, primary_key=True) title = models.CharField(max_length=300, default='') author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') tags = models.ManyToManyField(Tag) I have a custom Django management task where I delete the Tags table, get new data, and refresh the Tags table with bulk_create Tag.objects.all().delete() ....get new data for Tag table Tag.objects.bulk_create(new_tags) However after this - if I try to add a tag to an instance of MyModel.tags... mymodel_queryset = MyModel.objects.all() for mymodel in mymodel_queryset mymodel.tags.add(5) ...I get this error: CommandError: insert or update on table "bytes_mymodel_tags" violates foreign key constraint .... DETAIL: Key (tag_id)=(5) is not present in table "bytes_tag". It seems like the Tag table is empty even though I just updated it For some reason deleting and resetting the Tag table prevents me from adding to an instance of MyModel.tags. How can I do this? Note: If I don't first delete and reset the Tags table then I can add to MyModel.tags just fine -
Django Rest Framework sending Request to External API - Expecting value: line 1 column 1 (char 0)
I'm working on an API for my application to send a POST request to an external API. So for example, if my app hits endpoint /myapp/api I want it to call out to an external API and grab some data. In this case, I need this to be a POST request because in order to get the data that I want, I need to pass in some values. I have made this POST call directly to the external API via Postman successfully many times, and I'm now trying to reproduce that in my python code. In my views.py, I have this: class MyAPPViews(APIView): def post(self,request): crt = 'path/to/crtfile' key = 'path/to/keyfile' #here I tried to reproduce the headers from the postman call #as best as I could just to be extra specific headers = { 'Content-Type': 'application/json', 'Accept': '/*/', 'Accept-Encoding': 'gzip,deflate,br', 'Connection': 'keep-alive' } payload = { "unitList": [ "CFQU319303" ] } res = requests.post('external/api/url', headers=headers, data=payload, cert=(crt,key)) print('this is the true http resonse: ',res.status_code) data = res.json() return Response({"status": "success", "data": data}) in my urls.py I have this path('externalAPI',MyAPPViews.as_view()), Now, when I try to go into postman and hit http://127.0.0.1:8000/myapp/externalAPI I get a 500 status code returned and the … -
Python - Django - Heroku - ImportError - cannot import name 'fromshare' from 'socket'
I successfully deployed my app to heroku but now I am getting an error: ImportError at / cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.9/socket.py) Looks like it traces back to: File "/app/users/forms.py" in <module> 1. from socket import fromshare I have looked everywhere I can online and have not seen anyone run into this. Any idea how I would fix this? -
running 'heroku login' won't create _netrc file
I am using on a 64-bit system running Windows 11 with Python 3.7 installed and working in a virtual environment where I have installed Django 3.2. I am trying to deploy my project using Heroku. I have tried adding heroku cli 64-bit Windows version to various paths. I have set the env variable HOME with a value of C:\Users<username>_netrc. I have cleaned up the path on each installation so there is only the current path. When I run heroku login from within my project, I get the following error: EPERM: operation not permitted, open 'C:/Users//_netrc Any help here is appreciated -
Django Admin, use list_filter, based on foreing key field
The app have 3 classes at model.py, and it was created a calculated field. class Category(models.Model): name = models.CharField(max_length=255) class Asset(models.Model): category = models.ForeignKey(Category, related_name='categories', on_delete=models.CASCADE) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) @property def category(self): return self.asset.category I tried to add in the admin.py a list_filter: class PortfolioAssetAdmin(admin.ModelAdmin): list_display =('asset', 'category' ) list_filter =(('category', RelatedFieldListFilter),) but i get the error message: "PortfolioAsset has no field named category" I think that is because category in PortfolioAsset is calculated, but don`t know how to solve that. Or if there is any better and working solution. Thanks -
How to get "content_type" using Get File Properties REST API for Azure Files Storage using Python
I'm trying to get the "content_type" property for files in Azure fileshare. I can get "last_modified" and "size" but not "content_type" from azure.storage.file import * from azure.storage.fileshare import * def azure_connect_conn_string(source_file_connection_string, source_share_name): try: share_service = ShareServiceClient.from_connection_string(source_file_connection_string)#ShareServiceClient interact with the account level share_client = share_service.get_share_client(source_share_name) #desired share name is accessed file_service = FileService(connection_string=source_file_connection_string) print("Connection String -- Connected.") return share_client, file_service #returns the share client except Exception as ex: print("Error: " + str(ex)) def fileshare_content_list(connection_instance, directory_name, file_service, share_name): d_client = connection_instance.get_directory_client(directory_name) my_files = d_client.list_directories_and_files() directory_list = [] for file in my_files: if file.get('is_directory'): #cannot get size of directory, only of files file_name = file.get('name') file_lastmod = file.get('last_modified') file_type = 'directory' file_size = 'unknown' else: file_name = file.get('name') file_props = file_service.get_file_properties(share_name, directory_name, file_name) file_lastmod = file_props.properties.last_modified file_size = file.get('size') print(file_name) print(file_lastmod) print(file_size) print(file_props.properties.content_type) def main(): try: azure_connection_string = 'DefaultEndpointsProtocol=https;AccountName=ecpcdmsdatamartexternal;AccountKey=neNa1jtdyVljMN/j403/rHwdYBpPUtKTreeYM4UsKiosiOfKdePgyZdJl8SK9UdAlsXwVvOkNdNWZjnOCyn/lw==;EndpointSuffix=core.windows.net' share_name = "ecdmpext" directory_name = "data" connection_instance, file_service = azure_connect_conn_string(azure_connection_string, share_name) ## List files fileshare_content_list(connection_instance, directory_name, file_service, share_name) print('Done') except Exception as ex: print('main | Error: ', ex) if __name__ == "__main__": main() I get error 'FileProperties' object has no attribute 'content_type' When I try using file.get("content_type") I just get "None". I use file.get() for "size" and "name", for "last_modified" I have to use … -
Javascript function inside Django Loop runs only once
In my template, i generate each table row within a django for loop, I have this function that formats strings the way I want, but it's working only in the first row of the table, I dont know why.