Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get addition field in through model serializer
Guys where i am doing wrong. I wanna get third field in my through model, but its always try to find it in related field. class WeekNutrientCreateSerializer(ModelSerializer): id = PrimaryKeyRelatedField(queryset=Nutrient.objects.all()) class Meta: model = WeekNutrient fields = ('id', 'volume',) class WeekCreationSerializer(ModelSerializer): nutrients = WeekNutrientCreateSerializer(many=True) growing_technologies = PrimaryKeyRelatedField(many=True, queryset=Technology.objects.all()) class WeekNutrient(Model): week = ForeignKey(Week, on_delete=CASCADE, related_name='week_nutrients') nutrient = ForeignKey('nutrients.Nutrient', on_delete=CASCADE, related_name='week_nutrients') volume = DecimalField(max_digits=3, decimal_places=2) Original exception text was: 'Nutrient' object has no attribute 'volume' -
Django getlist() return empty
I have the following array trough POST 'options[0][item_1]': ['3.50'], 'options[0][item_2]': ['text 1'], 'options[1][item_1]': ['5.50'], 'options[1][item_2]': ['text 2'], 'value[0][item_1]': ['2.50'], 'value[0][item_2]': ['text 3'], 'value[1][item_1]': ['1.5'], 'value[1][item_2]': ['text 4'] I would like to transform both arrays and merge them so I use .getlist() options = request.POST.getlist('options') # result: [] value = request.POST.getlist('value') # result: [] But in both cases it returns an empty array.. -
Extend INSTALLED_APPS in settings.py from django reusable app
I'm building a reusable app that has other django dependencies (django-rest-framework for example). I know that if I add it to install_requires in setup.py it will be packaged. But is there a way I can also extend INSTALLED_APPS in settings.py from the project that is using my packaged app so that it adds all the dependencies? At the moment, with this configuration, if I install my packaged app, I need to add my app name to INSTALLED_APPS but also all its dependencies, manually. I would like to think there's a way to avoid having to add all the app's dependencies manually into INSTALLED_APPS ? -
Supervisor uwsgi django import error No module named X
I deployed my django codes to aws recently and I tried to run it using uwsgi but I faced some issues. I can run server on aws using python manage.py runserver and it's working fine. But I can't run it with supervisor and nginx + uWSGI In supervisor error log I can see ModuleNotFoundError: No module named 'mydjangoprojectname' At first I had this command in my supervisor config file path_to_venv/uwsgi --http :9000 --wsgi-file path_to_project/wsgi.py It didn't work , so I tried to run the command in terminal manually( to see if I can run it with uwsgi or not ) , it was working fine! but when supervisor is starting it I am getting ModuleNotFoundError: No module named 'mydjangoprojectname' Instead of calling uwsgi I replaced the command to a script containing this : cd path_to_project_folder source path_to_virtual_env/bin/activate uwsgi --http :9000 --wsgi-file path_to_project/wsgi.py when I run the script in terminal it works fine. but in supervisor I get error again. After 8 hours of trying, I gave up and I'm here to see if anybody faced this issue before .. -
Django Production - TemplateDoesNotExist at /
I've been running into some troubles trying to deploy my Django project to Azure web app. i'm getting the error TemplateDoesNotExist at / When trying to connect to the site I get the following (DEBUG = True) when connecting to the production enviornment on the running server: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/site/wwwroot/templates/food/home.html (Source does not exist) django.template.loaders.filesystem.Loader: /home/site/wwwroot/django_azure_demo/templates/food/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /antenv/lib/python3.8/site-packages/django/contrib/admin/templates/food/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /antenv/lib/python3.8/site-packages/django/contrib/auth/templates/food/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/site/wwwroot/food/templates/food/home.html (Source does not exist) my view function def index(request): context = {} #rest ormitted return render(request, 'food/home.html ', context) From Azure portal I can from advanced tools, see in Kudu console, that I can navigate to and see the path exists for the first '/home/site/wwwroot/templates/food/home.html' Django tries to load. My templates settings are: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS' : [ os.path.join('templates'), ], 'DIRS' : [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I've been searching stackoverflow and other sites, but I could not find any which could help me. :/ Thanks in advance. -
Using a const variable in django
Whenever I try to define a 'const' variable in a django template I am told that its already been declared when I didn't declare it anywhere. I cannot find any material on this. This is what I have in my Django Template: <div> <li class="color">Blue</li> <li class="color">Red</li> <li class="color">Green</li> <li class="color">None</li> <div> The CSS reads like this: <style type="text/css"> .hidden { display: none; } </style> The JavaScript reads like this: <script type="text/javascript"> const colorLines = document.querySelectorAll('.color'); colorLines.forEach(element => { if (element.innerHTML == "None") { element.classList.add('hidden'); } }); </script> The aim is to not show anything if "None" is typed in. I know the JavaScript above works I've made a similar HTML file to it stand alone and its just fine. Django doesn't allow const or let for some reason and I can't find why not. And if I try var it throws no errors but still no outcome. I checked the same code outside of django. I can't seem to find what I am missing. -
Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/$'], but post_detail was working
i am integrating user profile and i am using CustomUser in the model here is the models.py: class CustomUser(AbstractUser): age=models.PositiveIntegerField(null=True,blank=True) name = models.CharField(max_length=50,null=True) image=models.FileField(upload_to="mediaphoto") propic=ImageSpecField(source='image',processors=[ResizeToFill(200,100)],format='JPEG',options={'quality':60}) and views.py: class SignUpView(CreateView): form_class=CustomUserCreationForm success_url=reverse_lazy('login') template_name='signup.html' class ProfileView(ListView): model=CustomUser template_name='profile.html' urls.py: urlpatterns = [ path('post/<int:pk>/delete/',BlogappDeleteView.as_view(),name='post_delete'), path('post/<int:pk>/edit/',BlogappUpdateView.as_view(),name='post_edit'), path('post/new/', BlogappCreateview.as_view(),name='post_new'), path('post/<int:pk>/',BlogappPostView.as_view(),name='post_detail'), path('post/<int:pk>/category', views.CategoryDetail, name='category'), path('profile/',ProfileView.as_view(),name='profile'), path('search',views.Search,name='search'), path('',BlogappListView.as_view(),name='home'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) profile.html: {% block content %} <div class="container"> <div class="card mb-4"> <div class="media"> <img class="rounded-circle account-img" src="{{post.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 class="card-title">{{user.name}}</h2> </div> </div> </div> {% endblock content %} front page is displaying after runserver but when i click on the username, it is showing post_detail error. but before that post detail was working. my post detail in blogapp/views.py: class BlogappPostView(DetailView): model = Post template_name = "post_detail.html" does any one show me the remedy please? -
Django field which accepts string or user
I have a django model which I'd like to update either by a user submitted form, or by an admin uploading a csv. I'd like each user to only be able to modify 1 record (their organization/username). I'd also like to store data for organizations which are not users, via csv upload. This works only for csv upload: class OrgData(models.Model): organization = models.CharField(max_length=200, primary_key=True) This works only for the user form: class OrgData(models.Model): organization = models.OneToOneField( get_user_model(), to_field='username', on_delete=models.PROTECT, primary_key=True, ) How do I make the model work for both? Perhaps modify the save method? -
I am trying to use mysql with django but run into a problem when using pip to install mysqlclient [duplicate]
OS: Ubuntu 20.04 Django: >3 Python: 3.8 Full log: https://pastebin.com/B5YvNyBY pip3 install mysqlclient [...] unable to execute 'x86_64-linux-gnu-gcc': No such file or directory error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for mysqlclient -
Django averaging models inputs
I am able to take the average of the model inputs helpfulness, pedagogy, and easiness as seen in my models.py. However, I also want to take the average of the averages of these three ratings and name it as "overall". How do I do this in Django? models.py: from django.db import models from django.db.models import Avg class Prof(models.Model): name = models.CharField(max_length=100, unique=True) association = models.CharField(max_length=50) def avg_ratings(self): return self.ratings.aggregate( Avg('helpfulness'), Avg('pedagogy'), Avg('easiness'), ) def __str__(self): return self.name class Rating(models.Model): helpfulness_choices = ( (1, 'Very Unhelpful'), (2, 'Unhelpful'), (3, 'Moderate'), (4, 'Helpful'), (5, 'Very Helpful'), ) pedagogy_choices = ( (1, 'Very Low Pedagogy'), (2, 'Low Pedagogy'), (3, 'Moderate'), (4, 'High Pedagogy'), (5, 'Very High Pedagogy'), ) easiness_choices = { (1, 'Very Difficult'), (2, 'Difficult'), (3, 'Moderate'), (4, 'Easy'), (5, 'Very Easy'), } name = models.ForeignKey(Prof, on_delete=models.CASCADE, related_name="ratings") subject = models.CharField(max_length=10) helpfulness = models.IntegerField(choices=helpfulness_choices) pedagogy = models.IntegerField(choices=pedagogy_choices) easiness = models.IntegerField(choices=easiness_choices) comment = models.TextField() def __str__(self): return str(self.name) template: {% with avg_ratings=prof.avg_ratings %} Helpfulness: {{ avg_ratings.helpfulness__avg }} <br> Pedagogy: {{ avg_ratings.pedagogy__avg }} <br> Easiness: {{ avg_ratings.easiness__avg }} {% endwith %} -
djnago website with postsql database sitemap [closed]
hi everyone i am working on a Django website using postsql my question is mywebsite is taking almost 98% of data from postsql database and I want to upload that website on google I was searching on google that sitemap is important for SEO and how to create site map and if we create that how it will happen like I put new content on my database can I have to update site map myself or Django will automatically update that site map, can anyone tell me properly what is that how will it work with postsql database -
Python Django - pick existing random object id in template
I would like to ask, if it is possible to pick existing random object id in template. Here are my models.py: class ImageInGallery(models.Model): image = models.ImageField(upload_to='media/photos/') views.py; class GalleryListView(ListView): model = ImageInGallery context_object_name = 'images' def get_queryset(self): return ImageInGallery.objects.all().order_by('-id') In the template I would like to to something like this: {% for picture in images %} {% if picture.id == X %} <img src="{{ picture.image.url }}"> {% endif %} {% endfor %} Where 'X' is the existing random object id of the image model. Is there any way how to do it? Or is there any other better way? Thank you. -
How to change django date format in jquery?
believe me its not the duplication. I have Django app, where I want to take date from database and append it into text using jquery. Presently when I doing this, i am getting date like this: "2015-03-25T12:00:00-06:00" I want it to get displayed somehow like HH:mm mm-dd-yy. I know that Django filters can serve my purpose well but as I am outputting text using jquery, I can't use them. In jquery, I tried something like this: var date = new Date(date); var newDate = date.toString('dd-MM-yyyy'); But nothing seems to workout. Any good suggestions? -
Django Deserializer: Problem installing fixture. Must be an integer
I'm trying to load fixtures from a json file (using loaddata) - the json file was generated using django's dumpdata, but two FK fields (returned as one of their unique fields) throw up errors. Django is looking for PKs, but the JSON has strings and hence the error. Here's my code: Model1 - AreaProductStock and AreaProductStockManager class AreaProductStockManager(models.Manager): def get_by_natural_key(self, code, inv_code): self.get(area__code=code, product__inv_code=inv_code) class AreaProductStock(models.Model): objects = AreaProductStockManager() area = models.ForeignKey('Area', null=True, blank=True) product = models.ForeignKey('Product', related_name='area_product_stocks', null=True, blank=True) def natural_key(self): return (self.area.code, self.product.inv_code,) # Returns a tuple as expected Model2: Area and AreaManager class AreaManager(models.Manager): def get_by_natural_key(self, code): self.get(code=code) class Area(models.Model): CA = 'CA' MA = 'MA' AREA_CHOICES = [(CA, 'CA'), (MA, 'MA')] code = models.CharField(max_length=2, choices=AREA_CHOICES, db_index=True, unique=True) def natural_key(self): return (self.code,) Model3 - Product and ProductManager class ProductManager(models.Manager): def get_by_natural_key(self, inv_code): self.get(inv_code=inv_code) class Product(models.Model): inv_code = models.CharField(max_length=99, blank=True, null=True, db_index=True, unique=True) def natural_key(self): return (self.inv_code, ) Generated JSON: [ { "fields": { "product": [ "SOME-INV-CODE" ], "q_on_so": 0, "area": [ "CA" ], "current_stock": 10, "available_stock": 10, "q_on_po": 0 }, "model": "my_app.areaproductstock" } ] Here's the error I'm getting: django.core.serializers.base.DeserializationError: Problem installing fixture '/project_path/project/product.json': [u"'[u'SOME-INV-CODE']' value must be an integer."] -
KeyError 'user' while entering admin page. Error during template rendering
enter image description here KeyError -
How can i use DateTime field in model without second ,only date
I am creating a model that has a DateTime field. I want to store only date without seconds and hour. How can i do that? class Measurements(models.Model): d_value=models.IntegerField() created=models.DateTimeField(auto_now_add=True) patient=models.ForeignKey(UserSignupModel,on_delete=models.CASCADE) def __str__(self): return str(self.patient) -
Install GDAL Python [MSC v.1916 32 bit (Intel)] on win32
My version of Python is [MSC v.1916 32 bit (Intel)] on win32 but I cannot see a release 1916 in http://www.gisinternals.com/release.php. Can I use an older release with my version of Python? I am trying to learn more Django skills and wanted to add some mapping functionality to my site http://rossdjangoawesomeapp2.herokuapp.com/. The site is purely for testing / experimental purposes. -
Save User progress in Quiz Django
I have some models: from django.db import models from django.conf import settings class Question(models.Model): name = models.CharField(unique=True, max_length=50) desctiption = models.TextField(max_length=500, unique=True) def __repr__(self): return f"Question: {self.name}" class Answer(models.Model): """Answer for one question. Can be correct or incorrect""" name = models.CharField(unique=True, max_length=50) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=50) is_correct = models.BooleanField(default=False) def __repr__(self): return f"Answer: {self.name}" class Quiz(models.Model): """Quiz Model contain questions""" name = models.CharField(unique=True, max_length=50) desctiption = models.TextField(max_length=500, unique=True) questions = models.ManyToManyField(Question) def __repr__(self): return f"Quiz: {self.name}" class ProgressUserQuiz(models.Model): """Save user progress for any quiz""" ... I can't understand how to structure ProgressUserQuiz. For example. If user passed two questions in quiz and close a tab he can return to his last questions. And When he finished I want to add this in model. How can I make it?tnx -
Q object from other Q object
I have a complex Q-object query = Q(offer__price__gt=1000) query.add(Q(offer__delivery_days=0), Q.AND) query.add(Q(offer__stock__name='example')) Now I need to create similar Q-object, but to add product__ before each item. First way to do this is use dicts: query_dict = {} query_dict['offer__price__gt'] = 1000 query_dict['offer__delivery_days'] = 0 query_dict['offer__stock__name'] = 'example' query = Q(**query_dict) query_dict2 = {'product__' + k: v for k, v in query_dict.items()} query2 = Q(**query_dict2) Other way - iterate by Q.children query2 = Q() for f in query.children: kwargs = {'product__' + f[0]: f[1]} offer_filters.add( Q(**kwargs), Q.AND ) Both ways are ugly. How can I do this more pretty way? -
Is it possible to auto repair (on the fly) Django corrupted Mysql table upon exception?
I am using Django with Mysql as part of a product. Occasionally some table get corrupted and when accessing the table I get InternalError: (145, "Table 'some_table' is marked as crashed and should be repaired") exception. I then need to run a sql script which uses REPAIR TABLE command to fix the issue. My questions are: 1. Is there a django mechanism which will detect this issue, run "REPAIR TABLE some_table", print notification and then retry the operation which has failed? 2. if not - is it reasonable to put a decorator to django interface functions like filter, save etc.? of course if the operation will fail again after repair I will want to print something rather than continue to run the db operation again. I appreciate any answer especially one with an elaborated python example. Thanks in advance. -
ERROR: ModuleNotFoundError: No module named 'requests'
I try to import Response from requests in Django : from requests import Response Error : from requests import Response ModuleNotFoundError: No module named 'requests' -
"Uncaught SyntaxError: Cannot use import statement outside a module" when trying to import vue.js inside js file in Django app
I'm starting out using vue.js in a real django project, but I'm already encountering an issue. I've installed npm in the venv environment, and installed the vue package. I now want to create a Vue object inside a js file, so I use : import Vue from 'vue' But in the console I get this error Uncaught SyntaxError: Cannot use import statement outside a module I've searched for this issue but couldn't find a good answer for my specific case. How to proceed to use vue js via the npm package then ? -
Django Postgre ProgrammingError Sum(text)
I switched from sqlite to postgresql. postgresql working and everything works just fine. But after switched i take these error; ProgrammingError... Error: sum(text) function is not available. LINE 1: ...pollvote"."country", "poll_pollvote"."votecount", SUM("poll_... When i remove this code in template error is gone; {% for vote in votes %} {% if vote.country == data.country %} <tr> <th scope="row">{{ vote.vote }}</th> <td>{{ vote.votecount__sum }}</td> <td>{{ vote.votecount__sum|div:data.votecount__sum|mul:100|floatformat }} % </td> </tr> {% endif %} {% endfor %} I think my problem these code sum value; result = PollVote.objects.filter(title_id=view.id).values('vote', 'country', 'votecount').annotate(Sum('vote'), Sum( 'votecount')).order_by('-votecount__sum') When i remove 'vote' value code is start working. How can i use SUM func in 'vote' ? -
Django smart_selects chained field coming up empty
I am trying to implement chained dropdown list using Django smart_selects. But its not working as expected. After selecting the first dropdown, the second dropdown is not populating. model.py: class ServerInfo(models.Model): server = models.CharField(max_length=255, verbose_name='Server') def __str__(self): return self.server class Database(models.Model): database = models.CharField(max_length=255, verbose_name='Database') server = models.ForeignKey(ServerInfo,related_name='database', on_delete=models.CASCADE) def __str__(self): return self.database class Tables(models.Model): table = models.CharField(max_length=255, verbose_name='Table') database = models.ForeignKey(Database,related_name='table', on_delete=models.CASCADE) def __str__(self): return self.table class TransferJob(models.Model): source_server = models.ForeignKey(ServerInfo, related_name='source_server', verbose_name='Source Server', on_delete=models.CASCADE) source_db = ChainedForeignKey( Database, chained_field="source_server", chained_model_field="server", show_all=False, auto_choose=True, sort=True) source_table = models.ForeignKey(Tables, related_name='source_table',on_delete=models.CASCADE, verbose_name='Source Table') dest_server = models.ForeignKey(ServerInfo, related_name='destination_server', verbose_name='Destination Server', on_delete=models.CASCADE) dest_db = models.ForeignKey(Database, related_name='destination_database', verbose_name='Destination Database', on_delete=models.CASCADE) -
Django runs other url, not those I call
NoReverseMatch at /web2app/main_page Reverse for 'open_note' with arguments '('user001',)' not found. 1 pattern(s) tried: ['web2app/open_note/(?P[^/]+)/(?P[^/]+)$'] In file login_template.html in action I call url with name login and get this error and how I see django runs even not a login, it runs open_note url, can't understand why urls.py from django.urls import path from . import views app_name = 'web2app' urlpatterns = [ path('', views.login_page, name = 'login_page'), path('main_page', views.login, name = 'login'), path('note_page/<str:username>', views.note_page, name = 'note_page'), path('open_note/<str:username>/<str:theme>', views.open_note, name = 'open_note'), path('save_note/<str:username>', views.save_note, name = 'save_note'), path('registration_page', views.registration_page, name = 'registration_page'), path('registration', views.registration, name = 'registration'), path('<int:note_id>/put_text', views.put_text, name = 'put_text') ] views.py from django.http import Http404, HttpResponseRedirect from django.shortcuts import render from .models import Note, User from django.urls import reverse from django.utils import timezone def login_page(request): return render(request, 'web2app/login_template.html', {'bool': -1}) def login(request): user = User.objects.filter(username = request.POST['username'], password = request.POST['password']) if(len(user) != 0): user_temp = user[0] user_notes = user_temp.note_set.all() return render(request, 'web2app/main_page.html', {'user_notes': user_notes, 'username': user_temp.username}) else: return render(request, 'web2app/login_template.html', {'bool': 0}) def registration_page(request): return render(request, 'web2app/registration_template.html', {'bool': -1}) def registration(request): username = request.POST['Username1'] password = request.POST['Password1'] confirm_password = request.POST['Confirm_password1'] if (password == confirm_password): user = User(username=username, password=password) user.save() user_notes = [] return render(request, 'web2app/main_page.html', {'user_notes': user_notes}) …