Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango Driver 13 for SQL Server][SQL Server]Invalid object name 'django_session'
Need help with setting up my django project. my settings.py : DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'DCMS_DEV', 'HOST': 'sql1165-xx-in.xxx.xxx.xxx.com,4567', 'USER': 'sakshi', 'PASSWORD': 'sakshi123', 'OPTIONS': { 'driver': "ODBC Driver 13 for SQL Server", } } } This is the error when i pass through admin: ProgrammingError at /admin/login/ ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'django_session'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.1.12 Exception Type: ProgrammingError Exception Value: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'django_session'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I am new bee for django. can you tell me what all basic requirement which are needed to run an django project? how do i resolve this? -
Is this a good solution for recording snapshot data in django
I have a db table to record user's asset data which modified frequently by other services. For now, I expose an API that allows other services to post back collected asset data, which means every time the data modified, I have to write the db table at the same time. If there are thousands of user's data modification simultaneously, there also are thousands of database written operation simultaneously, which is not efficient. The solution I came up with is using multi database. Specifically, I introduce an inmemory db such as sqlite3 to record the data. But I have no idea how to synchronize the data to the main database since the data must be stored persistently if the application reboot. I can not use a cache system simply,because I rely the ORM to query the data and display them. Is there any solution for such scenario? Thanks for your answer. -
Django - How to test this CBV?
:) I'm near the end of my first django "project". I managed to make tests for everything, but one view. I'm not really sure how and what to test here, does someone mind helping me out ? class CommentCreateView(CreateView): def get(self, request, *args, **kwargs): context = {'form': CommentForm()} return render(request, 'news/add_comment_to_article.html', context) def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): article = get_object_or_404(Article, pk=kwargs.get('pk')) print(article) comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={'article_id': article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) Thanks for the help !! -
Serve static files with IIS and Django
I'm getting an error when trying to serve static file on IIS using FastCGI with Django==2.2.5 and python==3.7.4 my settings.py static code STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I'm using wfastcgi version 3.0.0 and my server is windows server 2012 datacenter R2. I tried all solution here Django Admin Page missing CSS in IIS and here How to fetch static CSS files with django on IIS? and watched some tutorial on youtube but still stuck with that. The error when it shows when I'm trying to access the admin page GET http://xxxxxx/static/admin/css/base.css net::ERR_ABORTED 404 (Not Found) -
Django Admin Page on Deployment
I'm currently learning about web development using Django and something I thought about but can't seem to find a solution to is how to make the admin page of the web app accessible to developers but not to the users of the app while it is hosted on something like Azure or AWS. The idea is to have an admin page so the developers can see what is going on and manage what needs to be managed, but not allow the clients to reach the login page to the admin interface. -
Django: How to implement JOIN using Django ORM?
my models are: class User_Mapping(models.Model): user_key =models.ForeignKey('User',on_delete = models.CASCADE) product_key= models.IntegerField(null=True) geo_key= models.ForeignKey('Geography',on_delete = models.CASCADE) class Geography(models.Model): geo_key = models.AutoField(primary_key=True,null=False) zone = models.TextField(null=True) country = models.TextField(null=True) division = models.TextField(null=True) subdivision = models.TextField(null=True) I have to join the tables on geo_key and all the fields on user_key. i have tried using select_related I have tried the following queries: User_Mapping.objects.all().select_related('geography').filter(user_key=request.data.user_key) Geography.objects.filter(user_mapping__user_key=user_key).all() User_Mapping.objects.select_related().filter(user_key=3) But these are throwing errors: 'dict' object has no attribute 'user_key' name 'user_key' is not defined I am not able to figure out what can be the right query and why it is throwing this error as I have user_key in the table -
User Django Group
Using Django default authentication system, I want a logged in user to be able to create a group and add other users. I want to write a query that returns the user that created the group,I have not been able to achieve that. Can I achieve this with the Django default authentication system or I create a custom authentication system -
Fetch data from PostgreSQL using django-pgviews
I used django-pgviews in my Django project and I want to get data from django-pgviews but It shows an error that psycopg2.errors.UndefinedTable: relation But views which created using django-pgviews are exist in database and I can retrieve data in pgadmin. But I can not use those views in front end. -
Django - Is it possible to split a single model class into two model classes, while preserving the data from before split?
In Django is it possible to split a single model class into two model classes, while preserving the data that was previously entered? Initial Model: class Fruit(models.Model): name = models.CharField(max_length=100) color = models.CharField(max_length=100) taste_description = models.CharField(max_length=100) tasty = models.BooleanField() Split Models: class Fruit(models.Model): name = models.CharField(max_length=100) color = models.CharField(max_length=100) class Fruittaste(models.Model): fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE) taste_description = models.CharField(max_length=100) tasty = models.BooleanField() -
How to add unique constraint to big textfield in django?
models.py: class PageURL(models.Model): url = models.TextField(max_length=2048, unique=True) Error during migrations: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'url' used in key specification without a key length") I considered a CharField but Django said the max on that for this use case was 255 characters. Initially I just had TextField(unique=True) but decided to add a max_length which I heard was normally 2048 for URLs but that hasn't helped silence the errors. -
Using django-mysql EnumField
I'm using django-mysql Enum Field as follows: class SOData(models.Model): foo = EnumField(choices=['FOO', 'BAR'], default='FOO') class Meta: dbtable = 'so_data' q = SOData() q.save() returns the following error: MySQLdb._exceptions.DataError: (1265, "Data truncated for column 'foo' at row 1") Similar code using EnumField elsewhere does not return the same error. I'd like to understand the error and how I can resolve it. Also, I am surprised that the Default value for column foo is NULL and not FOO when I describe so_data? I expected that makemigrations would set the default value in the database table. -
Counting the number of records in a related table - going round in circles
I have viewed about 50 Stack Overflow questions as well as numerous Google articles but my head is hurting and I'm just not getting this. I have the following database tables and fields: Cases: --id --Name Information: --id --case_id --detail What I want to do is to count how many information records there are for each case. So in psuedo code it would be something like: SELECT COUNT(*) FROM Information WHERE case_id=id Or similar. My desired output is something like: Case#1 has 43 information records Case#2 has 16 information records Case#3 has 8 information records etc... I have tried mainly using the annotate function in django, and then specifying foreign keys in the models.py file. I think I have confused myself though as I have tried so many things now. views.py: def cases(request): #didnt work - number = Cases.objects.annotate(Count('id')) #didn't work - questions = Information.objects.annotate(number_of_information_records=Count('id')) #didn't work - results = Information.objects.annotate(number_of_information_records=Count((Case(When(Cases.id == Information.case_id), output_field=IntegerField())))) models.py: class Cases(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Case_Name', max_length=255) # Field name made lowercase. ##this was an attempt to get it to work ##information = models.ForeignKey("Information", on_delete=models.CASCADE, db_column="id") def __str__(self): return self.name class Meta: managed = False db_table = … -
Django aggregate, How to minus the total of two different models
I want to get the total of model 1 - model 2 . this are my model Model1 class Prod(models.Model): blerje = models.ForeignKey(Blerje, on_delete=models.CASCADE) produkti = models.ForeignKey(Produkti, on_delete=models.CASCADE) sasia = models.PositiveIntegerField() Model2 class Produ(models.Model): # Shitje shitje = models.ForeignKey(Shitje, on_delete=models.CASCADE) produkti = models.ForeignKey(Produkti, on_delete=models.CASCADE) sasia = models.PositiveIntegerField() My view produktb = Produkti.objects.filter().annotate(totals=(Sum('prod__sasia'))) produkts = Produkti.objects.filter().annotate(totals=(Sum('produ__sasia'))) total = Produkti.objects.filter().annotate(totals(Sum(F('prod__sasia')-F('produ__sasia'), output_field=FloatField()))) i want to do produktb - produkts = total example current error: prod__sasia = 10 - produ__sasia= 5 total = 5, when i go to add the same Produkti produ__sasia = 5 for another client adds automatically prod__sasia = 10 and give me the total = 10 when he has to give me = 0 -
Postgresql TrigramSimilarity Does Not Work With Ubuntu Server
The code I have an issue with is this: return models.Channel.objects.filter(name__unaccent__trigram_similar=search_term ).annotate(similarity=TrigramSimilarity('name', search_term), similarity_foreign_language=TrigramSimilarity('name_foreign_language', search_term) ).filter(Q(similarity__gt=0.3) | Q(similarity_foreign_language__gt=0.3) ).order_by('-similarity', '-similarity_foreign_language', 'name')[:15] It works well on the development server which is installed at my home. It does not work only on the cloud server which is abroad. I suspected that it might be a locale problem, but I could not find an issue with that. The Postgresql database is set to UTF-8 and Collate and Ctype are set to C.UTF-8. Also, Django Admin seems to handle the foreign language as well. When I order them using a field, they are ordered well. But the code above does not work. -
query returns none when querying by icontains
I've got a Customer model that has a field 'name'. I've got an instance of that Customer model where the name field is equal to 'John Smith' The following query returns None and I'm not sure why. qs = Customer.objects.filter(Q(name__icontains="John Smith")) The following query does return the customer qs = Customer.objects.filter(Q(name__icontains="John")) Any thoughts as to why the first queryset returns None? Thanks! -
Page cannot be found when searching for slug
I've got a search field within my page. I'm replacing spaces within the searched string with "+". The url for the search view looks like this: url(r'^profile/customersearch/(?P<searchcriteria>[\w-]+)/$', views.customersearch, name="customersearch"), When I try to execute a search with a string with no spaces, it works just fine. When I try to execute a search for a string with spaces, I get a page not found. Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/profile/customersearch/jimmy+smith Any thoughts as to why? Thanks! -
How to apply object level group permissions in Django
I have a Model named Memo that creates objects which end up as text fields on a page. What I would like to do is add a ChoiceField to the Memo class that allows the user to select which groups can see the memo. I am seeing Django-guardian for object level permissions but I'm wondering if this is the best way to handle this problem. I'd like to note that I'm also going to send notifications to the users when they get a memo sent to their group. For this I see Django-Notifications. I hate to add on too many external models but it seems like Django is good for that type of thing. Advice on how to best handle it is appreciated. -
Salut, j'essaie d'utiliser easy_pdf l'API dans mon application, jai effectué les installations et tout est ok mais ça me donne ceci :
ModuleNotFoundError: No module named 'easy_pdf' -
How to show data in local time to user in Django application?
How can I show data in the timezone of the user's computer clock. Not sure if this is related to this, but I get the following error whenever new data comes in, not sure if it is related: RuntimeWarning: DateTimeField Stat.created_at received a naive datetime (2019-09-29 22:50:35.812668) while time zone support is active. RuntimeWarning) views.py contains: from django.utils import timezone # some other code and then: stat = Stat() stat.message = customer_message stat.created_at = timezone.datetime.now() stat.save() models.py contains: class Stat(models.Model): message = models.TextField(max_length=400) created_at = models.DateTimeField() data.html contains: {% for stat in stats %} <td>{{ stat.message }}</td> <td>{{ stat.created_at | date:'M j, Y g:m:s A' }}</td> {% endfor %} -
How do I add a reverse field value into the django serializer data set
I have a parent id in an object that contains child data. I want to add another field value from the parent id into the serializer for the child table to return back to the view I made a nested serializer, but the literature only focuses on updating the parent and child object. I only want to update the child object, but I want a field from the parent object added to the data of the serializer. The reverse relationship is especially confusing because 1. it didn't work for me, and 2. the example here uses it on a parent item which was already used as an example of a forward relationship. https://www.django-rest-framework.org/api-guide/serializers/ class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ['choice_text', 'votes', 'question'] class QuestionSerializer(serializer.ModelSerializer): choice = ChoiceSerializer(many=True) class Meta class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)# Create your models here. def __str__(self): return self.choice_text s = ChoiceSerializer(data={'choice_text':'tests','votes': 50, 'question':1}) s.is_valid() s.save() I got this from s.data: ReturnDict([('choice_text', 'tests'), ('votes', 50), ('question', 1)]) I would prefer this: ReturnDict([('choice_text', 'tests'), ('votes', 50), ('question_test', … -
provide rows by priority in django
I have the following model in django: class task(models.Model): admin = models.BooleanField() date = modesl.DateField() I am trying to achieve a filter which provides me with a query_set that prioritize if admin = True So assume I have these 3 rows : admin = True , date = 01-01-2019 admin = False , date = 01-01-2019 admin = False , date = 02-02-2019 The output of the query set will be : admin = True , date = 01-01-2019 admin = False , date = 02-02-2019 it should filter out the row with 01-01-2019 which admin=False because there is already an admin=True row which should take prioritization. I could do it by fetching all and removing it from the query_set myself, but want to make sure there is no other way of doing it before. -
How to created a nested dictionary with list values?
I have the follow two queryset: opus = Work_Music.objects.filter(composerwork__person=self.kwargs['pk'], level=0).order_by('date_completed') event = LifeEvent.objects.filter(person=self.kwargs['pk']).order_by('date_end') The first pulls the work of a composer and the second pulls his life events. I want to create a nested dictionary: The first level is keyed by year. The second level has two keys 'work' and 'life'. It should be a list of values because there could be multiple work and events in a given year. I have written following: # timeline = defaultdict(list) timeline = dict() for o in opus: if o.date_comp_f not in timeline: timeline[o.date_comp_f] = {} timeline[o.date_comp_f]['work'] = {} timeline[o.date_comp_f]['work'].append(o) else: timeline[o.date_comp_f]['work'].append(o) for e in event: if e.date_end_y not in timeline: timeline[e.date_end_y] = {} timeline[e.date_end_y]['life'] = {} timeline[e.date_end_y]['life'].append(e) else: timeline[e.date_end_y]['life'].append(e) timeline = dict(timeline) I also want to sort the first level key in chronological order. How do I do this? I keep getting Key errors. -
Clear all children subcategories of a selected (sub)category in a chained dependent dropdown combobox selection
I'm trying to implement chained dependent dropdown combobox selection, so you start with one combobox for main category and once you select main category, another <select> appears for selecting a subcategory, and so on until the innermost (most specific) subcategory is selected. Let's say that I have two main categories, Books and Shoes, so if I go Books -> Textbooks -> Primary school, then I decide to go for Shoes instead, four <selects>s would appear. Instead, I want to clear all children subcategories of a selected (sub)category (in this scenario, two <select>s (Textbooks and Primary school)) and leave the user to chose from only main category. Or, if I chose Books -> Literature, it should remove the Primary school/High school <select> and show subcategories of 'Literature'. Here is my jQuery code in a Django template: {% extends 'pages/base.html' %} {% block content %} <h1>Create a product</h1> <form method='POST' id='productForm' data-products-url="{% url 'products:ajax_load_categories' %}"> {{ form.as_p }} </form> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var $r_ = function() { var url = $("#productForm").attr("data-products-url"); var categoryId = $(this).val(); $.ajax({ url: url, data: { 'category': categoryId }, success: function (data) { if (data != 'leaf_node') { $(".subcategories").append(data); } $('select').change($r_); } }); } //end of $r_ $('select').change($r_); … -
how to create a proportional (pre-define boundaries) colour bar with python bokeh library
I would like to plot a graph with a proportional colour bar on the right like graph 1, but with bokeh rather than matplotlib: The matplotlib version is: proportional (pre-define boundaries) colour bar using matplotlib colors.BoundaryNorm(bounds, cmap.N) But my current bokeh version is looks like this: right hand side colour bar not proportional, although I have given ticker boundaries Please see my bokeh version code. Although I have given ticker boundaries, but the colour bar still not proportional. ticker = FixedTicker(ticks=bounds) bounds = [0, 5, 25, 75, 95,100] color_bar = ColorBar(color_mapper=mapper, major_label_text_font_size='5pt', ticker=ticker, formatter=PrintfTickFormatter(format='%d%%'), label_standoff=6, border_line_color=None, location=(0, 0)) The reason I use bokeh is because I would like to use it with Django and have the tools option within the bokeh library. Please give suggestions. Thanks in advance, -
When doing GET request to localhost:121/logout I get "accounts.views.logout didn't return an HttpResponse object". Is this an issue?
When I go to localhost:121/logout I get The view accounts.views.logout didn't return an HttpResponse object. It returned None instead. Should I modify my code, to deal with this, or is this not an issue? My logout is working fine. Do I have to list logout in my urls.py? views.py def logout(request): if request.method == "POST": auth.logout(request) return redirect('login') urls.py from django.urls import path from . import views urlpatterns = [ path('register/', views.register, name='register'), path('logout', views.logout, name='logout'), path('', views.login, name='login'), ] profile.html <ul> <li> <a class="dropdown-item" href="javascript:{document.getElementById('logout').submit()}">Logout</a> </li> <form id="logout" action="{% url 'logout' %}" method="POST"> {% csrf_token %} <input type="hidden"> </form> </ul>