Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django advanced model operation
I do have such operation: Contact.objects.filter(contact_code__icontains=my_string[-8:]).exists() I want to find my_string[-8:] not in the beggining, not at the end but strictly on x position in contact_code. Or I want to splite contact_code field, them do MD5 on it and only then look on it? How can I manipulate model query here? I can do it in raw sql and want to do it in model filter - not in code. -
operator does not exist: character varying[] = text[] in django?
models.py from django.contrib.postgres.fields import ArrayField class Product(DateTimeModel): colors = ArrayField(models.CharField(max_length=500),null=True, blank=True) # I am having => black,red views.py def filters(request): color_filters = request.GET.getlist('colors', default=None) # from form ['red'] products = Product.objects.filter(colors__in=l) print(products) When I am performing this I am getting this error ProgrammingError at /product/filter-query/ operator does not exist: character varying[] = text[] HINT: No operator matches the given name and argument types. You might need to add explicit type casts. How to perform this. please needed help. -
Django - modelform + model property
I am trying to solve one issue about saving data in db. This is an example how I think of it: class MyModel(models.Model): id = models.AutoField(primary_key=True) fieldX = models.SomeFieldType() @property: def foo(self): return self._foo @foo.setter def foo(self, var): self._foo=var class MyModelForm(models.Modelform): class Meta: model = models.MyModel fields = '__all__' The thing is I have dict that I am passing to this form (so I am not using view or any provided interaction with user directly. In dict I have some fields and what I want to do is one field that is passed to use it as model property but I do not want it to be saved in db. So I tried something like: form = MyModelForm(data_dict) if form.is_valid(): form.foo = data_dict['data_for_property_not_db'] form.save() Form does not know that my model has this property. So basiclly what I want is to write some parts of my data_dict normaly to form and db as always ->works fine and then I want some data_info pass to that property and use it somewhere in save() as needed without saving it to db itself. Can you help me with this? -
How to refer to class instances from the class itself
I have a class 'Scene'. From this class I can have several choices (0..n). They will be presented to the User of Scene object with a simple sentence (String). Each of the choices must point to a Scene instance (the next_scene). So I only need to associate this choice with a scene instance Id. How can I implement that in Django Models, and/or in django model.Admin. Example of a class Scene : class Scene(model.Models) title = models.CharField(max_length=30) description = models.TextField() choices = # TODO I have tried several solutions but get always blocked. I suspect I do not conceive it right from the beginning. Any help would appreciated. Stéphane -
Django restricting html section to unauthenticated users on template
my homepage has a navbar and then some content. I want to restrict the visibility of the content only to logged in/authenticated users. I tried something like this : {% if user.is_authenticated %} <div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for product in products %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="http://127.0.0.1:8000/media/{{ product.image|truncatewords:2 }}" style="max-height:400px; max-width:100%"> <div class="card-body"> <p class="card-text"> {{ product.description|truncatechars:105 }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary" style="background-color:rgb(0,128,50, 0.5)">Buy</button> <button type="button" class="btn btn-sm btn-outline-secondary"><a href="http://127.0.0.1:8000/book/{{ product.id }}" style="text-decoration:none">Read More</a></button> </div> <small class="text-muted" style="border: 1px solid black; padding:3px; border-radius:5%"><strong>{{ product.price}}€</strong></small> </div> </div> </div> </div> {% endfor %} {% else %} <h1>Just login, bro</h1> {% endif %} this is my view that renders the page : def all_products(request): products = Product.objects.all() return render(request, 'store/home.html', {'products' : products, 'user': request.user}) So, what should I do in order to show that piece of HTML only if the user is authenticated or logged in ? I have already seen someone do something like this but can't find it, am I missing something? -
AWS RDS and PGAdmin
I am working on a personal Django project and plan on using a PGSQL DB on AWS RDS. Tutorials I see always show the process of linking RDS dbs to PGAdmin and I am wondering if this step really is necessary/vital. Would there be consequences (apart from not having access to all the benefits of PGAdmin of course) if I skipped it? -
Django user.is_authenticated is not for some subpage
In my index.html(base template) have nav bar and user is_authenticated is not working for profile subpage it is working for home Index.html <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> ... {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link mx-1" href="/account/profile/">{{user.username}}</a> </li> <li class="nav-item btn-danger "> <a class="nav-link text-white " href="/account/logout/">Logout</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="/account/login/">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="/account/register/">Register</a> </li> {% endif %} ... </nav> Profile.html {% extends 'index.html' %} {% block body %} {% for user_info in user%} <div> ... </div> {% endfor %} {% endblock body %} What i am trying here is when i login it remove login and registration button and instead whatever the user name and logout button is appear it is working on home but whenever i got profile page i see login and registration even though i am curretly logged in . Thanks and any advice would be much appreciated. -
How to send all django error as json data
I am building a rest api in django, I am using postman to test my apis, Everything is great though I want if any error occurs in my django app so django send me a json error rather than a html page. Is there a way to do that. -
how can i use django form validation
I am trying to use Django form and validation is not working. django version 3.2 I tried different methods and still, none of them worked for me. from django import forms from django.core import validators from django.core.exceptions import ValidationError #Custom_Validator def check_size(value): if len(value) < 6: raise forms.ValidationError("value is short") class UserForm(forms.Form): firstName = forms.CharField() LastName = forms.CharField(validators = [check_size, ]) password = forms.CharField(widget = forms.PasswordInput, validators = [check_size, ]) def clean_firstName(self): inputfirstName = self.cleaned_data['firstName'] if len(inputfirstName)>5: raise ValidationError("reached max length") return inputfirstName -
Can we use NextJs to develop ML model App?
I have an App (Shiny) that deploys a Machine Learning model and I want to use something better than R-Shiny. I Got two suggestions Django+React and NexJS. Can you advise me which is better and if there is a free App that is developed with these technologies so I can have a look and test it by myself? Thanks. -
While using bulk_create() -> error = "detail": "JSON parse error - Expecting ',' delimiter: line 1 column
In this file, I am trying to post user information, either one or many using bulk_create() views.py @api_view(['POST']) def post_user(request): print("INSIDE") print(request.data) if len(request.data) == 1: user_data = UserInfoSerializer(data=request.data) if user_data.is_valid(): user_data.save() return Response(user_data.data) else: UserData.objects.bulk_create(request.data, batch_size=1000) The request which I send is [{"name":"George","gpa":2}, {"name":"Dev","gpa":4}, {"name":"Bianca","gpa":3.2}] When I send a request with one dictionary, data gets uploaded. But not with multiple -
Django 401 (Unauthorized) On making PUT request with axios. But working with Postman
I'm trying to update the User in Django from react side. The same function has worked on testing through Postman. But when I try to make a request using Axios in react.js Django doesn't accept it. and throw 401 error. [21/Feb/2022 16:25:16] "PUT /api/v1/accounts/profile/update/ HTTP/1.1" 401 58 On the postman, I'm using Bearer Token for authorization. And the same token I'm passing in headers config. // Related Action Code const userData = JSON.parse(localStorage.getItem('userData')) const config = { headers: { 'Content-type': 'application/json', Authorization: `Bearer ${userData.token}` } const { data } = await axios.put( `/api/v1/accounts/profile/update/`, config ) Can anybody find out why this happening? And how to fix that problem. -
My website form submission is responding with Server Error 500. How to fix it?
I have a django blogging website hosted on digital ocean apache server, but when an authenticated user is creating a blog and then submitting it, the server is responding with this error - "Server error 500". Rather it should show that 'your blog is submitted successfully' and should redirect to a different page. When I referred the /var/log/apache2/error.log file, I found this text written inside it: [Mon Feb 21 06:25:06.622898 2022] [mpm_event:notice] [pid 1379:tid 139646411897792] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Mon Feb 21 06:25:06.622981 2022] [core:notice] [pid 1379:tid 139646411897792] AH00094: Command line: '/usr/sbin/apache2' [Mon Feb 21 09:59:50.545910 2022] [core:error] [pid 1670:tid 139646038083328] [client 45.146.165.37:57224] AH00126: Invalid URI in request POST /cgi-bin/.%2e/.%2e/.%2e/.%2e/bin/sh HTTP/1.1 How can I fix this error? -
Sum of Duration Fields in Django
I am having a small issue in summing up two simple duration fields. I have two variables which contains two different duration fields. Basically, I just need to sum them in order to get the total time. The problem is that, the way the database is built, I can't use Sum or F or ExpressionWrapper because I have to accept also None values and, the calculation gives me a None value in return. I post some code: views. py duration_dual = Mission.objects.filter( training_course_id=1, solo_flight=False) total_dual_duration = duration_dual.aggregate(eet=Sum(ExpressionWrapper( F('duration_dual'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_dual_duration != None: total_dual_duration = duration(total_dual_duration) duration_solo = Mission.objects.filter( training_course_id=1, solo_flight=True) total_solo_duration = duration_solo.aggregate(eet=Sum(ExpressionWrapper( F('duration_solo'), output_field=IntegerField()), output_field=DurationField()))['eet'] if total_solo_duration != None: total_solo_duration = duration(total_solo_duration) models.py class Mission(models.Model): name = models.CharField(max_length=200) duration_dual = models.DurationField(blank=True, null=True) duration_solo = models.DurationField(blank=True, null=True) training_course = models.ForeignKey( TrainingCourse, on_delete=models.CASCADE) note = models.TextField(null=True, blank=True) solo_flight = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) In fact, what I need to do is just adding the total_solo_duration and total_dual_duration variables. I tried with datetime or timedelta but I can't figure out the proper way to do so. Thank you very much in advance -
What to do when pip dependency resolver wants to use conflicting django plotly dash versions of a application?
So I'm trying to integrate plotly with my django app however I'm having an issue rendering a chart. I was using VSCode which did not pick up the dependency conflict. However when i started to use Pycharm. It said my Dash was version 1.11 which satisfies the django-plotly-dash but did not satisfy the dash_bootstrap_components which required 2.0.0 I have now installed Dash version 1.10 which conflicts with both apps just to show the error message below: Relevant error code ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following de pendency conflicts. django-plotly-dash 1.6.6 requires dash<1.21.0,>=1.11, but you have dash 1.10.0 which is incompatible. dash-bootstrap-components 1.0.3 requires dash>=2.0.0, but you have dash 1.10.0 which is incompatible. Any help is appreciated -
Django how to create object has foreignkey in views.py?
I've wrote this code: views.py if not null: Address.objects.create(user = request.user,first_name = ad,last_name = soyad,address_title = baslik,address = adres,postalcode = posta,tel = gsm,il_ilce = Ilce.objects.get(il_id__il = sehir,ilce = ilce)) models.py class Il(models.Model): il = models.CharField(max_length=20,blank=False,null=False) def __str__(self): return str(self.il) class Ilce(models.Model): ilce = models.CharField(max_length=20,blank=False,null=False) il_id = models.ForeignKey(Il,blank=False,null=False,on_delete=models.PROTECT) def __str__(self): return str(self.ilce) class Address(models.Model): first_name = models.CharField(max_length=30,blank=False,null=False) last_name = models.CharField(max_length=30,blank=False,null=False) user = models.OneToOneField(User,on_delete=models.CASCADE) address_title = models.CharField(max_length=20,blank=False,null=False,default="Adres") address = models.TextField(max_length=255,blank=False,null=False) il_ilce = models.ForeignKey(Ilce,blank=False,null=False,on_delete=models.PROTECT) postalcode = models.CharField(max_length=5,blank=False,null=False) tel = models.CharField(max_length=11,blank=False,null=False) def __str__(self): return str(self.user) + '-' + str(self.address_title) but I'm getting this error: duplicate key value violates unique constraint "Users_address_user_id_key" DETAIL: Key (user_id)=(1) already exists. I don't want the code to create a new user object I want it to create a new address object only. -
'NoneType' object is not subscriptable df.apply(lambda row: (row)[0], axis=1)
I linking two table from variety_id to variety_name but my code is giving an error when the variety_id is null 'NoneType' object is not subscriptable the code where I am linking table if not df.empty: df['commodity_name'] = df.apply(lambda row: commodity_name(row)[0], axis=1) df['state_name'] = df.apply(lambda row: state_name(row)[0], axis=1) df['variety_name'] = df.apply(lambda row: variety_name(row)[0], axis=1) def commodity_name(self): if self.commodity_id: return get_commodity_name(self.commodity_id) return None def state_name(self): if self.state_id: return get_region_name(self.state_id) return None def variety_name(self): if self.variety_id: return get_variety_name(self.variety_id) return None also written query for mapping the columns def get_variety_name(variety_id): """ This function is used to return state_name by querying the database based on lgd_state_id """ query = "SELECT commodity_variety_name FROM itrade.commodity_variety_master WHERE commodity_variety_id={}".format( variety_id) query_result = get_column_value(query) if not query_result.empty: return list(get_column_value(query)['commodity_variety_name']) return None def get_commodity_name(commodity_id=None): """ This function is used to return commodity_name by querying the database based on commodity_id """ query = "SELECT commodity_id, commodity_name FROM itrade.commodity_master" if commodity_id: query += " WHERE commodity_id={}".format(commodity_id) return list(get_column_value(query)['commodity_name']) return get_column_value(query).to_dict(orient='records') -
Django function params
Where there are a series of parameters passed to a Django function they may have defaults. If a param is supplied when the function is called it is used. If not the default is used. Is there a way to access the first default while supplying subsequent param[s] in the function call? Example: def pong(fname = 'Pinkus', lname = 'Poke'): print(f'My name is {fname} {lname}') pong() # My name is Pinkus Poke pong('Frank') # My name is Frank Poke pong('Frank', 'Finklestein') # My name is Frank Finklestein pong('', 'Bloggs') # only gives empty string, no default! -
Django E-learning Platform modeling
I am making an E-learning web application/Blog and I have 2 models: Courses and Chapters, so obviously a course can have multiple chapters, but what I want to do is let's say I have a course with 12 chapters I want to group the chapters into parts without creating another model exemple: Course: Exemple_Course Part 01: 5 chapters Part 02: 5 chapters Part 03: 2 chapters this is my code : class Article(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True ) title = models.CharField(max_length=120) description = models.TextField() slug = models.SlugField(blank=True,null=True,) date = models.DateTimeField( auto_now_add = True) allowed_subscription = models.ManyToManyField(Plan,blank=True, null=True,) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:article-detail', kwargs={'article_slug': self.slug}) def pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(pre_save_receiver, sender=Article) CHAPTER_TYPES = ( ('CHAPTER', 'Chapter'), ('SUB_CHAPTER', 'Sub chapter'), ) class Chapter(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True,null=True,) article = models.ForeignKey(Article,on_delete=models.CASCADE,null=True,blank=True,) content = models.TextField() chapter_type = models.CharField(max_length=256, choices=CHAPTER_TYPES) def __str__(self): return self.title def get_absolute_url(self): return reverse('articles:chapter-detail', kwargs={'article_slug': self.article.slug,'chapter_slug': self.slug,}) pre_save.connect(pre_save_receiver, sender=Chapter) -
how to filter the jsonfield in models with list in django?
models.py class Product(DateTimeModel): subcategory = models.ForeignKey(SubCategory, null=True, on_delete=models.CASCADE) product_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) item_colors = models.JSONField(max_length=500, null=True, blank=True) views.py I want to perform filter action in this model, the filter query lists I get from the template from checkboxes. def filters(request): category_filters = request.GET.getlist('category', default=None) color_filters = request.GET.getlist('colors', default=None) if category_filters or color_filters: total_filters = list(chain(category_filters, color_filters)) products = Product.objects.filter(Q(subcategory__title__in = total_filters) | Q(item_colors__in = total_filters) ) Here I am not getting the objects related to item_colors as I expected. item_colors field is like (item_colors = {'colors':['black','red',..]}). I can't perform the __in in JSON field. How do I do that in the right way? -
The django admin site error No migrations
I want to run this command but I face this error. python ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
download button in django to convert home page to pdf
I have a pbl with my download button in my django app i give this error : " AttributeError at /views.download_my_pdf 'str' object has no attribute 'read' " what i did wrong please ? views.py def download_pdf(request): filename = 'faults.pdf' content = FileWrapper(filename) response = HttpResponse(content, content_type='application/pdf') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename=%s' % 'faults.pdf' return response urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home), path('views.download_my_pdf', views.download_pdf, name="download_pdf"), ] .html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> Dashboard Result</title> </head> <body style="margin-top: 30px; padding: 100px"> <a class="btn btn-primary" href="{% url 'download_pdf' %}" role="button">Download pdf</a> {% for key, value in results1.items %} <tr> <td>{{ key }} </td> <td>{{ value }} </td> </tr> {% endfor %} {% autoescape off %}{{ output_df }}{% endautoescape %} </body> </html> -
How to create custom user in Django rest framework without a password?
I'm working on a project where I have to create a custom user with email address and other details but not a password, instead of a password, I want to use OTP. I have searched through the web and haven't found a decent source which can help me with it. What I want is - To create a custom user manager in DRF To create a superuser without a password (using OTP for that instead) Create a user similarly Please help me figure this out. -
how to add value in exiting list in Update Query in Django
i have model which containing a list, i want to append value in all instances from this model class model(models.Model): title = models.CharField(max_length=255) roles = ArrayField(base_field=models.TextField(choices=ModelRoles.choices()), default=list) my update statement is model.objects.all.update(roles=roles.append("new role")) -
can i make a view visible to some specific users and other not on Django
I want to make some pages not accessible for some users , what i mean for example i want to make user1 can see a viewa and can not see a viewb, I have tried to do that I have developed 2 functions of permissions and role user function: Here is the code of the 2 functions of permissions in views.py: def is_normaluser_login_required(function): def wrapper(request, *args, **kw): user=request.user if not user.roleuser.is_normaluser: return render(request, 'unauthorized.html') # or raise 403 else: return function(request, *args, **kw) return wrapper def is_privilgeuser_login_required(function): def wrapper(request, *args, **kw): user=request.user if not user.roleuser.is_privilgeuser: return render(request, 'unauthorized.html') # or raise 403 else: return function(request, *args, **kw) return wrapper then i have go to home template where there was a sidebar contain 2 list(every list call a view) , I want to make just the users that are permitted to see this form-list on the navigate bar; Here is the code in template.html that contain the 2 forms that i want limit the access for both of them: <nav class="mt-2"> <ul class="nav" > {% if perms.app1_name.is_normaluser_login_required %} <li class="nav-item"> <a href="{%url 'form_module1'%}" class="nav-link"> </a> </li> {% endif %} {% if perms.app1_name.is_privilgeuser_login_required %} <!----> <li class="nav-item"> <a href="{%url 'form_module2'%}" class="nav-link"> </a> …