Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku can't connect pdf fonts
I have downloaded fonts for html template that is converted with xhtml2pdf to pdf. I didn't manage to google for answer that works for me. I thought that path was changed but in heroku bash path isn't change. Here are some photos of my code: fonts are in invoices/static/invoices/fonts -
How to add @property to the base Group model in Django?
I want to be able to add a property to the group model This is what I have been trying from django.contrib.auth.models import Group class GroupExtensions(Group): class Meta: proxy = True @property def assigned_property(self): return 'something' I want to get this property from the base group model group_instance.assigned_property Where group is an instance of the Group model -
Bootstrap dropdown not appearing directly under navbar button
I am very new to bootstrap and html/css so sorry if this may be an obvious question. I am working on a Django project and I am currently trying to have a navbar button be a dropdown to have multiple different options. Like what you typically see in a profile dropdown in a lot of websites. Currently I am able to get that working but the dropdown appears on the far left side of the page and not directly under the button like what you expect. I followed bootstraps documentation on the navbar but it seems to still only show on the left side. Is there something I am missing? Here is what the output is currently like on the website: Here is the html code: <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-jj fixed-top"> <div class="container"> <a class="navbar-brand mr-4 jjfont" href="/"> <i class="material-icons">logo</i> WEBSITE NAME</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <!-- Navbar Left Side Goes Here --> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <!-- home icon --> <a class="nav-item nav-link" href="/"> <i class="material-icons">home</i> </a> <!-- create icon --> <a class="nav-item … -
'JSONRenderer' object has no attribute 'has_permission'
Error Screenshot I am working on react-native and django together in Pycharm. When I run the project. Attribute Error popped up! I don't know how to fix it and there's no related articles on Google for 'JSONRenderer object has no attribute has_permissions'. Also Internal Server Error is Displaying on terminal. Internal Server Error -
two project with same database user table problem
I have two projects and I have connected both to one database. One of these projects has an abstract user, which means I have overridden the user table. But in it I use one of the default Django tables. In this case, when I want to create a superuser in the second project, it gives this error: django.db.utils.OperationalError: no such table: auth_user What can I do? -
How to make ajax request for dependent drop down
I am new to programming and learning django. I am struggling to understand how to make ajax request to fetch data to create dependent dropdown lists. I have looked around on various google searches and stackoverflow but I get more confused looking at them. Hence, I could not move forward with fetching the dependent values My code for html looks like this <div class="form-group"> <select name ="service" id="service"> {% for item in serv %}" <option value="{{ item.id }}" >{{ item.name }}</option> {% endfor %} </select> <select name ="subcategory" id="subcategory"> {% for item2 in subcategory %}" <option value="{{ item2.id }}" >{{ item2.name }}</option> {% endfor %} </select> </div> My views.py looks like this def book(request): employees = Employee.objects.values_list('name',flat=True) services_ = Service.objects.values_list('name',flat=True) services = [] serv = Service.objects.all().order_by('-id') subcategory = SubCategory.objects.all().order_by('-id') # subcategory = SubCategory.objects.get(pk=request.GET('service_pk')) for i in services_: services.append(i) context = { 'employees':employees, 'services':services, 'serv':serv, 'subcategory':subcategory, } return render(request,'book.html',context=context) my urls.py is set like this among others path('service/<int:service>', services, name='services'), my models.py looks like this def rand_slug(): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) # Create your models here. def path_and_rename(instance, filename): upload_to = 'uploads/images' ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set … -
How to add a template folder to the Django project ? (in community pycharm)
How to add a template folder to the Django project ?(in community pycharm) -
How to make city recognition in urls in django app
What is best practice for django app to add city recognition in urls like: stite_name/moscow/ stite_name/city_name/ And how to make it found in google and e.t.c. -
Django error when filter by date "operator does not exist: date >= integer"
I'm using django framework with postgresql. I have virtual environment. My local machine Mac , server is on Debian 10. $ pip freeze amqp==5.0.6 asgiref==3.4.1 billiard==3.6.4.0 celery==5.1.2 certifi==2021.5.30 chardet==4.0.0 click==7.1.2 click-didyoumean==0.0.3 click-plugins==1.1.1 click-repl==0.2.0 Django==3.2.5 django-celery-beat==2.2.1 django-celery-results==2.2.0 django-timezone-field==4.1.2 greenlet==1.1.0 idna==2.10 kombu==5.1.0 lxml==4.6.3 multitasking==0.0.9 numpy==1.21.0 pandas==1.3.0 plotly==5.1.0 prompt-toolkit==3.0.19 psycopg2==2.9.1 psycopg2-binary==2.9.1 python-crontab==2.5.1 python-dateutil==2.8.1 pytz==2021.1 requests==2.25.1 six==1.16.0 SQLAlchemy==1.4.20 sqlparse==0.4.1 tenacity==7.0.0 urllib3==1.26.6 vine==5.0.0 wcwidth==0.2.5 yfinance==0.1.60 models.py from django.db import models from django.utils import timezone class Ticker(models.Model): symbol = models.CharField(max_length=12) description = models.CharField(max_length=100, blank=True, default='') avg_volume = models.DecimalField(max_digits=20, decimal_places=6) last_close_price = models.DecimalField(max_digits=20, decimal_places=6, default=0) last_update_date = models.DateField(default=timezone.now) def __str__(self): return self.symbol class TickerData(models.Model): date = models.DateField(default=timezone.now) open_price = models.DecimalField(max_digits=20, decimal_places=6) high_price = models.DecimalField(max_digits=20, decimal_places=6) low_price = models.DecimalField(max_digits=20, decimal_places=6) close_price = models.DecimalField(max_digits=20, decimal_places=6) adj_close = models.DecimalField(max_digits=20, decimal_places=6) volume = models.IntegerField() symbol = models.ForeignKey(Ticker, on_delete=models.CASCADE, related_name='infoset') def __str__(self): return f'{self.symbol}: {self.date}' views.py from datetime import date, datetime, timedelta from django.db import connection from django.shortcuts import render, get_object_or_404 from .models import Ticker, TickerData def ticker_data_view(request, pk): # dates enddate = date.today() startdatedays = enddate - timedelta(days=180) ticker = Ticker.objects.get(pk=pk) ticker_info = TickerData.objects.filter(symbol=ticker).filter(date__gte=startdatedays) context = { 'TickerData': ticker_info, } return render(request, 'tickerdata_list.html', context) When I open page with info DatabaseError at /ticker/2 Execution failed on sql 'SELECT "webapp_tickerdata"."id", "webapp_tickerdata"."date", "webapp_tickerdata"."open_price", … -
Video streaming from multiple users in Django
I am developing an exam platform website where people can create exams and take exams. I almost finished the examination part and wanted to add a proctoring system. I want that when people start any quiz, their video is displayed on the examiner's side. That is, when the users press (ex.) the "Start Quiz" button, their video is turned on. And examiners can watch all the exam passers in some url. I found that I could use OpenCV to do this, but couldn't figure out how to get multiple video sharings from different users. Please suggest me any ideas. What should I learn? Can this be implemented in Django? -
Django add child line to form for all related children
I have a django form for entering a turnover order (like a sales order). Each order, has one specified supplier, and the supplier supplies only certain lines. How can I add a list of children lines in the form for all products that supplier has? This is the order model (the Parent of the order) class Turnover(models.Model): created_date = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null = True, related_name = 'to_created_by') last_update = models.DateTimeField(auto_now=True) representative = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null = True) order_date = models.DateField(auto_now_add = True) customer_ref = models.CharField(max_length=20, blank=True, null = True) discount = models.DecimalField(decimal_places=1, max_digits=6) This is the lines for the order class TurnoverLine(models.Model): turnover = models.ForeignKey(Turnover, on_delete=CASCADE) pde = models.ForeignKey(Pde, models.SET_NULL, blank=True, null = True) units = models.IntegerField(default = 0) bonus = models.IntegerField(default = 0) The views can (if needed) create all of the lines for that supplier. Supplier x line 1. Product a "qty" line 2. Product d "qty" line 3. Product f "qty" The end user adds "Units" and "bonus", everything else is taken care of in views. -
Getting psycopg2.errors.DuplicateColumn error when applying Django Migrations on server
Trying to apply django migrations on server gives psycopg2.errors.DuplicateColumn error though it runs normal locally and creates all the appropriate db tables. Can the difference in Postgresql versions in local and server be the reason? or something else? -
New ManyToManyField object is not adding
I am building a BlogApp AND i made a feature of Favorite Users in the ManyToManyField. It means user_1 can add multiple favorite users in one field. I build a view to add users. BUT when i create an instance to store favorite users from Admin before adding favorite users from site AND then if i add favorite users from site then they are adding. BUT if there is not already a instance of request.user's FavouriteUsers in Admin then it is not adding and creating a new object. So, A new object for storing favorite users of request.user is not adding, AND if object is already there then they are adding. models.py class FavoriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) favorite_users = models.ManyToManyField(User, related_name='favorite_users', blank=True) views.py def AddFavUsers(request,user_id): obj = FavoriteUsers.objects.filter(user=request.user) user = get_object_or_404(User,id=user_id) for ob in obj: ob.favorite_users.add(user) ob.user.add(request.user) ob.save() return redirect('home') Image of already created object When object is already , manually created then favorite users are adding BUT if it is not then new object is not creating. Any help would be much Appreciated. Thank You in Advance. -
request.FILES is empty though from tag contains multipart data encryption
I am trying to upload a file to database from frontend HTML form. Here is the code: createuser.html <form method="POST" enctype="multipart/form-data" action=""> <input type="file" name="myfile"> <input type="submit"> </form> views.py if request.method == 'POST': if request.POST: myfile = request.FILES print(myfile) Output <MultiValueDict: {}> The output must be a file which I am selecting. Is there any way I could fix this? -
How to make web-scraping faster? Django project
I'm building a web-scraping application using the Django framework. I need some tips on how to speed up my application. As of right now, it takes almost a minute to load the page just parsing through 3 urls which is a problem. I'm going to need to run a lot faster as I want to parse through up to 10 urls on my webpage. As you can see, I'm only targeting one div with my code which is why my application is running so slowly. I'm thinking I could try targeting multiple divs to narrow down my "soup" but I've had difficulty with that in the past so I'm hoping to get some pointers. def stats(request): if 'user_id' not in request.session: return redirect('/') this_user = User.objects.filter(id = request.session['user_id']) this_stock = Stock.objects.filter(user_id = request.session['user_id']) progress_dict = [] for object in this_stock: URL = object.nasdaq_url page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') progress = soup.find_all('div', class_='ln0Gqe') for number in progress: progress_dict.append(number.text) context = { "current_user" : this_user[0].first_name, "progress_dict": progress_dict, "this_stock": this_stock, } return render(request, "nasdaq.html", context) -
Upload a file from react native image picker to server
can someone tell me what i m doing wrong i keep getting error 400 bad request, i can't seem to figure out how to send the image i tried to send the path, the filename and the mime but it's not working this is my request: const [image,setImage]=useState(null) const[filename,setFileName]=useState(null) const sendpic=async ()=>{ await ImagePicker.openCamera({ mediaType:'photo', width: 300, height: 400, cropping: false, }).then(image => { setImage(image['path']); const paths=image['path'] const filename=paths.substring(paths.lastIndexOf('/')+1); setFileName(filename); console.log(filename) console.log(image) const data=new FormData(); data.append('image',filename) data.append('title','3aslemajiti') const headers={ Accept:'application/json', 'Content-Type':'multipart/form-data', } try{ const response= axios.post('http://192.168.1.19:8000/Sends/',data,{headers:headers}) alert('yess!!!!!'); } catch (error) { // handle error alert(error.message); } }); }; and this is my model: from django.db import models # Create your models here. class Send(models.Model): title = models.CharField(max_length=255) image=models.ImageField(default ='null') def __str__(self): return self.title how do i write the request so it is accepted by the server? -
update function in DRF viewset.Viewset
I am trying to implement update in DRF viewset manually, i have successfully implemented list and retrieve This is what i have so far class UserViewset(viewsets.Viewset): authentication_classes = (TokenAuthentication,) permission_classes = (permissions.UpdateOwnProfile,) serializer_class = UserSerializer def list(self, request): queryset = User.objects.all() serializer = self.serializer_class(queryset, many = True) return Response(serializer.data) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save( created_by=request.user, modified_by=request.user ) return Response(serializer.data, status=201) return Response(serializer.errors, status=400) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = self.serializer_class(user) return Response(serializer.data) -
Django Admin keep logout repeatedly. May because the DB is corrupted. How to fix this situation?
Let me describe how this problem Admin logout problem occurred. It was about few months ago. My DB is MSSQL. I was using Django 1.11, and I wish to update to Django 3.x . First I was updating my Django to 3.1, because of that, I have to switch django-pyodbc-azure to django-mssql-backend. And I did migrate after I update my Django to 3.1. But I didn't know that mssql-backend does not supporting Django 3.1. So I switch my Django from 3.1 to 3.0.x And I remember that I have to migrate again. But the migrations are the same. I didn't add any new migrations. Still, the migrate it applies something again: admin. {nums}_logentry_add_action_flag_choices auth. {nums}_alter_user_last_name_max_length auth. {nums}_alter_group_name_max_length auth.{nums}_update_proxy_permissions At this moment. I haven't login through Admin page. And I think I did change the Django versions after this (maybe two times again). Just because I was trying to find out which version is suit for me. So I don't really remember how many times I migrate before I found out the Admin logout problem. Anyway, I think I messed up something during the migrates. And it doesn't matter which Version of Django I use, 3.0.x ~ 3.1.x all have the … -
Django how to prevent update old user instance?
I am using django signals in my models so I need to be save user in my views. When admin updating any user blog post it's replacing old user author id with admin user. Let you explain little bit. Assume User Jhone create an Blog post and it's pending for admin approval if admin approve the post then author of blog post changing from Jhone to Admin. It's only happening when admin updating post from HTML template. I think it's happing for this line in my views: isinstance.user = self.request.user #it's saving current user id How to prevent updating old user id in my views. here is my views.py: def form_valid(self, form): isinstance = form.save(commit=False) isinstance.user = self.request.user status = self.object.is_published name = self.object.name[0:20] messages.success(self.request, f"{name} comment status {status}") return super().form_valid(form) my models.py: class BlogComment(models.model): #my fields...... def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() if comment.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="Comment Approved") notify.save() if comment.is_published == "published": notify = Notifications(blog=blog, sender=sender, user=blog.author,text_preview=comment_text[:250], notification_type="Notify Author") notify.save() if comment.is_published == "rejected": … -
Django lost migration file
I have a django app connected to postgresql database (RDS instance running on AWS) Recently, I added new fields to my database tables, but forgot to run makemigrations locally and pushed the code to the server. The server went down since changes were not applied, and in order to fix the problem quickly I decided to run makemigrations and migrate directly in docker container of the application, I thought it would generate migration files, but unfortunately, it didn't. The migration was applied on database level, but there is no migration file of the changes. When running python manage.py showmigrations in the container, it outputs: redirect [X] 0001_initial [X] 0002_redirect_clicks [X] 0003_redirect_name But in database, running SELECT * FROM django_migrations; tells that there is one more migration: 103 | redirect | 0004_auto_20210707_2039 | 2021-07-07 14:39:19.058233+00 What would you advise? I thought of running makemigrations locally, generate the file and push it to vcs, and on the server apply the changes using migrate --fake. I don't know what this does exactly and I am too scared to do it without guidance, any help would be appreciated -
unabel to fetch data from data from databse in django
i create a model name subject and in the model i also have thumbnail field what i want is to implement that models field n my template my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name my views.py @login_required def home(request): subject_list = Subject.objects.all() return render (request, 'home.html', {'subject_list': subject_list }) my html file in ehich i tried to show it <div> <ul> {% for subject in subject_list %} <li> <a href=""> <img src="{{ subject.subject_thumbnail }}" alt=""> {{ subject.subject_name }} </a> </li> {% endfor %} </ul> </div> any suggestion what i am doing wrong here -
Customize lookup isnull
I'm trying to customize isnull lookup to return both null and blank values and django documentary doesn't give enough inforamtion about how exactly it works. i need some help writing params and return value. here is my code so far: from django.db.models import Lookup class IsNull(Lookup): lookup_name = 'isnull' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + lhs_params if rhs_params[0]: return '%s != %s and %s != %s' % (lhs, None, lhs, str()), params else: return '%s == %s or %s == %s' % (lhs, None, lhs, str()), params # User.objects.filter(first_name__is_null=True) error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near "LIMIT": syntax error detail: Traceback (most recent call last): File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near "LIMIT": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 262, in __len__ self._fetch_all() File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "E:\aibox\git\venv\user_service\lib\site-packages\django\db\models\query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) … -
How do I update data of django model by simply clicking on a button without any form?
I'm working on a Django project. My motive is to update the value of status in the database by simply clicking on a button. I don't want to submit any form. This is what I've tried: Models.py class auction_listing(models.Model): title = models.CharField(max_length=100) status = models.BooleanField(default=True) def __str__(self): return f"{self.id} : {self.title} " Here status is the boolean field. By default it's true. No form required here but I want this status is to be changed with a button click. Here is the button in my HTML template. template.html <div style="margin-top: 2%;"> <form action="{% url 'status' list.id %}" method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Close</button> </form> </div> Here is my views.py function: views.py def status(request,list_id): listing = auction_listing.objects.get(pk=list_id) if request.method == "POST" and instance.status is True: instance.status = False instance.save() else: instance.status = True instance.save() return HttpResponseRedirect(reverse("displaylistitem",kwargs={"list_id":list_id})) urls.py path("<int:list_id>",views.display_list,name="displaylistitem"), path("<int:list_id>", views.status,name="status"), This is all I tried. The problem is when I press the button, it simply refreshes the page rather than updating the value of status in database. -
How to dispaly data just locally on websocket
I'm building a Chat App with django channels websocket and I have two methods, the new_message that create an instance and send to the front-end to be displayed to everyone in the room, and a fetch_messages that make a query and return the 20 messages. When the user log-in to the chat room the fetch_messages method is called and all the message are displayed, but if another user already have loged to the room, the messages will be displayed again, since that the messages already have been displayed when he loged. on my consumers.py class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): message_instances = Message.last_20_messages() messages_objects = [] for instance in message_instances: messages_objects.append(self.message_to_json(instance)) self.send_chat_message(content=messages_objects) def new_message(self, data): username = data['from'] user = get_object_or_404(User, username=username) message_insntance = Message.objects.create( user=user, message=data['message'] ) message_object = self.message_to_json(message_insntance) self.send_chat_message(content=message_object) my JS script: this is the function that I am talking about when the user log to the chat chatSocket.onopen = function(e) { chatSocket.send(JSON.stringify({ 'command': 'fetch_messages' })) } chatSocket.onmessage = function(e) { const data = JSON.parse(e.data); if (data.length > 1) { for (let i = 0; i<data.length; i++) { createMessageDiv(data[i], username) } } createMessageDiv(data, username) }; function createMessageDiv(data, username) { let div = document.createElement('div'); div.classList.add('message'); if (data['username'] == username) … -
Undefined variable 'Listing' Pylint in VSCode
Eventhough I have installed pylint-django and made changes in settings.json file like below, I could not able to access the object named 'Listing'. It shows error as undefined variable "Listing'. { "workbench.editorAssociations": { "*.ipynb": "jupyter.notebook.ipynb" }, "terminal.integrated.tabs.enabled": true, "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", "--disable=all", "--enable=F,E,unreachable,duplicate-key,unnecessary-semicolon,global-variable-not-assigned,unused-variable,binary-op-exception,bad-format-string,anomalous-backslash-in-string,bad-open-mode",], "[python]": { "editor.wordBasedSuggestions": false }, } Kindly help.