Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
How to return queryset instead of list?
models class Permission(models.Model): name = models.CharField(max_length=250, unique=True) class PermissionDetail(): perm = models.ForeignKey( Permission, on_delete=models.CASCADE, related_name='perm_details') group = models.ForeignKey( 'Group', blank=True, null=True, related_name='group_perms', on_delete=models.CASCADE) class Group(): name = models.CharField(max_length=250) users = models.ManyToManyField(User, blank=True, related_name='groups') permissions = models.ManyToManyField(Permission, blank=True, related_name='permissions') what I did: user_groups = user.groups.all() perm_details = [] for group in user_groups: perm_details.append(group.group_perms.filter(perm=perm)) return perm_details This returns the correct list of data but I want queryset instead of list. How can I return the queryset instead of making list here ? -
when client request to server, there is an error, saying 'Permission denied' from static directory
it seems like Nginx can not access the static files. I checked /var/log/nginx/error.log and got the following messages; after checking this message, I put this code 'chmod -R 755' but it did not work (even 777) of course I did collectstatic and point to static root before this matter happened. I don't know why this happened and how to fix it... I have been struggling with this matter for more than 3 days now 2021/05/12 00:17:07 [error] 12940#12940: *10 open() "/home/admin/github/djangobook/static/admin/css/nav_sidebar.css" failed (13: Permission denied), client: 101.191.5.33, server: 149.28.172.215, request: "GET /static/admin/css/nav_sidebar.css HTTP/1.1", host: "easycoding.live", referrer: "http://easycoding.live/admin/login/?next=/admin/" 2021/05/12 00:17:07 [error] 12940#12940: *2 open() "/home/admin/github/djangobook/static/admin/css/base.css" failed (13: Permission denied), client: 101.191.5.33, server: 149.28.172.215, request: "GET /static/admin/css/base.css HTTP/1.1", host: "easycoding.live", referrer: "http://easycoding.live/admin/login/?next=/admin/" 2021/05/12 00:17:07 [error] 12940#12940: *8 open() "/home/admin/github/djangobook/static/admin/css/login.css" failed (13: Permission denied), client: 101.191.5.33, server: 149.28.172.215, request: "GET /static/admin/css/login.css HTTP/1.1", host: "easycoding.live", referrer: "http://easycoding.live/admin/login/?next=/admin/" 2021/05/12 00:17:07 [error] 12940#12940: *8 open() "/home/admin/github/djangobook/static/admin/js/nav_sidebar.js" failed (13: Permission denied), client: 101.191.5.33, server: 149.28.172.215, request: "GET /static/admin/js/nav_sidebar.js HTTP/1.1", host: "easycoding.live", referrer: "http://easycoding.live/admin/login/?next=/admin/" 2021/05/12 00:17:18 [error] 12940#12940: *1 open() "/home/admin/github/djangobook/static/admin/css/nav_sidebar.css" failed (13: Permission denied), client: 101.191.5.33, server: 149.28.172.215, request: "GET /static/admin/css/nav_sidebar.css HTTP/1.1", host: "easycoding.live", referrer: "http://easycoding.live/admin/" 2021/05/12 00:17:18 [error] 12940#12940: *10 open() "/home/admin/github/djangobook/static/admin/css/dashboard.css" failed (13: Permission denied:```` -
AttributeError at / 'dict' object has no attribute '_mptt_meta'
I try to build blog by using posts and MPTT comments, this will be in the home view www.mysite.com that's mean I cann't pass pk to the url so I tried to get the post objects using for loop comma = Post.objects.all() comm = [] for post in comma: comment = PostCommentIDF.objects.filter(post=post) comm.append({"comme": comment} And my Mptt comment model class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() created_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) likes = models.ManyToManyField(Account, blank=True, related_name='pos_com') My Post Model class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) article = models.TextField(null=True, blank=True) photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath) My mptt coments in the template {% recursetree comment %} <div id="{{ node.id }}" class="my-2 p-2" style="border: 0px solid grey"> <div class="d-flex justify-content-between"> {{ node.publish|naturaltime }} <div class="node-content mt-3">{{ node.content }}</div> </div> {% endrecursetree %} -
Django DRF not returning image field url
I am trying to get the figure field url in get request. However, I am getting error or null value. Question Model class Question(models.Model): """ Base class for all question types. Shared properties placed here. """ quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) sub_category = ChainedForeignKey(SubCategory,blank=True,chained_field="category",chained_model_field="category",show_all=False,auto_choose=True,sort=True,null=True) topic = ChainedForeignKey(Topic,blank=True,chained_field="category",chained_model_field="category",show_all=False,auto_choose=True,sort=True,null =True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Figure")) Serializer.py class QuestionSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField('get_image_url') getanswers = ChoiceSerializer(many=True) figure = serializers.ImageField( max_length=None, use_url=True ) class Meta: fields=( 'id', 'content', 'figure', 'questionmarks', 'getanswers', 'image_url', ) model=Question def get_image_url(self, obj): request = self.context.get("request") return request.build_absolute_uri(obj.figure.url) I keep getting error. Could some please guide me with the right way to achieve this? -
Django: How to test whether a user is a member of a subclass of django auth Group?
I have the following: class Department(Group): hod = models.ForeignKey(User, models.CASCADE, blank=True, null=False) # Other fields and I need to check whether a user is a department member. Do I go: if user.groups.filter(department__pk=department.pk).exists(): # Do something or: if user.groups.filter(pk=department.pk).exists(): # Do something or is there a better way to check this? Thanks -
Page not found error / url is not working with pk
I m working on learning Django with MDN project on Local Library. My two pages are rendering whereas the book detail page is not rendering and giving error page not found. Please advice what if I have missed anything: So far entire project is on MDN documents. catalog/urls.py from django.urls import path from catalog import views app_name = 'catalog' urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), ] catalog/templates/catalog/book_detail.html {% extends 'catalog/base.html' %} {% block content %} <h1>Title: {{ book.title }}</h1> <p><strong>Author:</strong> <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a></p> <p><strong>Summary:</strong> {{ book.summary }}</p> <p><strong>ISBN:</strong> {{ book.isbn }}</p> <p><strong>Language:</strong> {{ book.language }}</p> <p><strong>Genre:</strong> {{ book.genre.all|join:", " }}</p> <div style="margin-left:20px;margin-top:20px"> <h4>Copies</h4> {% for copy in book.bookinstance_set.all %} <hr> <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'd' %}text-danger{% else %}text-warning{% endif %}">{{ copy.get_status_display }}</p> {% if copy.status != 'a' %}<p><strong>Due to be returned:</strong> {{copy.due_back}}</p>{% endif %} <p><strong>Imprint:</strong> {{copy.imprint}}</p> <p class="text-muted"><strong>Id:</strong> {{copy.id}}</p> {% endfor %} </div> {% endblock %} catalog/templates/catalog/base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static 'catalog/style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"/> {% block title %} <title></title> {% … -
TypeError object is not iterable in Django
I am creating a movie site using Django. I have created a Genre model in it and displayed it in the template. Now i want those each genre objects to redirect to some other page. For example i have created 45 genre types and displayed in the template. Now what i want to do is, redirect user to for example Action genre list when clicked on Genre Action in the template. For that i used for loop in template but when clicked in any of the genre objects it throws TypeError at /home/genre/5/ 'Genre' object is not iterable. What is the problem here? Any suggestions will be great. my urls.py: urlapatterns = [path('', views.home, name='home'), path('genre/<int:pk>, views.genreView, name='home')] views.py: def genreView(request, pk): genres = get_object_or_404(Genre, id=pk) context = { 'genres': genres } return render(request, 'genre.html', context) def home(request): genres = Genre.objects.all() context = { 'genres': genres } return render(request, 'index.html', context) home.html: {% for genre in genres %} <a href="{% url 'genre' genre.id %}" class="text-yellow-400 hover:text-white p-2 text-xs">{{genre.title}}</a> {% endfor %} models.py: class Genre(models.Model): title = models.CharField(max_length=500) def __str__(self): return self.title -
Customize the Django ContentTypes and AdminLog and Migration model
I am working on a Django project and it requires 3 different database servers with different engines like MySql, PostgreSQL and SQLite. SQLite has all the client side setting table, tables with not shared data [app has a feature to not upload some data to the server] and configuration tables and it is on the client machine through a tweaked C# app to create a django server environment and show the django site in a browser control like a native application. PostgreSQL has tables that can be accessed by different clients on the network and has different tables with values of shared data. They maintain integrity with SQLite data through ContentType. Django provides the contentType table that is created in both SQLite and PostgreSQL. Due to heavy use of other database managing tables we require them to be in a MySQL database on a separate server. So it would be great to have django_content_types, django_admin_log and django_migration in that MySQL server. ContentTypes table is also used a lot and it is difficult to maintain contentTypes form two different database tables so we require it to be in one separate one with values form both the databases. And when one goes … -
Is there a way that django access the cookies stored by the browsers for authentication?
I have developed an internal website for my org ,which used some authentication at browser level (like login),they will authenticate on the start of the day and they want that authentication to even visit my website .I am accessing another service in the back-end which requires the same cookies which was stored by the browser when they authenticate .Is there a way i can get that cookies from the browser storage? -
Send image via post request to ImageField
I have a model with API for an ImageField. I need to send image fetched via post method on the template and send it via post request to the API created. The image fetched has a type InMemoryUploadedFile, if I try to send it directly, I get 406 because of failed serializer validation. So I tried making a PIL object out of it and tried sending. I checked the JS counterpart of the code and it just takes the file from the input field and sends it directly to the same field and it works. Is there a way I can just send an image file object via post request to fail serializer validation. category_thumbnail = request.FILES.get('category_thumbnail') category_thumbnail = Image.open(category_thumbnail) data = { 'category_thumbnail': category_thumbnail } This would give me 406. I also tried converting image string to a base64 byte object. category_thumbnail = request.FILES.get('category_thumbnail') category_thumbnail = Image.open(category_thumbnail) with io.BytesIO() as output: category_thumbnail.save(output, format="GIF") contents = output.getvalue() category_thumbnail = base64.b64decode(contents) data = { 'category_thumbnail': category_thumbnail } but this would give me 406 too. I wonder if there's a way I can just send the image file object taken from InMemoryUploadedFile. Also tried category_thumbnail = request.FILES.get('category_thumbnail').file -
Django-Email, sending multiple email depends on Email ID
Anyone know how to solved my issue, Im working with DJango-email with multiple recipient. Sending email in multiple recipient accounts from my DB are working, but now I want to send email and the email:body are depending on the Data ID. This are the email list, Scenario: Plate_No: 123123 will be send to example_email1@gmail.com only and ABV112 will be send again to example_email2@gmail.com and so on. Only the Plate_no assign in email will send, can someone help me to work my problem. Thank you! Here are my auto send email script: class HomeView(ListView): cstatus = VR.objects.filter(Deadline__date = datetime.datetime.today(), sent_email="No") print(cstatus) recipient_list = [] for recipient in cstatus: recipient_list.append(recipient.email) print(recipient_list) plate = "" for carreg in cstatus: print(carreg.plate_no) plate = carreg.plate_no if plate != "": subject = 'FMS Automated Email' html_message = render_to_string('vr/pms_email.html', {'content':cstatus}) plain_message = strip_tags(html_message) from_email = 'FMS <fms@gmail.com>' mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False) cstatus.update(sent_email="Yes") model = VR context_object_name = 'list' template_name = 'vr/list.html'