Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems with Many to Many relationships in Django REST-framework
I am having some problems with the Many to Many relationships in Django. When you have a fresh setup of a Django REST framework app, you usually have two default models: Users and Groups. From within the web interface you can create groups. After doing this you will also be able to select an existing Group from a list to add to a user. Like so: http://prntscr.com/hp2lu0 Now when I try to do something like this myself, I get the following in my web-interface: Lists are not currently supported in HTML input.: http://prntscr.com/hp2pe5 Why does it work for Groups but not when I try do it myself? These are the models im trying to get it to work with: class Ip(models.Model): address = models.CharField(max_length=100) @classmethod def create(cls, address): ip = cls(address=address) # do something with the ip return ip class IpCollection(models.Model): title = models.CharField(max_length=100) ipAddresses = models.ManyToManyField(Ip) @classmethod def create(cls, title): ipCollection = cls(title=title) # do something with the ipCollection return ipCollection And this is how my serializers look like: class IpSerializer(serializers.ModelSerializer): class Meta: model = Ip fields = ('address',) class IpCollectionSerializer(serializers.Serializer): title = serializers.CharField(max_length=200) ipAddresses = IpSerializer(read_only=False, many=True) def create(self, validated_data): """ Create and return a new `IpCollection` instance, … -
How to get manytomanyfield model datas in View in Django
models.py class Account(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User') id = models.CharField(max_length=50, unique=True) pw = models.CharField(max_length=200) nick = models.CharField(max_length=50, blank=True) blog = models.URLField(null=True, blank=True) published_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.published_date = timezone.now() self.pw = make_password(self.pw) super(Account, self).save(*args, **kwargs) def __str__(self): return self.id class Meta: ordering = ["-published_date"] class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, default='auth.User') account = models.ManyToManyField(Account) published_date = models.DateTimeField(default=timezone.now) def publish(self): self.published_date = timezone.now() self.save() forms.py classAccountForm(forms.ModelForm): class Meta: model = NaverAccount fields = ('id', 'pw', 'nick','blog',) class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('account',) task.html <form action="#" class="form-horizontal" method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" type="submit">Save</button> views.py def task(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() #1. id = str(from Account model) #2. pw = str(from Account model) post.save() form.save_m2m() return redirect('task') else: form = TaskForm() context = {'form': form} return render(request, 'work/task.html', context) I'm making small task app. I want to get model datas that user select(Account) from template in view. ex) user can select 'id1', 'id2'. and i want to get id, pw value in view. so i can play small task with using id, pw in view i … -
Logger in Django project sends messages at sentry and console at the same time
I have this LOGGING setting in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'django.utils.log.NullHandler', }, 'sentry': { 'level': 'DEBUG', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'logfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(TELESPINE_ROOT, 'logs', 'server.log'), 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console', 'sentry'], 'propagate': True, 'level': 'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'project': { 'handlers': ['console', 'logfile', 'sentry'], 'level': 'DEBUG', }, 'sockets_server': { 'handlers': ['console', 'sentry'], 'level': 'INFO', }, } } And I also have this in the file with websocket server: logger = logging.getLogger('sockets_server') application.listen(3000) logger.info('WebSockets server started on 3000') Why do I always get not just console but also Sentry messages in my console while running sockets_server file. Instead of just getting this: [18/Dec/2017 11:50:47] INFO [sockets_server:149] WebSockets server started on 3000 I also get this: ERROR:sentry.errors.uncaught:[u'WebSockets server started on 3000'] And why this message is shown as error? It has just info level -
django xadmin not compatible with Multiselectfield
'''I wanna use Multiselefield module in xadmin to get multible checkboxs. But it is still dropdown option which only can choose one option and can't update to database. However Multiselectfield is no problem used in admin. It can update and show in the list_display while xadmin can't! How to resolve this issue in xadmin? admin: [enter image description here][1] [enter image description here][2] xadmin: [enter image description here][3] ''' model.py class RoomBooking(models.Model): ROOM_CHOICE = ( (1, 'Room1'), (2, 'Room2'), (3, 'Room3'), (4, 'Room4'), (5, 'Room5'), (6, 'Room6'), ) roomNumber = models.CharField(max_length=5, verbose_name=u'会议室', blank=True, null=True) roomStatus = models.CharField(max_length=10, verbose_name=u'会议室号状态', choices=(('occupied', '占用'), ( 'reserved', '预定'), ('available', '可用')), blank=True, null=True) roomUser = MultiSelectField(verbose_name=u'会议室使用者', choices=ROOM_CHOICE, default='1,3,5', blank=True, null=True) class Meta: verbose_name = u'会议室管理' verbose_name_plural = verbose_name form.py from django import forms from .models import RoomBooking class RoomBookingForm(forms.ModelForm): ROOM_CHOICE = RoomBooking.ROOM_CHOICE roomUser = forms.MultipleChoiceField(`enter code here` required=False, label='会议室', widget=forms.CheckboxSelectMultiple(), choices=ROOM_CHOICE, ) class Meta: model = RoomBooking exclude = ['roomNumber', 'roomStatus', 'roomUser'] adminx.py import xadmin from django import forms from .models import RoomBooking from .form import RoomBookingForm from xadmin.filters import format_html class RoomBookingAdmin(object): # form = RoomBookingForm list_filter = ['roomNumber', 'roomStatus'] search_fields = ['roomNumber', 'roomStatus'] list_editable = ['roomNumber', 'roomStatus', 'roomUser'] def has_delete_permission(*args, **kwargs): return False list_display … -
How do I correctly create a related object overriding the save() method?
I'm overriding the save() method on a subclass of a UserCreationForm. I'm doing so because I'd like to create another related object as the User object is created. Here is the form along with the save method: class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update({ 'duplicate_username': 'This username has already been taken.' }) class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) if commit: user.save() Profile.objects.create(user=user) return user So the Profile object is never created. I can get it to work, technically, if I remove the if commit: like so: def save(self, commit=True): user = super(MyUserCreationForm, self).save(commit=False) user.save() Profile.objects.create(user=user) return user However I'd like to know why False is being passed to the save() method each time I create a User. Based on what I've read, the conditional should be there in order to preserve the same behavior as the overridden save() method. -
Django template language - Python array with Javascript index
Well, maybe this is a silly question, but i couldn't find the answer so far. So, i am rendering a view in Django (i will do the code generic to make the problem easier), and the python side looks something like this: ... marray = [1, 2, 3, 4, 5] ... return render(request, "template.html", {"marray": marray}) Now, in the template.html file, I want to access the array, but the index must be determined by a JavaScript variable: var index = 2; var mvar = {{ marray.index }}; console.log(mvar); Output wanted: 3 Obviously, the previous code does not work, it's just to show what I want. Any suggestions? Thanks. -
AWS Cloud9 LinkedIn Authentication django
I have a project in AWS cloud9 when i tryed to do LinkedIn Authentication.(I used this guide - https://realpython.com/blog/python/linkedin-social-authentication-in-django/ and ran a server in port 8080) I added to my linkedin App the URL - http://127.0.0.1:8080/complete/linkedin-oauth2/ - to the field - 'Authorized Redirect URLs:' - in the 'OAuth 2.0'. When I ran the commend 'python manage.py runserver 127.0.0.1:8080' the server started running and open in random url when I tried to login by LinkedIn I got this error myError -
django and ajax - data not returning list values
The ajax request is sent when a user clicks a navigation bar list element. It redirects after the request is processed. The value I am trying to send is an array of an array. I get the data to return a list and print it in the terminal in django. It always shows a list that is empty. views.py @csrf_exempt def color_pick_stats(request): if request.method == 'POST': colors_lst = request.POST.getlist('colors') print(colors_lst) return render(request, 'stats/statistics.html') if request.method == 'GET': return render(request, 'stats/statistics.html') html <li class="list-element"><a href="{% url 'statistics' %}" style="text-decoration: none; color: white;"><span onclick="sendData()">Statistics</span></a></li> javascript function sendData() { $.ajax({ url: '', type: 'POST', data: { colors: color_pick }, success: () => { console.log('success'); }, error: (xhr,errmsg,err) => { console.log(xhr.status + ": " + xhr.responseText); } }) } When I alert the values of the list color_pick in javascript it gives the correct values. In django when printed in terminal the values do not return and the list is returned as empty. Thanks in advance. -
Form resubmission Django how to avoid for refresh or back button
I hava a django application. It is a form to fill (like answered 5 questions clicked next button and go to next five questions). All steps with questions are rendered within 1 view and 1 html file. If I click about_us or other link (to another view and html file), then back button click is followed with "Form resubmission required" and filling from the very beginning required. How to turn back strictly to the previous place. View render template with the next code. @secure_required def presubmit(request): if request.user.is_authenticated(): profile = request.user.profile try: profile.vodID = dictresponse['soap:Envelope']['soap:Body']['InitiateVOAResponse']['VOD_ID'] except: profile.vodID = '' profile.save() lo = {} try: lo_user = User.objects.get(email=request.user.profile.loanOfficer) lo_obj = LoanManager.objects.get(user=lo_user) lo['isChosen'] = True lo['name'] = lo_obj.user.profile.firstName + ' '+lo_obj.user.profile.lastName lo['email'] = request.user.profile.loanOfficer lo['nmlsID'] = lo_obj.nmlsID lo['phone'] = lo_obj.phone except: lo['isChosen'] = False load = False try: preapp = PreApp.objects.filter(username=request.user.username).order_by('-id')[0] load = True except: pass return render_to_response('home/revisedVersion.html', {'user': request.user, 'lo':lo, 'accountcheckURL': accountcheckURL,'load':load}, context_instance=RequestContext(request)) return render_to_response('home/revisedVersionSignup.html', {'user': User.objects.get(email='test9@gmail.com')}, context_instance=RequestContext(request)) revisedVersionSignup has redirect back to this page if user is authenticated and did npt logged out at intermediate steps -
Django widgets - add class to field
I am trying to add class to my inputs in django ModelForm like this: from django import forms from .models import OrderProject class OrderProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderProjectForm, self).__init__(*args, **kwargs) for field in self.fields: if field.widget.__class__ == forms.widgets.TextInput: if 'class' in field.widget.attrs: field.widget.attrs['class'] += 'project-form__input' else: field.widget.attrs.update({'class':'project-form__input'}) class Meta: model = OrderProject fields = ('name', 'customer', 'area', 'status', 'budget', 'opening_date', 'ending_date',) Unfortunately I got error: 'str' object has no attribute 'widget' Any ideas what I am doing wrong ? -
error while importing a channel route
I am trying to build a chat app using django channels .I ran into this error and can't manage to solve it. raise ImproperlyConfigured("Cannot import channel routing %r: %s" % (routing, e)) django.core.exceptions.ImproperlyConfigured: Cannot import channel routing 'flamingo.routing.channel_routing': 'module' object has no attribute 'channel_routing here is my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! >SECRET_KEY = '=ee2q)ew^@d(6v$3+@dt#jm9j@6eck-*+fu#b(v$to1dspe&l-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'flamingo.urls' redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "flamingo.routing.channel_routing", }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'flamingo.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Django social auth with default AUTH_USER_MODEL
I am new in django and want to implement custom django social auth such that pick username and email from social site and create and save AUTH_USER_MODEL like: from django.contrib.auth.models import User random_passward = generate random passward user = User.objects.create_user( username = social.username, email = social.email, password = random_passward) //send random_passward via email send_mail(...) user.save() what will be the exact implementation and where should i place this code? Thanks in advance -
Return data (one latest object) from all the symbols passed as a list to query
I have a query like EquityIntradayData.objects.using('marketdata').filter(symbol__in=symbol_list).order_by('-date_time')[:1] the return response is like: [ { "close": "591.00000", "symbol": "MPSLTD" } ] I am filtering on a list of symbols symbol_list = self.request.GET.getlist('symbol') I want it to return me data (just one latest object by date) per symbol example: if I passed in a list of symbols : ['MPSLTD', 'SANDESH'] I should get [ { "close": "591.00000", "symbol": "MPSLTD" }, { "close": "783.00000", "symbol": "SANDESH" } ] I tried to do distinct and earliest but was hitting a wall. EquityIntradayData.objects.using('marketdata').filter(symbol__in=symbol_list).distinct().earliest('date_time') How can I achieve this ? -
One table can not be foreign key to others except one table
For example class Room(models.Model): visitor = models.ForeignKey(Visitor) number = models.PositiveIntegerField() capacity = models.ForeignKey(Capacity, on_delete=models.PROTECT) floor = models.ForeignKey(Floor, on_delete=models.PROTECT) price = models.PositiveIntegerField() is_premium = models.BooleanField(default=False) is_vip = models.BooleanField(default=False) expiry_date = models.DateTimeField() class Meta: unique_together = ('') def __str__(self): return '№{0}'.format(self.number) class Reserved(models.Model): room = models.ForeignKey(Room) begin_date = models.DateTimeField() def __str__(self): return 'Reserved Room {0}'.format(self.room) class Busy(models.Model): room = models.ForeignKey(Room) Table Room can not be connected to Tables Reserved and Busy at the same time. Room should be reserved or busy. Is there way put validation for this? I tried to use unique_together but if for fields of table Thanks -
Django urls and 404 for every address
I got a new project to work on and I'm stuck. Whichever url I try to give I get 404 response from server and I can't figure out how urls are managed. In project urls root I have something like this: urlpatterns += patterns('', url(r'^$', include(resolver_urls, namespace='resolver')), url(r'^', include(other_urls, namespace='other')), url(r'^accounts/', include('accounts.urls', namespace='accounts')), ) This says AFAIK: "if nothing after slash is passed (for ^ is beginning of a stringand$matches end of it, nothing is expected between), then use urls from resolver_urls, otherwise search further". OK, but inresolver` I have this: urlpatterns = patterns( '', url(r'^.*$', ResolveUrlToRestaurantView.as_view(), name='resolver'), ) Which says "match any count of any character". If I try to connect to say 127.0.0.1:8080/signup which: is in other urls module: urlpatterns = [ (...) url(r'^signup/$', SignUpView.as_view(), name='signup'), (...) ] and is defined in views: class SignUpView(SignUpMixin, APIView): def post(self, request): self.signup_user(request) return Response(status=status.HTTP_200_OK) def get(self, request): return Response(status=status.HTTP_200_OK) and I have it in installed apps setting, I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8080/signup/ Raised by: other.views.api.SignUpView So 2 questions: does this url configuration make any sense? Why do I keep getting 404 for all requests? -
django use timedelta in template
I am new django. I have the following code to get the current time and my filter is to convert the string date to dateformat and convert it to solar calendar. Is there any way to find the date of tomorrow in the template and not in any python file? {% now 'Y-m-d' as value %} <script> var today = "{{ value|dateCustomFilter }}"; // var tomorrow = ? </script> -
How to return objects by popularity that was calculated with django-hitcount
I have itens in my app that I want to be returned by "popularity". This popularity meaning the number of views the item has. I'm using django-hitcount to do this. I saw here how I could get the number of hits of each object. But I don't want to load all my Item objects to memory to accomplish what I want because it's an unnecessary overload. I want to return the N most popular itens to be passed to the view and the access number of each item. My Item model is as bellow class Item(models.Model, HitCountMixin): nome = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, null=True) imagem = models.ImageField(upload_to='itens/item/', null=True, blank=True) descricao = RichTextUploadingField(null=True, blank=True) categoria = models.ForeignKey(Categoria) hit_count_generic = GenericRelation( HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return '{}'.format(self.nome) def get_absolute_url(self): from django.urls import reverse return reverse('itens:detail_item', args=[str(self.slug)]) At first, in my View I was trying to get the most popular itens with this function def get_most_popular_itens(amount): return Item.objects.order_by('-hit_count.hits')[:amount] But it didn't work. I couldn't understand how this contenttype/generic relationship works. So, I saw how the database tables were and managed to do something functional (see bellow). But it has one problem. The queryset returned isn't ordered by the number of views … -
Nested relations in microservices
I have been exploring microservices architecture for some time now, and want to try it in real world app. But I have stumbled across problem and haven't found definitive answer. Imagine we are writing Tutorial app that connects tutors with students. We have user/accounts service that is responsible for governing stuff related to tutors and students. We also have tutorials service that manages everything related to scheduling a tutorial session. In pseudo-Django code it may look like this: user/accounts service entities: class Tutor(models.Model): name = models.CharField() avatar = models.ImageField() class Student(models.Model): dob = models.DateTimeField() name = models.CharField() tutorial service entities: class Tutorial(models.Model): tutor_id = models.IntegerField() # id of Tutor instance student_id = models.IntegerField() # id of Student instance datetime = models.DateTimeField() Now suppose we want to display: all tutorial sessions for given Tutor. It looks straight forward: fire an API request to tutorials service and you're done! But I want to display name and date of birth of each student. How should I handle this case? Two approaches I figured out are: Let tutorial service call user/accounts service and "nest" retrieved Student objects in response in student field of each Tutorial object From frontend app collect all id of students … -
How can I print my form errors in a proper way in Django and Jinga
I am trying to create a login page in Django. Now the page works fine but I can not print the errors in a proper way. For some reason, I am not using {{ form.as_p }} Here is the code <form method="POST" class="fcolumn fcenter login-form"> {% csrf_token %} <h1>LOGIN PANEL</h1><hr><br> <input type="text" placeholder="Username" required name="username"> <input type="password" placeholder="Password" required name="password"> <button type="submit">Login</button> {% if form.errors %} <p>{{ form.errors}}</p> {% else %} <p>New Here, <a href="{% url 'joinus' %}">Create an account</a></p> {% endif %} </form> Now this method printing the error in a ul, but I just want the error text Thanks in advance :) -
Django apache configuration with mod_wsgi module
From the Django documentation: WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com WSGIProcessGroup example.com where does 'python-home' point to ? where does 'python-path' point to ? where does 'example.com' point to ? -
CSV to PDF Convert in django
I want to be able to convert CSV to PDF files and have found several useful scripts but, being new to Python, I have a question: How could I convert CSV to PDF? import csv from fpdf import Template import os from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User as DjangoUser from django.http import HttpResponse def invoice_report(request): response = HttpResponse(content_type='"application/pdf"') response['Content-Disposition'] = 'attachment; filename="users.pdf"' #print response writer = csv.writer(response) writer.writerow( ['Creation Date', 'Bill Number', 'Name', 'Quantity', 'Product/Service Name', "Ref No", "Cost", "discounted Price", "Net Amount", "Costomer Name", "Commission Staff", "Commission Amount", "Patyment Type"]) commision_user = UserCommission.objects.filter(bill_id = bill.id, product_service_id=products_in_bill.product.id).first() name = "-" comm_amount = "-" if commision_user: name = commision_user.staff_user.user.first_name comm_amount = commision_user.commission_amount except: name = "-" comm_amount = "-" print(str(products_in_bill)+" | "+str(products_in_bill.product_qty) + name ) writer.writerow([ bill.creation_date,bill.bill_number,bill.staff.user.first_name+" "+bill.staff.user.last_name, products_in_bill, products_in_bill.product.reference_number, products_in_bill.product.cost, products_in_bill.discounted_price, products_in_bill.product.cost, customer_name, name, comm_amount, payment_type ]) file_name = "" file_name = 'reports/invoice_reports/' + timezone.now().strftime('%Y_%m_%d_%H_%M_%S.pdf') file_path = os.path.join(BASE_DIR, 'static/' + file_name) with open(file_path, 'wb') as f: f.write(response.content) return render(request, 'billing/report/invoices_report.html', { 'invoices':record_for_frontEnd, 'customers': Customers, 'cashiers': cashiers, 'file_name': file_name }) -
[wsgi:error]:No module named mysite.settings
I have deployed Django app in Wamp server which was working fine. Unfortunately after running pip install Wamp server stopped serving Django applicaiton and throwing below error mod_wsgi (pid=26240): Target WSGI script 'D:/testdeployment/mysite/mysite/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=26240): Exception occurred processing WSGI script 'D:/testdeployment/mysite/mysite/wsgi.py'. Traceback (most recent call last): File "D:/testdeployment/mysite/mysite/wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\core\\wsgi.py", line 13, in get_wsgi_application django.setup() File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\\Python27\\Lib\\importlib\\__init__.py", line 37, in import_module __import__(name) ImportError: No module named mysite.settings WSGI.PY import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() Wamp configuration: WSGIScriptAlias / "D:/testdeployment/mysite/mysite/wsgi.py" WSGIPythonPath "D:/testdeployment/mysite/mysite/" <Directory "D:/testdeployment/mysite/mysite/"> Order deny,allow Allow from all Require all granted </Directory> <Directory "D:/testdeployment/mysite/mysite/"> <Files wsgi.py> Require all granted </Files> SSLOptions +StdEnvVars Options Indexes FollowSymLinks MultiViews AllowOverride All Require local </Directory> Please let me know what is the issue here -
Do I need a many-to-many relationship for the leave approver of a company?
I have a: User and Company class User(AbstractBaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.ForeignKey( 'projects.Company', on_delete=models.PROTECT ) class Company(models.Model): '''Company model every user needs to be assigned to a company ''' name = models.CharField(max_length=255, unique=True) Now I need a to set a few leave approvers per company which will be Users. There can be a few and I want to set a priority for them. If it were a single LeaveApprover then I would simply add a one-to-one to the Company model with a foreign key to LeaveApprover. But In my case A company can have many approvers, an approver can only approve a single company. Do I need a many-to-many field? -
Shared image volume mount error in docker
I use docker-compose for running my containers in docker. I have two services - one of celerybeat and other the web (I have many others but considering only these services because they contain my problem). docker-compose.yml file looks like this: . . . celerybeat: image: web-image volumes: - /home/ubuntu/celerybeat:/code/celerybeat command: > /bin/ash -c "su -m celery -c 'celery -A <application_here> beat -s /code/celerybeat/celerybeat-schedule'" web: image: web-image volumes: - /home/ubuntu/celerybeat:/code/celerybeat command: > <some_command_to_run_server> In my Dockerfile I have added these commands for proper permissions RUN mkdir celerybeat RUN touch celerybeat/celerybeat-schedule RUN chown -R celery:celery celerybeat Note: In my compose file structure written above I have provided volume mounts for both containers (but actually I am using one at a time), for the ease of not writing the compose files again and again. The problem is actually here only. Technically the volume mount should be provided only in the celerybeat service. When I write volume mount for celerybeat-schedule in the celerybeat docker service I get permission denied. Whereas when I write the volume mount command in the web service celerybeat service starts happily. What is happening here can anyone explain me? I need a fix for this. -
send_mail works locally but not on production hosting
The following works locally but as I deployed it to production hosting at Digital Ocean, the email is not sending as I test on shell command (python manage.py shell) like below. The send_mail line just got stuck there and am getting error: [Errno 101] Network is unreachable after few minutes. How can I capture the error on the email sending? Please advise how can I troubleshoot this issue. from django.core.mail import send_mail send_mail('test email', 'hello world', 'xxxx@gmail.com', ['xxxx@gmail.com'],fail_silently=False) # Email settings EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'xxxx' #my gmail password EMAIL_HOST_USER = 'xxxx@gmail.com' #my gmail username EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER