Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - PDF file not uploading but path is available
I'm trying to upload a pdf file to the database with forms but however the file isn't send to the server. models.py class Presse(models.Model): pdf = models.FileField() forms.py class PresseForm(forms.ModelForm): class Meta: model = Presse fields = '__all__' I tried same way I do when uploading images, which works fine. Somewhere I have an error or forgot something I didn't know about. views.py def presse(request): article = Presse.objects.get(id=1) if request.method == 'POST': form = PresseForm(request.POST, request.FILES, instance=article) if form.is_valid(): form.save redirect('main:presse') else: form = PresseForm(instance=article) return render(request, 'main/presse.html', { 'article': article, 'form': form }) presse.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success">Ersetzen & speichern</button> </form> If I upload a file after getting redirected I get error 404 GET http://localhost:8000/media/Untitled.pdf 404 (Not Found) The path is correct but the file wasn't served. Do you have an idea where the problem is? -
Django SECRET_KEY SyntaxError: invalid syntax
Just started to learn Django and ran into an error. When starting migrations! I watched a video on YouTube. and fulfilled all the conditions as in the video. But I got an error https://b.radikal.ru/b20/2105/d8/428b3c29860e.png (venv) D:\django-sites\testsite\mysite>python manage.py makemigrations Traceback (most recent call last): File "D:\django-sites\testsite\mysite\manage.py", line 22, in <module> main() File "D:\django-sites\testsite\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\django-sites\testsite\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_comma nd_line utility.execute() File "D:\django-sites\testsite\venv\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Skyba Vyacheslav\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_mod ule return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\django-sites\testsite\mysite\mysite\settings.py", line 22 SECRET_KEY = 'django-insecure-v6o#d_au9g#5%3*s(-_vh7mq=!65v7446&m3q)+@zn2yd4806g' ^ SyntaxError: invalid syntax enter image description here """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.2. For more information on this file, see … -
Python List data to Django ORM query
Let say, I have a list data for example: data = [ {'id': 1, 'name': 'brad', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}}, {'id': 2, 'name': 'sylvia', 'color': 'blue', 'tags': [], 'author': {'name': 'user'}}, {'id': 3, 'name': 'sylwia', 'color': 'green', 'tags': [], 'author': {'name': 'admin'}}, {'id': 4, 'name': 'shane', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}}, {'id': 5, 'name': 'shane', 'color': 'red', 'tags': ['python', 'django'], 'author': {'name': 'user'}} ] and I want to make it ORM'able, such as what Django has doing: ModelName.objects.filter(color__icontains="gree") And this what I have do; import operator from collections import namedtuple from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist class DataQuerySet: """ Custom ORM for List dict data, https://stackoverflow.com/a/58351973/6396981 """ allowed_operations = { 'gt': operator.gt, 'lt': operator.lt, 'eq': operator.eq, 'icontains': operator.contains } def __init__(self, data): self.data = data def all(self): return self.data def filter(self, **kwargs): """ >>> kwargs = {'name': 'sylwia', 'id__gt': 1} >>> DataQuerySet().filter(**kwargs) [{'id': 3, 'name': 'sylwia', 'color': 'green'}] """ operation = namedtuple('Q', 'op key value') def parse_filter(item): """item is expected to be a tuple with exactly two elements >>> parse_filter(('id__gt', 2)) Q(op=<built-in function gt>, key='id', value=2) >>> parse_filter(('id__ ', 2)) Q(op=<built-in function eq>, key='id', value=2) >>> parse_filter(('color__bad', 'red')) Traceback (most recent call last): ... AssertionError: 'bad' … -
How to create a query across a M2M Relation with conditional aggregation in Django3?
I came up with this simple data model for a small quiz night. Now I want to create a queryset which contains the earned points (count if answer.is_correct is true) for each team and turn. Furthermore I want to show the earned points for each team in total. Unfortunately I dont get the annotate and values logic for Many2Many relations. class Team(models.Model): name = models.CharField(max_length=100) class Game(models.Model): attending_team = models.ManyToManyField(Team, blank=True) title = models.CharField(max_length=200) class Turn(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) title = models.CharField(max_length=200) class Question(models.Model): turn = models.ForeignKey(Turn, on_delete=models.CASCADE) question_text = models.CharField(max_length=500) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) is_correct = models.BooleanField(default=False) answer_text = models.CharField(max_length=500, blank=True, null=True) The leaderboard should look like the following table: Rank Team name Turn 1 Turn 2 Turn 3 Total 1 Team A 3 2 5 10 2 Team B 1 1 3 5 3 Team C 1 3 0 4 So I tried the following query in my view to display the total earned points per team: def leaderboard(request, game_id): game = Game.objects.get(id=game_id) turns = Turn.objects.filter(game=game) teams_turns = Team.objects.filter(game=game_id, answer__is_correct=True).annotate(num_correct_answers=Count('answer__id')) # example for total earned points of first team print(teams_turns[0].name, teams_turns[0].num_correct_answers) This works but I think it is not the best … -
Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "product-detail"
I'm struggling with DRF. When I try to obtain a list of products using: requests.get("http://127.0.0.1:8000/products/").json() Server error 500 occurs and an error is displayed as in the title: Could not resolve URL for hyperlinked relationship using view name "product-detail" However, when I try obtain a single product, request is successful: requests.get("http://127.0.0.1:8000/products/t/").json() {'id': 1, 'url': 'http://127.0.0.1:8000/products/t/', 'name': 't', 'slug': 't', 'description': '', 'order': 'http://127.0.0.1:8000/orders/1/', 'ingredients': '', 'allergens': '', 'suggested_products': [], 'image': None, 'available': True, 'price': 100.0, 'category': 'http://127.0.0.1:8000/categories/t/'} So what's the problem here? I'm not using app namespacing, so this is not the cause. Serializer code: class ProductSerializer(serializers.HyperlinkedModelSerializer): # TODO: Fix URL url = serializers.HyperlinkedIdentityField("product-detail", lookup_field="slug", read_only=True) category = serializers.HyperlinkedRelatedField("category-detail", queryset=Category.objects.all(), lookup_field="slug") image = Base64ImageField(max_length=settings.MAX_UPLOAD_SIZE, required=False) class Meta: model = Product fields = ("id", "url", "name", "slug", "description", "order", "ingredients", "allergens", "suggested_products", "image", "available", "price", "category") View code: class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = "slug" @method_decorator(cache_page(LONG_CACHING_TIME)) @method_decorator(vary_on_headers("Accept-Language")) def dispatch(self, *args, **kwargs): return super(ProductList, self).dispatch(*args, **kwargs) class ProductDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = "slug" Urlconf: path("products/", ProductList.as_view(), name="product-list"), path("products/<slug:slug>/", ProductDetail.as_view(), name="product-detail") Thank you. -
l have trying to send mail through django, but it got failed. I am not getting any error. But the page redirecting to the same page with different URL
While I am sending mail through django, I am not getting any error. But the page redirecting to the same page with different URL in web page and that URL is reflecting in console also. Finally the issue is "mail not sending" Here is the code in settings.py EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER='fhjfhfjs@gmail.com' EMAIL_HOST_PASSWORD='fjsfghsfjk@123' EMAIL_USE_TLS= True Here is the code in views.py from django.core.mail import send_mail from blog.forms import Email_Form def mail_view(request,id): post=get_object_or_404(Post,id=id,status='published') sent=False if request.method=='GET': form=Email_Form() else: form=Email_Form(request.POST) if form.is_valid(): cd=form.cleaned_data() send_mail('sub','message','jfsdhfsdjk@gmail.com',[cd['to']]) sent=True return render(request,'blog/sharebymail.html',{'post':post,'form':form,'sent':sent}) Here is the code in html file {%if sent%} <h1>Post Sent Successfully</h1> <h2>Post with title {{post.title}} information shared by email</h2> {%else%} <h1>Share Post "{{post.title}}" By Mail</h1> <form> {{form.as_p}} {%csrf_token%} <input type="submit" class="btn btn-primary btn-lg", value="Send Mail"> </form> {%endif%} Here is the url in which the page redirecting http://127.0.0.1:8000/4/share/?name=djfkj&email=fhsdjf%40gmail.com&to=fjshnf%40gmail.com&comments=kgjlfsgjfs&csrfmiddlewaretoken=RBXpbZW74LqvdRXdQLufO75rHmmXVMN8y9i1dN3Go9bBlpZTyEgtYEn2YGR3ZQDy -
The best way to connect Next.js CSR React app, Django and PostgreSQL
My question concerns programming a full-stack app. On the frontend, I have a Next.js React app. I want to render it on the client-side and probably use SWR. On the backend, I have a Django app with a PostgreSQL database. I have seen two approaches to make all of these work together. The first one is to use Django to serve Next.js React app with django-webpack-loader and then to load React app within Django template. The second one is to build two separate apps - frontend (Next.js) and backend (Django + PostgreSQL) and deploying them on two servers (e.g. Docker container). I have read this article and it makes me lean towards the second option. However, it is a pretty old solution and maybe some things have changed since then. What is the most optimal solution when it comes to connecting Next.js React Client-side rendered, Django and PostgreSQL? -
How to pass a Jinja variable inside a Svelte component (Django/Flask)
I have a Flask app, and I need to pass a variable called var to Svelte component App.Svelte In a HTML, I would do {{ var }} but this confuses Svelte as it uses { } for its delimiters, and says var is not defined. In Vue, we can define different delimiters for Jinja (such as []) to solve this problem, but in Svelte I could not find how to do it. How can I pass a variable to Svelte? -
Django how to change value in models field on button click
I've made a Django app which is like a trouble ticket. When a user click a specific button the ticket should automatically get closed i.e., a boolean field. I've been trying to save the value on button click but I'm getting an integrity error. Models.py class Risk(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) time = models.DateTimeField(default=timezone.now, blank=True) header = models.CharField(max_length=15, null=True) start_date = models.DateField(null=True, blank=True) ...... close = models.BooleanField(default=False) Views.py class PostUpdateView(LoginRequiredMixin, UpdateView): def form_valid(self, form): form.instance.author = self.request.user risk_id=self.kwargs['pk'] elif 'btn-close1' in self.request.POST: profil=get_object_or_404(Risk, pk=risk_id) profil.close=True profil.save(update_fields=["close"]) return super().form_valid(form) Error: IntegrityError at /RISK00069/update/ UNIQUE constraint failed: blog_risk.id Request Method: POST Request URL: http://127.0.0.1:8000/RISK00069/update/ Django Version: 3.2 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: blog_risk.id Exception Location: C:\Users\acchaka\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\acchaka\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Also, I would like to update "start_date" field on button click with todays date + 24 days, Please guide me on how to do that. -
How will I trigger a function on losing focus from TextInput in python Django?
I am following CS50W and have a project wiki in Django Python. I want to call a function from views.py to run when TextInput lose focus. and will try to validate that text from the topic list. function to be called from views.py def myCheckFunction(request, entry): page = util.get_entry(entry) if page is None: return HttpResponse('Title not found') else: return HttpResponse('Title exists') Entry in urls.py path("myCheckFunction", views.myCheckFunction, name="check"), NewPage.html <body> <form method="post"> {{ form }} </form> </body> createNewPage.html <form> {% csrf_token %} <div class="form-group" style="margin-right: 20%"> <label for="InputCaption"><b>New Page Title</b></label> {% include 'encyclopedia/newPage.html' %} <br> <label for="NewPageText"><b>Enter Page Text</b></label> <textarea class="form-control" id="NewTopicText" name="NewPageText" rows="14"></textarea> </div> <div class="btn-save-placement flex-container" style="height: 48px; padding-top: 0px;"> <button class="btn btn-outline-dark" type="submit">Save New Page</button> </div> </form> forms.py class CreateNewList(forms.Form): name = forms.CharField(label="", widget=forms.TextInput( attrs={ 'autofocus': 'autofocus', 'onfocusout': '/myCheckFunction/', 'class': 'form-control', 'placeholder': 'Type Topic Title Here...', })) -
Cannot validate input through == equals in Python
Im creating a Django web and able to let user select which parameter to parse the email ingestion function. When user click on "OK", the email ingest function will take the input parameter and validate through the if else statement . User can validate through Subject or text of an email and then it can parse with three conditions: equals, contain and does not contain. The subject part is all fine but when come to the text part, the equals is not functioning. It always return me no email even I entered the correct input to match. The main function of this program is able to send an email to a particular user when the condition is triggered. Views.py from django.shortcuts import render from django.http import HttpResponse import datetime import email import imaplib import mailbox import smtplib def index(request): return render(request,'DemoApp/hi.html') def send(request): EMAIL_ACCOUNT = "xxx@gmail.com" PASSWORD = "xxx" mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login(EMAIL_ACCOUNT, PASSWORD) mail.list() mail.select('inbox') result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN) i = len(data[0].split()) for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)') # result, email_data = conn.store(num,'-FLAGS','\\Seen') # this might work to set flag to seen, if it doesn't already raw_email = … -
Django could not parse the remainder javascript
Im new to django so any help would be appreciated im creating a django site but i cannot figure out how to redirect the url with javascript im getting this error Could not parse the remainder: '${id}' from '${id}' my function: function redir(id){ window.location.href = "{% url 'detail' ${id} %}" } my site: {% for item in store %} {% if item.available %} <div class="product-container" onclick="redir({{item.id}})"> <img src="{{ item.imageURL }}" alt="Photo" onerror="this.src='http://via.placeholder.com/640x360'"/> <h1>{{ item.title }}</h1> <h4>RS.{{ item.price|floatformat:2 }}</h4> </div> {% endif %} {% endfor %} thanks in advance -
How to implement partial data update without specifying an identifier (pk) in the url-path?
I am unloading all objects using generics.UpdateAPIView and generics.ListCreateAPIView: serializers.py: class ProductSerializer(WritableNestedModelSerializer): product_set = QuantitySerializer(many=True) class Meta: model = Product fields = ('code', 'name', 'price', 'product_set') views.py: class ProductsList(generics.UpdateAPIView, generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer urls.py: path('api/products/', views.ProductsList.as_view()), path('api/product_detail/<int:pk>/', views.ProductQuantityDetail.as_view()), Updating, adding data for an object is obtained if I go specifically along the path api/product_detail/int:pk/. I would like to directly be able to partially update the data using the method PATCH/PUT in api/products/, but I get the error: Expected view ProductsList to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. I would be glad for any help, maybe someone came across this. -
how to add crontab by docker
I am new in docker world and I wrote a function for cronjob and define in settings.py as bellow: CRONJOBS = [ ('* * * * *', 'apps.quiz.cron.quiz_status_change'), ('* 11 * * *', 'apps.quiz.cron.quiz_winner_notification_for_payment')] I changed my Dockerfile to insatll cron as bellow: RUN apt-get update && apt-get install -y cron here is my docker-compose file version: "3" services: web: build: . command: bash -c "python manage.py crontab add && python manage.py runserver 0.0.0.0:8000" env_file: - /home/krypton/edubook_project/edubook_backend/.env volumes: - .:/edubook ports: - "8000:8000" now when i up my docker image i am getting error of no crntab for root -
How to update excel files on django and upload them to sharepoint
I have been asked to create a web page with django, with a button in it, which when clicked runs a python script in command prompt in your system. It updates an excel file, from which data is to be extracted and updated to another excel which will be available in microsoft sharepoint. The file with the required python and excel files is given and are not to be disturbed. I have created the web page in django and and the button as well. I have also written a python script which extracts the data and updates in the other excel file which is as follows import pandas as pd import openpyxl as op def xl(): A = pd.read_excel('testcase_database.xlsx') #The excel file from which the data is to be taken B = pd.read_excel('S32K3XX_SecureBAF_Sprint3_Test_Report.xlsx', sheet_name='Test_Report') #The excel file to which the data is to be updated tcname = A['Unnamed: 2']#Test case nams in A fcname = B['Unnamed: 5'] #Test case names in B pi = A['Unnamed: 5'] #Results in A temp = "" temp1 = "" #To compare the test case names in A and B and then printing that test case result in B for i, temp in enumerate(tcname): for … -
Django How to return object.filter query results so I don't have to iterate through them
I am trying to return only one result from a query and return it as an object so I can call its' attributes in my template without having to iterate over them. Basically, I have a landing page that iterates a list of objects on table1 and creates a link for each one, like product listings. When I click on a link, it presents data from that object on the page. I want to also present data from the object on table2 that has the foreign key to the objects whose page I am currently on. The problem is I am returning an iterable item from table2, so in order to present that data, I have to run a for loop. It only returns one item, so it doesn't make a difference in how the page looks, but I would like to accomplish the same thing without the for loop. models.py class Exercises(models.Model): exercise = models.CharField(max_length=45) evolution = models.CharField(max_length=8) start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) logo = models.TextField(blank=True, null=True) class Meta: constraints = [ models.UniqueConstraint( fields=['exercise', 'evolution'], name='exercise_evolution_UNIQUE') ] def __str__(self): return f"Exercise: {self.exercise}\t Evolution: {self.evolution}" class Units(models.Model): uic = models.CharField(max_length=10) unit_name = models.CharField(unique=True, max_length=45) mcc = models.CharField(max_length=5, … -
Django admin list_filter on custom model function
In my django model i create a custom function for retrive a data from another model like this: class UserProfile(models.Model): ... def card_type(self): if self.user: return a_cards.objects.get(c_user = self.user.id).c_type return "-" card_type.allow_tags = True card_type.short_description = "Card Type" then in my admin i do: list_display = ('u_sname', 'u_name','user_link', 'card_type', ... all was done, but if i try to filter using my custom method: list_filter = ('card_type',) i get: ERRORS: <class 'agenti.admin.UserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'card_type', which does not refer to a Field. How can i filter data using my custom model function returned vals? So many thanks in advance -
Vue router permission based on User Role from Django Rest Framework
I have Django and Vue project and I need to add permissions in the Vue router based on user role. I managed to do this in the template by accessing the user data from my user API. <li class="nav-item active mx-1 mb-1"> <router-link v-if="user_data.role != 2" :to="{ name: 'activities' }" class="btn btn-sm btn-success" >Activities </router-link> </li> <script> import { apiService } from "@/common/api.service.js"; export default { name: "NavbarComponent", data() { return { user_data: {}, } }, methods: { setRequestUser() { this.requestUser = window.localStorage.getItem("username"); }, getUserData() { // get the details of a question instance from the REST API and call setPageTitle let endpoint = `/api/user/`; apiService(endpoint) .then(data => { this.user_data = data; }) }, }, computed: { isQuestionAuthor() { return this.requestUser === 'admin_user'; }, isUser() { return this.requestUser; }, }, created() { this.setRequestUser() this.getUserData() } }; </script> The user doesn't see the button but can still access the pages if enter the path directly in URL. I can't find a workaround to get the same user data from user API and use it to manage route permissions based on user.role My router.js looks like this: Vue.use(VueRouter); const routes = [ { path: "/", name: "home", component: Home }, { path: … -
CPanel RAM issue
We are facing RAM issue in our CPanel. I have a gaming website which run a game everyday for 15 minutes at that time 1,500+ people visit my website , so my CPanel's RAM gets upto 90%. I have talked to go-daddy and they said you have purchased plan which supports 1,50,000 user at a time and you don't need to get any premium package there is some error in your website's code side. Our code is made in Django and I am working hard enough to figure out whats wrong but am unable to get a resolve. Basic procedure: Its a live tombola website at 5 pm our cron job sets our python program run and start generatng new no. every ten second and save them to database and it does so. Next our javascript code hits api and gets list of no. which are called and shows them to dashboard according. Now the problem is this in this whole procedure where our server is facing problem,is it javascript problem, api problem or python code problem or django framework problem. -
Saving different models in ModelSerializer create not working
I have a ModelSerializer for Booking model in its create method i have to update a field for Room model. But the Room model instance is not updated. Even though the Booking object is created class BookingCreateUpdateSerializer(serializers.ModelSerializer): room = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all()) booking_status = serializers.ChoiceField(choices=BookingStatus.choices()) class Meta: model = Booking fields = [... ] def to_representation(self, instance): return BookingDetailSerializer(instance=instance,context=self.context).to_representation(instance) @transaction.atomic def create(self, validated_data): room = validated_data['room'] booking_status = validated_data.pop('booking_status') room.booking_status = booking_status room.save() validated_data['room'] = room return super().create(validated_data) Expected Results Room.booking_status should be set Current Results Room.booking_status is not set -
Getting { "non_field_errors": [ "login failed" ] } when trying to login
{ "non_field_errors": [ "login failed" ] } Getting this error when trying to log in. I'm using Custom User with email as username required. Providing the serializer, custom user models and views below. Please let me know if any other details are required in the comment section. Thanks in advance. Custom user model class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) first_name = models.CharField('First Name', max_length=255, blank=True, null=False) last_name = models.CharField('Last Name', max_length=255, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() serializer.py class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=50) password = serializers.CharField(max_length=50) def validate(self, data): email = data.get("email") password = data.get("password") obj = User.objects.get(email=email) user = authenticate(email=email, password=password) if user: data['user'] = user print(user.id) else: msg = 'login failed' raise exceptions.ValidationError(msg) return data views.py class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] djangologin(request, user) token, created = Token.objects.get_or_create(user=user) return Response({'message': 'You have successfully Logged in.', 'user': user.id, 'token': token.key}, status=200) -
pyinstaller and django-import-export lib
I created a Django app that use django-import-export library to import and export data, then i created an EXE file from this project by Pyinstaller whit the aim of running it as a windows program. but when i open Django admin in the browser, i get this errors: TemplateDoesNotExist at /admin/export/ admin/import_export/export.html and then : 'import_export_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I think the reason for it is Pyinstaller not import django-import-export library , I use hidden-import and creating hook file to import django-import-export, but not working for me :( -
Is it right to use the Json file as a site information and settings (Django)?
I have a django project. And I want to use a JSON file for site information and settings (Like phone number | About Text | Contact Us information). Like this ---> { "about_text": "Hi this is about text", "phone": "0912------984", "email": "text@text.com" } And using these in View... import json from django.shortcuts import render def about(request): with open("data_file.json") as f: data = json.load(f) context = { "about_us_text": data.about_text # Using *marked* lib to render to html (In template) } return render(request, 'about.html', context) Is it correct? Is not the solution the best? Doesn't it cause a problem? I think there is a better solution because it might take time and slow down the program... . -
How to set up a webpage with the following functionalities
I have an assignment where, I have to create a web page using django, which should include a clickable button, which when clicked should run a python script in the command prompt on your system, after running the python file, it updates an excel file with the results and then data from it is to be extracted and be updated to another excel file, and these files have to available in microsoft sharepoint for multiple users to check those files. The python script, and the excel files are in a file structure with multiple folders and files.I am not allowed to edit the python file or the file structure the file is in, as any changes to it will affect the automatic update of the excel file. Can anyone help me with how to go about it? Thanks. -
Django: Filtering model entries that doesn't have a related OneToOne entry in another model
I have two models class Bike(models.Model): ... ... another one class Sell_info(models.Model): ... ... bike = models.OneToOneField(Bike, on_delete=models.CASCADE, related_name="sell_info") I am filtering those Bikes that don't have a related Sell_info entry available. bikes = Bike.objects.filter('sell_info__isnull=True') but it get this problem ValueError at /new-bikes/ too many values to unpack (expected 2)