Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model React
I'm trying some Django + React stuff and I'm a bit confused with the particular role of Django model in this scheme. As I can understand Django model provide smooth way to create some typical forms by users of the site (please correct me). And I can't feel the edge of what should be hardcoded and what I need to store in model. In case of React (I'm trying to connect react with django through api via djangorestframework) should I create a model for Header? And store bg image with it and my slogans. I feel it's should be purely in frontend. But next section with 3 typical screens (they will be listed horizontally and swap each other). They are just copy of each other with different data (title, bg, fg, text, link), for me it seems closer to model usage. But model initially empty and if I want to get this data from model I firstly need to somehow store this data to model. ofc I searched this info widely but so far can't create clear understanding by myself. Thanks ) -
Delete files and directories that are older than 30 days in specific path [closed]
How can I delete all the files and directories in a specific directory that are older than 30 days? -
Refresh displayed data on click in Django app
I am using Ajax to get the appropriate url that displays orders based on the date that was clicked in a calendar. This works, but every time user clicks on a date, the content duplicates, not removing the previous display. https://i.stack.imgur.com/nEdWg.png I would like the content to refresh, when the user clicks on a date again. How would I do that? I was searching for a "Jquery refresh DIV", and stumbled upon location.reload(), ajax.reload(), jquery load method, and similar solutions. I tried implementing these, but not sure if they are the right solution for my case. Here is my code. Please let me know if I should post anything else. Help appreciated. .js $(function () { var $archive = $('#orders-per-day'); $(".day-click").click(function (event) { event.preventDefault(); var day = $(this)[0].innerText; var month = $(".month")[0].innerText.substring(0, 3); var year = $(".month")[0].innerText.substr(-4); console.log(year); $.ajax({ type: 'GET', url: `/ocal/date/${year}/${month}/${day}/`, success: function (data) { $archive.append(data); } }) }); }); html template for showing the orders of one day {% extends 'ocal/base.html' %} {% block content %} <h1>Orders for {{ day }}</h1> <ul> {% if object_list %} {% for order in object_list %} <li> <a href="/ocal/{{ order.id }}/detail">Order {{ order.id }} </a> {{ order.status_str }} </li> {% endfor … -
Django Dynamic form for manytomany relationship
I am trying to make a form which includes the functionality of Add/Delete Row. This question needs a detailed answer and it's quite important Models.py class Inserts(models.Model): no_of_inserts_perit = models.IntegerField(default=0, blank=True, null=True) insert_length = models.IntegerField(default=0, blank=True, null=True) insert_breadth = models.IntegerField(default=0, blank=True, null=True) insert_height = models.IntegerField(default=0, blank=True, null=True) class Pfep(models.Model): created_by = models.ForeignKey("packsapp.Employee", on_delete=models.CASCADE, related_name='ffco_createdby') receiver = models.CharField(max_length=250, default=0 ,blank=True, null=True) receiver_location = models.CharField(max_length=250, default=0 ,blank=True, null=True) inserts = models.ManyToManyField(Inserts) In my form I need a Add Row and Delete Row button for inserts fields. I have never worked with a manytomany relationship but upon googling I ended up with the conclusion that inline_formset is used for this, is it ? This is how I am creating the rest of form: Views.py @method_decorator([login_required, employee_required], name='dispatch') class PfepFormView(CreateView): model = Pfep form_class = Pfepform template_name = 'pfep/PfepForm.html' def form_valid (self, form): if self.request.user.employee.employee_role == 'admin': product = form.save(commit=False) product.created_by = Employee.objects.filter(user=self.request.user.id)[0] product.save() messages.success(self.request, 'The PFEP was created with success!') return redirect('emp:pfep_table') else: messages.success(self.request, "You don't have permission to create PFEP!") return redirect('emp:pfep_table') return redirect('emp:pfep_table') Forms.py class Pfepform(forms.ModelForm): class Meta: model = Pfep fields = '__all__' exclude = ["created_by"] HTML <h2 class="mb-3">Add a new PFEP</h2> <div class="row product-form-row"> <form method="post" class="col-md-12 proct-form" novalidate> … -
Django button to run script (to populate a database)
I have a pre-built python script that collects Google Analytics data, I am using this script to populate a database. I have been given the instruction to write a web app where all of this data can be displayed in the form of a dashboard.. I want the user of the web app to be able to click on a button and then all the latest Google Analytics data will be pulled and added to the database in the backend and then the dashboard will display updated values.. But it seems like I can only add data to the db via the python shell? I have a script that can do that.. But I am confused as to where in django should I have this script and how to implement it Should I put it in views, models or a separate file PS: I would post the script but it is 400 lines of code to get that data -
Problem with dynamic image path in Django
I'm trying to pass a dynamic url of an image, to be displayed in a template. This is my view function: def success(request): id_image = request.session.get('image_id') obj = EvalImage.objects.get(id=id_image) url = obj.Patient_Main_Img.url return render(request, 'myapp/success.html',{'image_url': url}) If I call {{image_url}} in the template, I get the correct path: myapp/media/images/15_LgiRvs6.jpeg But, if I use it into a img tag, like the following: <img src="{{image_url}}" class="rounded mx-auto d-block" alt="RX" width="300" height="300"> I get an error because the template is unable to find the file. The problem is that the template is looking for the file at: /myapp/eval/myapp/media/images/15_LgiRvs6.jpeg I don't understand why is the tag changing the path to the file. From settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'myapp/media') MEDIA_URL = 'myapp/media/' Thank you -
How do i show the list of items which belong to the same category using Django Python?
I have Shop page and it displays list of shops when i click on one shop i want the other page to display the related list of products for that page only. def shop_products(request, id): shops = Product.objects.all() return render(request, 'products/shop_products.html', {'shops': shops}) path path('products/<int:id>', views.shop_products, name='shop-products'), <a href="{% url 'shop-products' product.id %}" class="grey-text"> The clickable link Using the above code it is displaying all the products of every shop -
How to delete multiple objects in django?
I am trying to delete django model multiple objects using html checkboxes but i can't. Kindly guide me what I need to do complete my this task. I try the following code for this purpose but i failed. views.py class DeleteProducts(SuccessMessageMixin, View): success_url = reverse_lazy('stock:stock') success_message = "Products are deleted successfully." def post(self, request, *args, **kwargs): products = self.request.POST.getlist('product') Product.objects.filter(pk__in=products).delete() messages.success(self.request, self.success_message, extra_tags='alert-danger') return redirect('stock:stock') In template i used checkboxes prefectly or not?? template.html <form method="POST" action="{% url 'stock:deleteproducts' %}"> {% csrf_token %} {% for product in page_obj %} <div class="row" > <input type="checkbox" value="{{ product.id }}"> <div class="col-sm-2" > <h5>{{ product.id }}</h5> <img src="{{ product.Picture.url }}" height="120px" /> </div> <div class="col-sm-4" > <h5><u>Product Name</u>: {{ product.pro_name }}</h5> <h6><u>Company Name</u>: {{product.companyName}}</h6> <div class="row" > <div class="col-sm" > <p>Purchase Price: <b>{{product.Purchase_Price}}</b></p> </div> <div class="col-sm" > <p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p> </div> </div> <div class="row" > <div class="col-sm" > <p>Quantity <b>{{product.Quantity}}</b></p> </div> <div class="col-sm" > <p> Added By: <b>{{product.saler}}</b> </p> </div> </div> </div> <div class="col-sm-4" > <p><b>Added Date</b>:{{ product.pub_date }}</p> <hr/> <center> <a href="{% url 'stock:editproduct' product.id %}" class="btn btn-success" >Edit</a> </center> </div> </div> <hr/> {% endfor %} <input type="submit" class="btn btn-danger" value="Delete" > </form> urls.py path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'), -
self.scope['user'] in Django channels keeps showing up as AnonymousUser
When I log in to my front end, my self.scope['user'] call in my friends.consumer.py in django channels returns AnonymousUser but when login and call self.scope['user'] in my chat.consumer.py it shows up as the logged in user. For some reason the scope['user'] in one of my apps work and the other one does not. I do not understand what the problem is. I have the routing set up in my django project as this routing.py from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import chat.routing import friends.routing application = ProtocolTypeRouter ({ 'websocket': AuthMiddlewareStack( URLRouter( friends.routing.websocket_urlpatterns + chat.routing.websocket_urlpatterns ) ) }) I structure my second consumer.py similarly to my first consumer.py. This is my consumer.py where the scope['user'] works (I didn't need the scope['user'] in the first consumer but I just wanted to test to see if it works chat.consumer.py class ChatConsumer(WebsocketConsumer): ... def connect(self): print(self.scope['user']) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync (self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() This code is the consumer where my scope['user'] shows up as anonymous user even after I have logged in. friends.consumers.py class FriendRequestConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope['user'] grp = 'notifications_{}'.format(user.username) self.accept() async_to_sync(self.channel_layer.group_add(grp, self.channel_name)) Here are also my … -
How to use dynamic tabs in django?
I am trying to implement dynamic tabs in my project that gives multiple tabs based on the values stored in the database. In my case, I have two values stored in database so it's displaying just two, If I will increase more, it will show accordingly. Category.objects.filter(category='MEDICINES') Out[14]: <QuerySet [<Category: FRUITS>, <Category: GRAINS>]> Here is my models.py file, from django.db import models from django.contrib.auth.models import User STATUS = ((0, "Draft"), (1, "Publish")) class Category(models.Model): category_names = ( ('DISEASES','DISEASES'), ('MEDICINES','MEDICINES'), ('ENCYCLOPEDIA','ENCYCLOPEDIA'), ) category = models.CharField(max_length=100, choices=category_names) sub_category = models.CharField(max_length=100, unique=True) def __str__(self): return self.sub_category class Medicine(models.Model): title = models.CharField(max_length=200, unique=True) display_name = models.CharField(max_length=17, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='medicine_posts') category = models.ForeignKey(Category, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("medicine_detail", kwargs={"slug": str(self.slug)}) Here it my views.py file, from django.views import generic from .models import Medicine, Category from django.shortcuts import render, get_object_or_404 class MedicineList(generic.ListView): queryset = {'medicine' : Medicine.objects.filter(status=1).order_by("-created_on"), 'category' : Category.objects.all() } #queryset = Medicine.objects.filter(status=1).order_by("-created_on") print(queryset) template_name = "medicine.html" context_object_name = 'element' #paginate_by = 10 Here is my medicine.html file, <div class="container"> <div class="row"> … -
posting date in dd-mm-YYYY format in django rest framework
I have set my Date_INPUT_FORMATS = "%d-%m-%Y" in settings.py file. Below is my settings File - REST_FRAMEWORK = { 'DATE_INPUT_FORMATS': "%d-%m-%Y", 'DATE_FORMAT': "%d-%m-%Y", 'DATETIME_FORMAT': "%d-%m-%Y %H:%M:%S", } I have a model with joining date As below : class Employee(models.Model): joiningDate = models.DateField() name = models.CharField(max_length=50) My Serializer : class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ['joiningDate', 'name'] Viewset : class EmployeeViewSet(ModelViewSet): queryset = models.Employee.objects.all() serializer_class = serializers.EmployeeSerializer This is the json I am trying to post: { "joiningDate":"31-03-2020", "name":"EMpname", I think I have set it up correctly but while posting I am getting the following Error: "joiningDate": [ "Date has wrong format. Use one of these formats instead: %, d, -, %, m, -, %, Y." ] Can anyone guide me in the right direction? What did I miss? Thanks a lot in advance for your responses -
No module named settings error django elastic beanstalk
I'm trying to deploy a django app to elastic beanstalk. Beanstalk can't find the settings file when loading wsgi.py. I've seen this in a few other SO questions, but none of those solved my issue. I get the following error: ModuleNotFoundError: No module named 'kairos_app.prod_settings' Target WSGI script '/opt/python/current/app/kairos_app/kairos_app/wsgi.py' cannot be loaded as Python module. These are the contents of the 02_python.config file under .ebextensions: container_commands: 01_migrate: command: "source /opt/python/run/venv/bin/activate && python3 kairos_app/manage.py migrate --noinput" leader_only: true 02_collectstatic: command: "source /opt/python/run/venv/bin/activate && python3 kairos_app/manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "kairos_app.prod_settings" "PYTHONPATH": "/opt/python/current/app/kairos_app:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: kairos_app/kairos_app/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "www/static/" And this is what the directory structure looks like: It seems to pick up the WSGIPath okay, so I'm not sure why it can't pick up the django settings module path. -
populate GeoDjango PointField
I am going through the trouble to populate GeoDjango PointField. this is my model: class Shop(models.Model): name = models.CharField( max_length=50, ) location = models.PointField( null=True, blank=True ) I am not getting how to populate this PointField. I tried with like this: lat = 'nnnnnnnnnn' long = 'xxxxxxxxx' Shop.objects.create( name='example name', location=Point(lat, long) ) but it is not populating properly, I am not getting what is the right way to pupulate this pointField. Can anyone help me in this case? -
Django - The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead
I am building an customer management app and have built few decorator's. but when i run the app give this error The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead. decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') elif request.user.is_authenticated == None: return redirect('login') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user-page') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function and my views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from .models import * from .forms import OrderForm, CreateUserForm, CustomerForm from .filters import OrderFilter from .decorators import unauthenticated_user, allowed_users, admin_only # Create your views here. @unauthenticated_user def registerPage(request): form … -
Elasticsearch DSL query with specific Output
I have a few objects in the database: object 1, object 2, object 3, .., object n Now I am doing filter like this MyDocument.search().filter("match", is_active=True).sort('id').execute() Output: searchDocumentobject 1, searchDocumentobject 2,searchDocumentobject 3, .... Now I need to searchDocumentobject 2 in last from the list. Need the output like this: searchDocumentobject 1,searchDocumentobject 3, .... , searchDocumentobject 2 Thank you -
Using python and django to test for reference value
I am someone who is both a doctor and researcher. I want to improve the work process of our department nurses by creating python code (which partly I already made in python) to help most beginning nurses. The issue i can get my head around is trying to link my python code (input) to a webform like in django and for it to return the conditions i have set. Ideally I want to end up for a webpage with a form asking multiple questions (multiple choice), which will return and action for the nurses to perform. I am sorry if this is a very basis and easy question. -
Access table field dymanically in django using for loop
def xyz(): site_data=site.objects.all() site_fields = site._meta.get_fields() site_fields_name = [f.name for f in site_fields][1:] return render(request, "Demoapp/InputGssA1.html", {'headers': table_structure,'site_data':site_data,'site_fieldname':site_fields_name}) this is i am render from function inside view.py and want to show in table format in InputGssA1.html, here table code is like {% for i in site_data %} <tr> {% for x in site_fieldname %} <td>{{i.x}}</td> {% endfor %} </tr> {% endfor %} but problem is I can't access object.fieldname using i.x in my code , i.fieldname statically work but this way it not working, How I access object's fieldname this way inside template tag?? -
Permission Error: [WinError 32] The process cannot access the file because it is being used by another process Django
I am dealing with pdf on my web page using PyMuPdf library(other pdf reading libraries are not working properly for me) ,the user is uploading a pdf file which is been saved in FileSystemStorage because I am unable to read it without saving it(would appreciate if you could suggest a way to do it without saving the file) now after reading the pdf I am using the command os.remove({}.fromat(pdf_path)) to delete it from file system which causes the above mentioned error below is my code def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() fs.save(uploaded_file.name,uploaded_file) pdf_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name) doc = fitz.open("{}".format(pdf_path)) #doing some thing with the content of pdf doc.close() os.remove(pdf_path) return render(request,'upload.html',context) -
how to assign foreign key for two different types of classes
I have 3 classes: class Student(models.Model): name=models.CharField(max_length=200) class Background(models.Model): stud_name=models.CharField(max_length=200) surname=models.CharField(max_length=200) address=models.CharField(max_length=200) class Meta: managed=False db_table='background' class Class101(models.Model): stud_name=models.CharField(max_length=200) math=models.DecimalField(max_length=200) english=models.DecimalField(max_length=200) class Meta: managed=False db_table='class101' Class Student is input model whereas class Background and Class101 are static data taken from DB. When user writes down name the code goes and matches naem to stud_name in class Background and Class101 . In this case how to assign Foreign key ? i am confused here. Any helped is appreciated. Thanks in advance. -
Class Property method not read/called - Django Rest Framework
I am trying to add a class property method to the Game model, however it is not appearing on the frontend when I call game.owner_username. Model: class Game(models.Model): location = models.CharField(max_length=100) players = models.ManyToManyField(User) kickoff_time = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) max_player_count = models.IntegerField(null=True) goal_type = models.CharField(max_length=100) notes = models.CharField(max_length=300, null=True) status = models.CharField(max_length=6) owner = models.ForeignKey( User, related_name="games", on_delete=models.CASCADE, null=True) @property def owner_username(self): return self.owner.username -
Retrieving objects
I made a GET function that will retrieve posts and will make it available only to a particular user as well as its friends list. To make this work partially, I developed a raw query to get my desired output, and somehow it works fine for me. Now, I am trying to learn making queries in django without implementing raw query, so I am trying to maximize the Django ORM and not use raw query but I'm kinda stucked and kept wondering how I am gonna be able to make my queryset works without using raw query. this is my raw query: FeedMedia.objects.raw("""SELECT DISTINCT feed_media.* FROM feed_media INNER JOIN feed ON feed_media.feed_id = feed.id INNER JOIN media ON feed_media.media_id = media.id INNER JOIN profile ON profile.id = feed.profile_id INNER JOIN gosam_friend_profile ON gosam_friend_profile.profile_id = feed.profile_id INNER JOIN friendship_friend ON friendship_friend.id = gosam_friend_profile.gosam_friend_id WHERE friendship_friend.to_user_id = %(friend)s OR gosam_friend_profile.profile_id = %(profile)s""", params={'friend': request.user.pk, 'profile': profile.pk}) -
How to deal with Dynamic form in addition of common form in Django
I am new to Django. I am very confused to store the dynamic form with the common form I have created a model like class AudioDetail(models.Model): filename = models.ForeignKey(AudioData, default=1, on_delete=models.CASCADE) audio_type = models.CharField(max_length=20, null=True, choices=SPEECH_CHOICES) start_time = models.CharField(max_length=20, null=True) end_time = models.CharField(max_length=20, null=True) label = models.CharField(max_length=20, null=True) sentence = models.TextField(null=True, blank=True) class AdditionalFields(models.Model): word = models.CharField(max_length=20, null= True) transcript= models.CharField(max_length=20, null= True) language = models.CharField(max_length=20, null= True, choices=LANG_CHOICES) These 3 fields should be dynamic. if the 'sentence' field in 'AudioDetail' model has the value 'How are you?', then in 'AdditionalFields' it should be saved in 3 rows('How', 'are', and 'you') with the same 'AudioDetail' information in 3 rows. -
Django rest framework create data after check a condition
#View @permission_classes([IsAuthenticated]) class PageUserProjectView(viewsets.ModelViewSet): queryset = PageUserProject.objects.all() serializer_class = PageUserSerializer() def create(self, request): result = PageUserProject.objects.values('id').filter(page=request.data['page'], user=request.data['user'], project=request.data['project']) if len(result)>0: return Response("Selected page access is already given to selected user under this project", status=status.HTTP_200_OK) else: if PageUserSerializer.is_valid(request.data): return PageUserSerializer.create(request.data) #Model class PageUserProject(models.Model): allow_deny_enum = (('Allow', 'Allow'), ('Deny', 'Deny')) page = models.ForeignKey(Page, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) create_date = models.DateTimeField(default=datetime.now) access_status = models.CharField(max_length=20, choices=allow_deny_enum, default='Allow') I just need to add new data if the if condition in views is not satisfied. How to do that? Also with a response of JSON format like, { "id":5, "access_status": "Allow", "page": 2, "user": 1, "project": 2 } If condition is working properly but unable to work with the code inside else condition. -
How to set-up google oauth using django-allauth without the admin panel
Is there a way to set-up google oauth using django-allauth WITHOUT using the admin panel? I am building a website and don't want to use the default django admin app. I've acquired the required Google client id and secret, now I'm not able to understand how to configure the django-allauth SocailApp setting without the admin app. # SETTINGS.py # Django-allauth config SITE_ID = 1 SOCIALACCOUNT_PROVIDERS = { "google": { "SCOPE": ["profile", "email",], "AUTH_PARAMS": {"access_type": "online",}, "APP": { "client_id": env("GOOGLE_CLIENT_ID"), "secret": env("GOOGLE_CLIENT_SECRET"), }, } } How should I add site to this configuration? -
parameters in request to DRF
I'm trying to parse an API page written using DRF import requests from bs4 import BeautifulSoup import time URL = 'url' data = {'user': 'admin','auth':'admin'} full_page = requests.get(URL, params=data) print(full_page) But I get a 403 error. I understand that I do not correctly transfer the login and password. Tell me how to transfer them?