Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to set the DOCKER_HOST?
ERROR: Couldn't connect to Docker daemon at http://127.0.0.1:2375 - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. -
What is the point of a django virtualenv, if when deploying with apache, wsgi.py is executed on the server NOT in the virtualenv?
I have my apache config set up to point to my virtualenv, but when i load the page and look at the error log it gives the following error: from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi apache2 000-default.conf file: WSGIDaemonProcess project python-home=/home/django/config/env python-path=/usr/local/bfx/Databases/project WSGIProcessGroup project WSGIScriptAlias / /usr/local/bfx/Databases/project/project/wsgi.py Basically, it will work if I install django, and all my django packages on my server, but what is the point of the virtual env? Thanks -
changes does not reflected in tempate django till server is refreshed
I am trying to update the logo of my website and there is no problem till uploading it and loading it in template for the first time. But, when i try to update the logo, it does not reflect in the template until i make some changes to intentionally refresh the Django server or i break and run it again. I am using DJANGO 1.11.3 and PYTHON 3. I am still very new to django, if anyone need anything else other than the below content, i will provide. Thanks Header.html <a href="#" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <!-- logo for regular state and mobile devices --> {% load static %} {% for i in company_logo %} <img class="NO-CACHE" src = "/{{ i.Company_logo }}" alt="Profile Picture" style="height:50px;width:120px"> {% endfor %} views.py from .models import Company_master company_logo = Company_master.objects.all() def companys_logo(request): company_data = Company_master.objects.all() return render(request,'service/companys_logo.html',{'company_logo':company_logo, 'company_data':company_data}) def post_company_logo(request): company_id = request.POST.get('inp_id_hidden') company_logo = request.FILES.get('inp_company_logo') company_obj = Company_master.objects.get(Company_code = company_id) company_obj.Company_logo = company_logo company_obj.save() company_obj.refresh_from_db() return redirect("service:company_details") models.py class Company_master(models.Model): Company_code = models.AutoField(primary_key=True) Company_name = models.CharField(max_length=100) Address = models.CharField(max_length=200) Owner_name = models.CharField(max_length=50) Jurisdiction = models.CharField(max_length=100, null=True) Email = models.CharField(max_length=100, null=True) Email_service = models.CharField(max_length=50, null=True) Email_accounts = models.CharField(max_length=50, … -
Django 1.5 ImportError: No module named myproject.urls
Im trying to get a project working locally, however when I try and $python manage.py runserver I get the error: ImportError: No module named myproject.urls I am confident the project is set up properly I feel like something needs to be configured on my end, however I have not been able to solve it. The project structure looks like this /root -requirements.txt /myproject -manage.py /apps /settings -base.py -local.py settings/base.py ROOT_URLCONF = "myproject.urls" I have set my DJANGO_SETTINGS_MODULE=settings.local We were on python 1.4 before and now since we moved to 1.5 I havent been able to get the enviro working locally, it is however, working live. -
How can we redirect users to specified admin in Django?
I'm working on leave management system where a couple of users report to a particular manager( admin in terms of django, assume if there were more that one admin). from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 15) designation = models.CharField(max_length = 15) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField(help_text = 'mm/dd/yy') to_date = models.DateField(help_text = 'mm/dd/yy') reporting_manager = models.CharField(max_length = 50, default = None) reason = models.CharField(max_length= 180) accepted = models.BooleanField(('approval status'), default=False) def __str__(self): return self.name I've tried tweaking my admin.py by using loops and comparing the reporting_manager coloumn, but I couldn't reach my goal. I tried even using built-in user permissions, but that didn't help me. In brief, if there are more than admin with their names. The data/form should be visible to only those admin(s), whose name was mentioned in the form which was submitted y the user. -
Django ManyToMany relationship having through parameter
I have the following models for one of my Django apps: class Product(models.Model): product_name = models.CharField(max_length=50) description = models.CharField(max_length=150) class Seller(models.Model): seller_name = models.CharField(max_length=50) class Order(models.Model): date = models.DateField() order_details = models.ManyToManyField(Product, through="OrderDetails") class OrderDetails(models.Model): order = models.ForeignKey(Order) product = models.ForeignKey(Product) seller = models.ForeignKey(Seller) I am using tasty pie for my api's. When I am trying to make a get request on the order's received, I need order_details object nested within the order. Since the order_details field in Order model is a many-to-many field referring to the Products table but storing the data in OrderDetails table, it is giving me error mentioning that the Product object has no Seller item (Which is true). How can I achieve the desired result through my API? -
django.db.utils.IntegrityError: FOREIGN KEY constraint failed when adding or deleting User in admin
I am stuck in a problem and I am unable to resolve, I have made custom user model because I need multi-user types.But, when I tries to add User it gives me the error: sqlite3.IntegrityError: FOREIGN KEY constraint failed Models.py: class User(AbstractUser): is_student=models.BooleanField(default="False") Is_teacher=models.BooleanField(default="False") class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) batch=models.CharField(max_length=20) class Teacher(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) department=models.CharField(max_length=30) All was working well the user was adding through admin but when I tried to import users through csv file, after that It starts giving me the error.Csv file code is below: template_name = 'essay/THome.html' '''form_class = LoginFiles def get(self,request): form=self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self,request): csv_file=request.FILES["csv_file"] form=self.form_class(None) if not csv_file.name.endswith('.csv'): messages.error(request, 'File is not csv type') return redirect('essay:file') if csv_file.multiple_chunks(): messages.error(request, "File size is too big (%.2f MB)." %(csv_file.size/(1000*1000),)) return redirect('essay:file') file_data=pandas.read_csv(csv_file) myids=file_data['id'].tolist() passwords=file_data['password'].tolist() t_len=len(myids) for iterate in range(0,t_len): obj=User(username=myids[iterate],password=passwords[iterate]) obj.save() After above code I got an error. I have also removed the above code deleted all records and then added a new user but still it giving me the same error. Any suggestions why I am getting this? -
F() object is not resolving into a field value inside Case(When ()) annotation
I have a quite complicated query. I have two models Course and Group. They realted as OneToMany (one Course to many groups). I filter it all based on dates of courses and groups (nevermind why). In my view i have: groups = Group.objects.filter(date__gte=date_obj) qs = Course.objects.filter( ... ).annotate( groups_count=Count('group_set'), sort_date=Case( When(date__lt=date_obj, groups_count__gt=0, then=groups.filter(course__id=F('id')).start_date), default=F('date'), output_field=DateField() ) ).order_by('sort_date') So, that F('id') seems to be not resolving into an actual value, since that groups.filter always gives me empty QuerySet. -
Django sending unsubscribe link with email
how can i add an unsubscribe link in emails being sent. Also i want the user to be able to unsubscribe without being logged in. I am using Django==2.0.2. Any suggestions would be appreciated. -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Django is driving me crazy i swear to god this is the laast time i am gonna use django in anything after this project Anyway the error is written as in the tittle and i sweaar i did every fix on google and tried everything . .Tried to add (django.setup()) .Tried to add (DJANGO_SETTINGS_MODULE=myProject.settings) .Tried to write (py manage.py shell) .Tried eveeeeeeeerything and nothing worked !! .I didn't change anything except only i changed the models.py: from django.db import models class pet(models.Model): name=models.CharField(max_length=10) I spent 3 days trying to fix this stupid error and i can't !!! Any help would be appreciated before i switch from Django. .I use windows .I added paths to python and scripts. Has anyone faced this error before and solved it ?? Any help again would be apprecieated Thank you ! -
django Ajax GET url Not Found
I am trying to pass parameters using Ajax and Django 1.11 and getting the error Not Found: /enquiry/followup_alter/.Here is the code. Error: Not Found: /enquiry/followup_alter/ Ajax: $(document).ready(function () { $(".remove").click(function () { $(this).parents('tr').hide(); var a_href = $(this).attr('href'); $.ajax({ type:"GET", url:"/enquiry/followup_alter/", data:"id=" +a_href, success: function (response) { alert(response) } }); }); }) enquiry/urls.py: url(r'^followup_alter/id=(?P<id>[\d]+)/$', views.followup_alter), views.py: def followup_alter(request,id): get = Followup.objects.get(id = id) get.status = 1 get.save() return HttpResponse('Entry Removed') Please help! -
Convert existing dictonary to JSON with Python
In my current django project I have built a dictionary, which has a tuple inside of it, that contains data about a given team. A team consists of resources that have a sub-role and allocation to that particular team. The problem now is that I need to convert this dictionary to JSON-format because I want to use different Google Charts to visualize the data, and I can't figure out how to do that. Here is a example from the dictonary: {'Team Bobcat': {'Tom Bennett': {('Build Master', 50)}} {'Team Coffe': {'Garfield Foster': {('Scrum Master', 100)}} I think that I probably need to loop through my dictionary and build each part of the JSON, but not sure how to do that. Tried to use json.dumps(data), but that only game me a error saying "object of type 'set' is not json serializable", which I read something about in this post: Serializable Can anyone give me any advice? -
How to fix ImportError:No module named urls?
all I am trying to run a Django application and came across and error that says: ImportError:No module name urls. Here is the TrackBack that I got: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/Library/Python/2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in call return self.application(environ, start_response) File "/Library/Python/2.7/site-packages/django/core/handlers/wsgi.py", line 168, in call self.load_middleware() File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 46, in load_middleware mw_instance = mw_class() File "/Library/Python/2.7/site-packages/django/middleware/locale.py", line 23, in init for url_pattern in get_resolver(None).url_patterns: File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 367, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 361, in urlconf_module self._urlconf_module = import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/edwardkeselman/Desktop/Work/Crowdview/crowdview/urls.py", line 20, in url(r'^analysis/', include('data_analysis.urls')), File "/Library/Python/2.7/site-packages/django/conf/urls/init.py", line 28, in include urlconf_module = import_module(urlconf_module) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/edwardkeselman/Desktop/Work/Crowdview/data_analysis/urls.py", line 2, in from data_analysis import views File "/Users/edwardkeselman/Desktop/Work/Crowdview/data_analysis/views.py", line 4, in from rest_framework.decorators import api_view File "/Users/edwardkeselman/Library/Python/2.7/lib/python/site-packages/rest_framework/decorators.py", line 16, in from rest_framework.views import APIView File "/Users/edwardkeselman/Library/Python/2.7/lib/python/site-packages/rest_framework/views.py", line 16, in from rest_framework import exceptions, status File "/Users/edwardkeselman/Library/Python/2.7/lib/python/site-packages/rest_framework/exceptions.py", line 18, in from rest_framework.compat import unicode_to_repr File "/Users/edwardkeselman/Library/Python/2.7/lib/python/site-packages/rest_framework/compat.py", line 21, in from django.urls import ( # noqa ImportError: No module named urls Here is my urls.py file: from django.conf.urls import patterns, include, url … -
django choices dependency (model)
I have a simple models.Model class that has 2 models.CharField fields. The first field uses choices tuple, termed CHOICES1. The second field uses a different choices tuple, termed CHOICES2, but only a portion of it, depends on the choice that was made is the first field. Can you please guide me how to obtain this behavior? I've seen similar questions on the net, but couldn't gather all the pieces of information... It would be great if you could come up with comprehensive guidelines (step-by-step), for all the files I need to maintain, e.g. models.py, views.py, forms.py, specific js (if any), etc. Thanks ahead, Shahar -
How to create multiple objects along with a foreignkey whose foreignkey field is provided?
class User(models.Model): email = models.EmailField() class Lawyer(models.Model): user = models.OnetoOneField(User) class Session(models.Model): lawyer = models.ForeignKey(Lawyer) name = models.TextField() class SessionSerializer(serializers.ModelSerializer): email = serializers.SerializerMethodField() fields=['name', 'lawyer','email'] I do not have the lawyer id in the request , my request contains only email and name of the session. I need to create multiple objects with session serializer but how to save the lawyer by using the email that is passed? -
How to print two list simultaneously?
This is my views.py file in django def twitter_trend(request): tweets, urls = main() context = { "trends": tweets, "urls": urls, } print(context) return render(request, "feed/trends.html", context) In my template I want to print the value of trends and urls simultaneously. This is my template file {% extends 'feed/base.html' %} {% block content %} <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="thumbnail-center"> <font size="4"> <p>Trending Tweets</p> </font> </div> {% for t,u in tweets,urls %} {{ t }}{{ u }}<br> {% endfor %} </div> <div class="col-md-3"></div> </div> {% endblock %} But when I run the server I got the following error: Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ',urls' from 'tweets,urls' Please help me how can I iterate throw two list? -
Can I use prefetch_related to cache filtered querysets?
I am using DRF to serialize some related models. In my toy example below, assume that each author can have a million books. Clearly doing a db query for all "good" books and then another db query for all "bad" books is inefficient. This post [http://ses4j.github.io/2015/11/23/optimizing-slow-django-rest-framework-performance/] offered some suggestions regarding prefetch_related. But I found that this only helped when I made subsequent calls to .books.all() rather than .books.filter() as happens in the properties below. Is there any automatic way in Django to cache the books queryset and not have subsequent filters to it hit the database again? Here is some code: models.py: class Author(models.Model): name = models.CharField(max_length=100) @property def good_books(self): return self.books.filter(is_good=True) @property def bad_books(self): return self.books.filter(is_good=False) class Book(models.Model): title = models.CharField(max_length=100) is_good = models.BooleanField(default=False) author = models.ForeignKey(Author, related_name="books") serializers.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ("title",) class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ("name", "good_books", "bad_books",) good_books = BookSerializer(many=True, read_only=True, source="good_books") bad_books = BookSerializer(many=True, read_only=True, source="bad_books) @staticmethod def setup_eager_loading(queryset): queryset = queryset.prefetch_related("books") return queryset views.py: class AuthorViewSet(viewsets.ReadOnlyModelViewSet): serializer = AuthorSerializer def get_queryset(self): queryset = Author.objects.all() queryset = self.get_serializer_class().setup_eager_loading(queryset) return queryset Thanks. -
Issue with dependent_fields in django forms
I'm getting issues with my Django form and I'm blocked since few days. This is the context : User can make a choice inside a first list of objects (list of laboratories) Once the laboratory is selected, user can make a second choice among a list of documents for the selected laboratory previously I would like to pick-up informations according to the choosen document This is my model.py file : class Omcl(models.Model): name = models.CharField(verbose_name=_('name'), max_length=255) country = models.ForeignKey(Country, related_name="country", on_delete=models.PROTECT) ... class Document(models.Model): title = models.CharField(verbose_name=_('title'), max_length=200) src_filename = models.CharField(verbose_name=_('Filename'), max_length=254) category = models.CharField(verbose_name=_('category'), max_length=10, choices=CAT_CHOICES, blank=True) omcl = models.ForeignKey(Omcl, related_name='documents', on_delete=models.CASCADE) Then, I have a views.py file (CBV) like this : class ManageDocView(View): template_name = 'omcl/manage_doc_form.html' form_class = ManageDocForm success_url = 'omcl/manage_doc_form.html' def get(self, request): form = self.form_class context = { 'form': form } return render(request, self.template_name, context) And I have a forms.py file : class ManageDocForm(forms.Form): omcl_list = forms.ModelChoiceField( queryset = Omcl.objects.all(), label = u"Choix de l'OMCL", widget = ModelSelect2Widget( model = Omcl, search_fields = ['code__icontains', 'name__icontains'] #Research over both attributes : code and/or name ) ) document_list = forms.ModelChoiceField( queryset = Document.objects.all(), label = u"Choix du Document", widget = ModelSelect2Widget( model = Document, search_fields = ['category__icontains', … -
Use annotated values as value in when()
I try to use a calculated value with annotated fields in the "then" parameter of a When(). Django raise me an error: can't adapt type 'CombinedExpression' Here is my code: categories = Category.objects.filter( Q(amount__card__date__range=( start_day_compare, stop_day_compare )) | Q(amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare )) ).annotate( somme=Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ) ).annotate( previous_somme=Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ).annotate( evolution=Case( When( ~Q(previous_somme=0), then=Value( ( ( Sum( 'amount__amount', filter=Q( amount__card__date__range=( start_day_compare, stop_day_compare ) ) ) - Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ) * 100 ) / Sum( 'amount__amount', filter=Q( amount__card__date__range=( previous_start_day_compare, previous_stop_day_compare ) ) ) ) ), default=Value('N/A'), output_field=CharField() ) ).order_by( 'order' ) So I try to annotate as "evolution" a percentage of evolution between previous_somme and somme. But when previous somme is 0 I don't want to do the calculation (because of division by zero). But it seems impossible to do calculation inside the Value. I tried to use directly "somme" and "previous_somme" but they are not reconized. Do you have an idea to do this? Thanks -
How to clear form fields after a submit a button in Django
I have this Views.py from django.shortcuts import render,redirect from django.views.generic.edit import FormView from .forms import ReportForm from django.views import View import spacy import pdb nlp = spacy.load('en_core_web_sm') class stopwordsremoval(FormView): template_name = 'report.html' form_class = ReportForm #pdb.set_trace() def form_valid(self, form): document1 = (form.cleaned_data.get('text')) return redirect('report_details', document1) return http.HttpResponseRedirect('') class ReportDetails(View): def get(self,request,document1): word_lemma = [] #pdb.set_trace() for word in (nlp(document1)): a = (word.is_stop, word.text) word_lemma.append(a) searchedData = (word_lemma) return render(request, 'report.html', {'naturallanguageprocessing': searchedData}) forms.py from django import forms import pdb class ReportForm(forms.Form): #pdb.set_trace() text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100})) it is creating the form and renders it below is the html code html {% extends 'base.html' %} {% block content %} <h1>StopWordsRemoval</h1> <div> <form action = "" method = "post" > {% csrf_token %} {{ form.as_p}} <button type="submit">stopwordsremoval</button> </div> <div > <ul> <li>{{ naturallanguageprocessing }}</li> </ul> <a href="{% url 'stopwordsremoval' %}" </a> <style> div { width: 1000px; border: 5px solid green; padding: 10px; margin: 10px; } </style> </div> </div> {% endblock %} my problem is while clicking button form will display we can enter input and get output at same place but button remain same form will invisible.my requirement is everything should be same only when i click button it output … -
Django, getting url parameter into view
I have a company model, each instance of which has a foreign_key named admin to a user. I am writing a view to allow company admins to administer their companies: urls.py: path('admin/crn=<company_spec_url>', CompanyAdminView.as_view(), name="CompanyAdminView"),` views.py: class CompanyAdminView(LoginRequiredMixin, UserPassesTestMixin, TemplateView): template_name = 'company_admin.html' def test_func(self): company = Company.objects.filter(crn=context['company_spec_url'])[0] return company.admin == self.user def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['company'] = Company.objects.filter(crn=context['company_spec_url'])[0] context['announcements'] = CompanyAnnouncement.objects.filter(company__crn=context['company_spec_url']) return context The get_context_data bit is working fine, the issue is in the test_func. Clearly only the company's admin should be allowed to administer a company, so I am trying to get the into the test_func, in order to test against it. The code in test_func does not currently work, because it does not have access to context. Is it best practice to: Call super().get_context_data once, and make context a global variable so that it can be accessed from test_func - Call super().get_context_data twice, once in get_context_data and once in test_func, or something else entirely? I've tried looking at the GET dict in the request, but it's empty. I could just parse the url within test_func to get the parameter myself, but it doesn't seem like the 'correct' way to do it. -
Using global variable within django template item value
I want to save variable in ModelItem.textarea_field value Example TextModel(models.Model): title = models.CharField(), content = models.TextField(), author = models.CharField(), Then Save item like this: author = "S. King" title = "One more amazing book" content = "It was amazing book by {{ article.author }}" Usage in template: <h1>{{ article.title }}</h1> <p>{{ article.content }}</p> Expecting that content will render "article.author" variable Now: It was amazing book by {{ article.author }} Needs to be: It was amazing book by S. King Thoughts May be something like english.ini file with text and variable in it logout_from_account = Logout from account %account% and then in template {{ english_dict_file.logout_from_account }} -
Django models range from to
Hello In my model I have age_from = models.IntegerField(blank=True, null=True, verbose_name='Age min.') age_to = models.IntegerField(blank=True, null=True, verbose_name='Age max') I would like to have age to to be greater or equal to age from -
Multiple file uploads in django admin
I have a House and a HouseImage models: class House(models.Model): ... class HouseImage(models.Model): image = models.ImageField() house = models.ForeignKey(House, related_name='images') The problem is to allow users in admin page upload multiple HouseImages. Now I have HouseImageAdmin as an inline of HouseAdmin and in this case user can't add multiple HouseImages by uploading multiple files, user must add new inline object then upload file then repeat those actions N times. I want to add one multiple file upload widget which will automatically add HouseImage for each uploaded file. How can I do it? -
pycharm: says package not installed but server runs fine from terminal without any error
I have a Django project. I have installed django-extensions from terminal and added django-extensions to installed apps Now in pycharm when i run the server it says django-extension not found. But i can run the server from terminal without any errors. In pycharm > settings > python interpreter : django-extensions is not shown. I checked pip list in terminal and it shows django-extension package. ALso i can see django-extension folder in site-packages. I am not able to understand whats the problem.