Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key missing from migrations
I have the model Trade: from datetime import datetime from django.db import models from home.models import Player class Trade(models.Model): buyer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyer'), buyee = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyee'), date = models.DateTimeField(default=datetime.now) Model Player: from django.contrib.auth.models import User from django.db import models class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='user') value = models.IntegerField(default=1500) owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='owner', blank=True, null=True) A Trade happens between 2 Players. That is, the buyer and buyee fields in Trade are foreign keys to Player. Now, when I make migrations for the Trade model, this is what I get: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Trade', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(default=datetime.datetime.now)), ], ), ] Why are the 2 foreign key fields missing from the migration? -
How to configure Django-AllAuth to login using Facebook without entering password
I’m using Django AllAuth on my website. But, when people register using Facebook, they are asked to enter their password even when the Facebook account is open in the same browser. I’ve seen other websites where the user is signed up without asking for a password. How can I change the AllAuth settings to register without password? Here is the configuration I have: SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.12', }, } -
'something here' matching query does not exist
I created a web app and deployed on Heroku successfully even database migrations. When I open the app I see the error like this: 'something here' matching query does not exist. App URL: https://lp7.herokuapp.com/lp7/ App isn't working and if I remove this data feild from model, then app works but no single data is coming from database. But, when I go to heroku database it shows: No. of Tables = 28 No. Rows = 220 Size of data = 9.4Mb It means, the all migrations exists on heroku but not showing on website. Any solution..? -
How to implement a dropdown populated with values from a database
I am very new to Python and Django, thus having this issue. What I want to do is create a behavior of HTML Select tag with a Django form. This dropdown/select has to be populated with values from a database. What I already have is location = forms.ModelChoiceField(queryset = MyModel.objects.all()) which does give me a select/drowpdown control, but I need it to display one value from the database and have a different one as an actual value (both from the same table just different columns) What I mean in HTML code would look like this: <select> <option value="1">Berlin</option> <option value="2">New York</option> <option value="3">London</option> <option value="4">Riga</option> </select> So, using the form I would see a name of the city, eg. London, but when it is selected and submit is called I insert 3 in the database. Looking forward to your suggestions. -
How would I add a dropdown box that contains all the different type of models in my program?
I want a drop down box of all the models in my program. I made a myModels model that has a charfield of 100. I tried to add the choice tuple and then reference it in the model. helper_choices = [] for my_model in django.apps.apps.get_models(): helper_choices.append((my_model._meta.verbose_name, my_model._meta.verbose_name)) MODEL_CHOICES = tuple(helper_choices) model_name = models.CharField(max_length=100, choices=MODEL_CHOICES, default='') However since this is occurring during the loading of the models phase, I get an error "Models aren't loaded yet." What would be a workaround to this problem? -
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', …