Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to define Transform with more than 1 args?
I'm trying to create a custom Transform for the PostgreSQL specific GET_BYTE() function, so that I can query a bytea column by byte position. I want to be able to do the following SQL: SELECT * FROM my_table WHERE GET_BYTE(my_bytea_column, 0) = 1; The way I imagine it should be handled in Django: MyModel.objects.filter(my_bytea_field__gb0=1) I have tried subclassing Transform and overriding get_transform() on models.BinaryField as the Django documentation on custom lookups suggested. from django.db.models import Transform, BinaryField class GetByte(Transform): function = 'get_byte' # function should take 2 arguments # If set to 1, it fails with 'TypeError: can't escape int to binary' arity = 2 def get_byte_transform(byte_pos): """ This function should return a Transform subclass """ # return GetByte(byte_pos) # TypeError: 2 arguments needed + TypeError: not callable # return GetByte(field, byte_pos) # how do I get the field? + TypeError: not callable return GetByte # this works, but now I lost the byte_pos info class FingerprintField(BinaryField): def get_transform(self, lookup_name): if lookup_name.startswith('gb'): try: byte_pos = int(lookup_name[2:]) # return only works if it returns GetByte, but not GetByte() # but then fails, because it expects 2 args return get_byte_transform(byte_pos) except ValueError: pass return super().get_transform(lookup_name) However, it seems that Transforms expect functions … -
Django web socket not start in server
Help me for above error while i am trying to send message using django channel i am getting above error on server -
Django forms. Make ChoiceField required on frontend <select>
I have created a Django form, which uses a ChoiceField: control_model = forms.ChoiceField(choices=(), required=True) (The reason 'choices' are empty is because they are set using a function based on my backend database) The following is the entire form: class CreateWorkflowForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateWorkflowForm, self).__init__(*args, **kwargs) self.request = kwargs.pop("request") self.fields['control_model'].choices = my_function() control_model = forms.ChoiceField(choices=(), required=True) class Meta: model = CreateWorkflowModel fields = ['control_model'] The model used looks the following: class CreateWorkflowModel(models.Model): control_model = models.CharField(max_length=100) I use this form in a Django template the following way: <div class="form-content"> {{ form.media }} {{ form.as_p }} <input type="submit" id="id_submit" value="Submit" /> </div> However on my webpage the <select> that corresponds to my ChoiceField doesn't have the attribute 'required': This means that my form will fail if no value is input into the ChoiceField (because its required in the form) However I would much prefer if a popup box appeared on frontend stating "You need to enter a value on this field". I know having the "required" value on the <select> would do this exact thing, however I don't know how to make django generate the <select> with this attribute. -
Create JSON object on conditional statement Django Restframework
Iam Working on Django Restframework. I want to create/POST into an API to create an object. The problem is the condition I want to make, is itself in the POST data. For example, I have 5 fields: Name Lastname Email is_member membership_id I want to create a membership_id, if the user "is_member== True" POST while Data receive. Iam until here def create_user(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') category = request.POST.get('category') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) if is_member == True: membership_id = hashString(str(timestamp)) else: membership_id = "" try: user_object = MasterUser( firstname = firstname, lastname = lastname, email = email, contact = contact, is_member = is_member, date_joined = date_joined, last_signed_in = last_signed_in, is_subscription = is_subscription, category = category, membership_id = membership_id ) user_object.save() return HttpResponse('User successfully created') Is it possible or do I have to look out for some different apporach. Any ideas are welcomed! Thanks -
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