Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
Change is query in ListModelMixin after Django upgrade
I have upgraded my existing project from Django 2.2.26 to 3.2.11 and updated all its dependencies. Using the list method in ListModelMixin after the upgrade yields a different query. My approach has been to check Django changelogs which has not provided me with an answer yet. Is there any other possible reason for this to happen? -
Is it possible to display objects in Django with customized sorting according to categories, just like Pandas dataframes?
Thank you for reading. A large amount of data has been saved through Django objects.save(). In that data, I want to reorder rows with a specific value in a specific column first, and then just float the rest in order. Data objects data category 1 A 2 B 3 C 4 C For example, I want to show category B first, i want to reorder like below. data category 2 B 1 A 3 C 4 C In a pandas dataframe, I can use the sort function after creating a category like below. df['category'] = pd.Categorical(df['category'], ["cate3", "cate4", "cate1","cate2"]) df.sort_values(['category']) But what if I have already saved it as a django object? Django object.save takes a lot of time, so I can't save it after sorting the dataframe. I saved django objects with below codes. ca=pd.read_csv('data.csv') for i in range(0,1000): Product(data=ca.iloc[i].data.astype('float'),category=ca.iloc[i].category).save() Thank you. -
Django tables2 TypeError: Object of type Client is not JSON serializable
I'm trying to implement a big data on django-tables2, but with bootstrap table fitches (sort, filter, export, click to select, etc). Found a solution but it works with only simple fields, in my project, some fields in the model are linked to another model: class Cars(models.Model): dealer = models.ForeignKey(Dealer, blank=True, null=True, on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True) VIN = models.CharField(max_length=19, blank=True, null=True) model = models.CharField(max_length=50) # Car_model, on_delete=models.CASCADE client = models.ForeignKey(Client, blank=True, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(Manager, blank=True, null=True, on_delete=models.CASCADE) This is my code in views.py: class TableViewMixin(SingleTableMixin): # disable pagination to retrieve all data table_pagination = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # build list of columns and convert it to an # ordered dict to retain ordering of columns # the dict maps from column name to its header (verbose name) table: Table = self.get_table() table_columns: List[Column] = [ column for column in table.columns ] # retain ordering of columns columns_tuples = [(column.name, column.header) for column in table_columns] columns: OrderedDict[str, str] = OrderedDict(columns_tuples) context['columns'] = columns return context def get(self, request, *args, **kwargs): # trigger filtering to update the resulting queryset # needed in case of additional filtering being done response = super().get(self, request, *args, **kwargs) if 'json' …