Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
From django.core.mail EmailMessage Goes into infinite loop
I have a simple ahref link in my Django Project : <a class=" btn btn-md" href="/someurl/{{ some_id }}/">Notify User</a> And on clicking it,the requested URL is : url(r'^someurl/(?P<some_id>\w+)/$', login_required(some_view), name='some_view'), And the requested view is : def some_view(request,some_id): schObj = SomeModel.objects.get(id = some_id) user = schObj.user usermail = user.email name = user.fname + " " + user.lname template = get_template('../templates/email_templates/success_mail.html') c = Context({}) c.update({'some_id':some_id,'address':user.address}) c.update({"fullname":name}) html = template.render(c) subject = "Successfull." email = EmailMessage(subject, html, to=[usermail],from_email='some_mail@gmail.com') email.content_subtype = "html" email.send() return HttpResponseRedirect(request.path) My Problem is,After clicking the button,email is getting repeatedly sent to the user.And this goes into infinite loop.How to solve this problem?? -
intial formset from database
I have a project and a person model. the relation between is many_to_many. I want to select all people who are not participated in some projects (like project 1 and 3 and4). I do not know how to make this query set, so I will try to do it in manually. At first step I have select the projects. I create a form for with checkboxes class ProjectListForm(forms.Form): proj = forms.CheckboxInput() Now I can make a formset. each form is belong to one project. I want inject project data to formset. and set checkbox label to project titile and id. How can I do that? -
save() missing 1 required positional argument: 'request' in django
I create a model: class Person(models.Model): name = models.CharField(max_length=250) slug = AutoSlugField(populate_from='name') birth_date = models.DateField(null=True, blank=True) blood_group = models.CharField(max_length=5) present_address = models.CharField(max_length=250, blank=True) permanent_address = models.CharField(max_length=250, blank=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='member_persons') forms.py: class MemberForm(ModelForm): class Meta: model = Person exclude = ('user',) def save(self, request, commit=True): person = super().save(commit=False) if not person.pk: person.user = get_user(request) if commit: person.save() self.save_m2m() return person It worked fine for first person create. When same person again try to submit create form with different data it gives 'save() missing 1 required positional argument: 'request''. Full traceback: Traceback: File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/ohid/test_venv/lib/python3.5/site-packages/django/views/generic/edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) … -
How can I raise an error in my Django form?
I have a PHP script in a server that returns {"available":true} or {"available":false}, depending on whether the email address is available or not. Here is the code: <?php $servername = "localhost"; $username = "root"; $password = "mysqlpass"; $dbname = "testdb"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT username FROM testtable"; $result = $conn->query($sql); $query = $_GET['query'].'@groupdesignace.com'; $arr = array(); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $arr[] = $row['username']; } if (in_array($query, $arr)) { $output = array('available' => false); echo json_encode($output); } else { $output = array('available' => true); echo json_encode($output); } } else { echo "0 results"; } $conn->close(); ?> On a different server where users are requesting their email address through a form, I am using Django. I have written the following code to check whether the email is available, if not, it should raise an error. Here is the code: class RequestEmailAddressForm(forms.Form): email = forms.CharField(label='Email', max_length=100) password = forms.CharField(widget=forms.PasswordInput) def clean_email(self): email = self.cleaned_data.get('email') if email: import requests payload = {'query': email} r = requests.get('http://172.16.16.172/check_email.php', params=payload) result = r.json() print r.url … -
Comparing an empty string and an integer (Python 2)
I am having trouble getting the else statement to run when comparing an empty string and an integer. I am using Python 2.7 DATA 1: {"name":"Item 1", "pk":14} DATA 2: {"name":"Item 2", "pk":""} I want the ELSE statatement to run for DATA 2. In english, if it gets a PK value of an empty string, it should run the else. I tried: if info_data.get('pk', 0) > 0: Here is my full code: def update(self, instance, validated_data): infos_data = validated_data.pop('info') for info_data in infos_data: if info_data.get('pk', None): info = Info.objects.get(pk=info_data['pk']) info.text = info_data['text'] info.save() else: info = Info.objects.create(text=info_data['text'],typeinfo=info_data['typeinfo']) instance.info.add(info) return instance NB: Using python 2.7 -
Field related to field of related object Django
How can i make field related to field of related model. I have two models: album and photo, album model have boolean field private. How to create field private in photo, which will have False value if album field equal to None and value of album private field if it's not. models.py: from django.db import models from django.contrib.auth.models import User import os import uuid def get_image_path(instance, filename): return '{}.{}'.format(uuid.uuid4(), filename.split('.')[-1]) class Album(models.Model): user = models.ForeignKey(User, related_name='albums', on_delete=models.CASCADE) title = models.CharField(max_length=80, default='New album') creation_date = models.DateField(auto_now_add=True) private = models.BooleanField(default=False) def __str__(self): return self.title class Meta: ordering = ['-creation_date', ] class Photo(models.Model): user = models.ForeignKey(User, related_name='photos', on_delete=models.CASCADE) album = models.ForeignKey(Album, related_name='photos', on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=80, default='New photo') image = models.ImageField(title, upload_to=get_image_path) creation_date = models.DateField(auto_now_add=True) # ??? private = models.BooleanField() # ??? def __str__(self): return self.title class Meta: ordering = ['-creation_date', ] -
Is it possible to put volume label in the dockerfile?
I am working with nginx, gunicorn, django, angular And I have to split the static files into volume and share it with django container to let it do collectstatic Question1: I want to share /usr/src/app/static to the other container. By this how do I know the label my volume? I have read official doc from https://docs.docker.com/engine/reference/builder/ and https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume It does not mention anything about label in dockerfile Question2: I heard term "dangling" volume. Will I get one from this? dockerfile: FROM node:latest # Create app directory RUN mkdir -p /usr/src/app VOLUME /usr/src/app WORKDIR /usr/src/app # Bundle app source RUN mkdir -p config COPY ./config/ ./config/ # Install app dependencies under static directory COPY ./package.json ./static WORKDIR /usr/src/app/config/static RUN npm install --progress false WORKDIR /usr/src/app COPY ./dockerfiles/frontend-entrypoint.sh . # set the script to be executable RUN chmod +x frontend-entrypoint.sh yml: frontend: build: context: . dockerfile: dockerfiles/frontend_dockerfile restart: "no" command: ["sh", "./frontend-entrypoint.sh"] shellscript: #!/bin/bash echo "build" npm run build echo "watch" npm run watch -
Django Rest framework with Many to Many framework with a intermediate model
Iam not sure how to serialize data for following models, for expected JSON file. Here are my models: class CheckModel(models.Model): check_name = models.CharField(max_length=1024,unique=True) RulesToWaivers = models.ManyToManyField('RulesToWaivers',blank=True,default='default') class RulesToWaivers(models.Model): rule = models.ManyToManyField('Rule',blank=True ) waiver = models.ManyToManyField('Waiver',blank=True) deliverables = models.ManyToManyField('Deliverables',blank=True) class Waiver(CommonInfo): desc = models.TextField(blank=True) class Rule(models.Model): rule_description = models.CharField(max_length=512,blank=True) class Deliverables(CommonInfo): name = models.CharField(max_length=1024,blank=True) And following are my serializers class CheckModelSerializer(serializers.ModelSerializer): rulewaiver=RuleWaiverSerializer(read_only=True,many=True) class Meta: model= CheckModel fields = ('check_name','rulewaiver') class RuleSerializer(serializers.ModelSerializer): class Meta: model=Rule fields=('id','rule_description') class WaiverSerializer(serializers.ModelSerializer): class Meta: model=Waiver fields=('id','desc') class DeliverbalesSerializer(serializers.ModelSerializer): class Meta: model=Deliverables fields=('id','name') I want to serialize data in my following format { "p0_checks" : [ { "check_id": "400", "rules" : [ { "rule_id" : "21_22", "description": "checks blah blah", "deliverables" : ["del1"], "waivers": [ { "description" : "I will waive everything" }, { "description" : "I will waive all warnings" } ] }, { "rule_id" : "15217", "description": "checks blah blah" "req_ids" : ["lef"], "waivers": [ { "description" : "I will waive everything" }, { "description" : "I will waive all warnings" } ] } ] }, Iam not sure how to get this json from serializers, Any suggestions? -
Django Many To Many table created as a foreign key
How to make the foreign key of a certain model to be the ids of the created table of objects with a ManyToManyField. Please check the data_type attribute on the Transaction model I actually did the through attribute. However it gave me this error when I try to migrate: ValueError: Cannot alter field provider.Provider.data_types into provider.Provider.data_types - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) My code is: class Provider(models.Model): name = models.CharField(max_length=75) code = models.CharField(max_length=15) data_types = models.ManyToManyField('DataType', blank=True, through='ProviderDataType') class DataType(models.Model): name = models.CharField(max_length=75, null=True, blank=True) code = models.CharField(max_length=15) class ProviderDataType(models.Model): provider = models.ForeignKey('Provider') data_type = models.ForeignKey('DataType') -
The TabularInline has no add button after I upgrade to Django 1.10
It used to have a "Add Another" button, now it disappeared, I tried the superuser, so it's not a permission issue. I also tried to switch to StackedInline, no use as well. Right now, as a workaround, I can only specify the extra attribute in the class to a certain number I want. Can't find any useful info on google, anyone experienced the same? I'm using django 1.10.3 and python3.5.2 -
django admin app obscured when urls.py refers to any other app
this seems to be a misunderstanding on my part of how the urls config works in django. I thought that the first regex that matches is where it gets 'dispatched', but if I have others in the urls list, it goes to them instead of the first. The contents of project's urls.py when the admin site is accessible: from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^api/', include('api.urls')), #url(r'^index', include('limbo.urls')), #url(r'^polls/', include('polls.urls')), # url(r'^limbo/', include('limbo.urls')), #url(r'edit/', include('limbo.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) but when I un-comment the 1st, 2nd or last comment-out lines, I get an error: invalid literal for int() with base 10: '' any thoughts? for example, if I un-comment the line that says url(r'^api/', include('api.urls')),, I get the error I stated. api/urls.py contents: from django.conf import settings from django.conf.urls import url from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^(?:addUse\.?[html]{,4})?$', views.addUsageHistory, name='addUsageHistory'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and the In the traceback, I can see it seems to originate with this file: /home/ec2-user/limbo/limboenv/local/lib/python2.7/site-packages/django/contrib/admin/templates/admin/login.html and a ways down the stacktrace (second from bottom), i can see that in /home/ec2-user/limbo/limboenv/local/lib/python2.7/site-packages/django/utils/regex_helper.py, the variable pattern is … -
Django Many To Many table created as a foreign key
How to make the foreign key of a certain model to be the ids of the created table of objects with a ManyToManyField. Please check the data_type attribute on the Transaction model My code is: class Provider(models.Model): name = models.CharField(max_length=75) code = models.CharField(max_length=15) data_types = models.ManyToManyField('DataType', blank=True) def __unicode__(self): return self.name class DataType(models.Model): name = models.CharField(max_length=75, null=True, blank=True) code = models.CharField(max_length=15) class Transaction(models.Model): data_type = models.ForeignKey('????') # I want the foreign key of this one to be the ids of the automatically created many to many table of both DataType and Provider via ManyToManyField data = JSONField() timestamp = models.DateTimeField(auto_now_add=True) file_name = models.CharField(max_length=100, null=True, blank=True) Let us say I the table created in my database is: ----------------------------------- | id | provider_id | data_type_id | | 65 | 5 | 15 | ----------------------------------- I want that 65 to be the supposed to be ForeignKey but I do not know how -
starting django project advice
Background: I have an idea for a side project that I can best describe as a combination between expedia.com/kayak.com and wikipedia. The main website would use APIs, web scraping/screen scraping, or other technologies to populate search results generated from external sources. I would also create a community (like wikipedia) where users could edit content inside the search result ( I apologize if I'm being too vague) Problem: I have limited experience in python and Django and I feel watch youtube tutorial is not benefiting me. Could anyone offer some advice on projects I can work on or tutorials I can watch so that I can build confidence to work on this project of mine. Thank you in advance -
How to model two relationships, and enforce that the pair is unique
I have a DRF model like so: class Party(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(unique=True, blank=False, null=False) And two and only two parties can form an integration, which I currently have modeled like this: class Integration(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) party_a = models.ForeignKey('Party') party_b = models.ForeignKey('Party') class Meta: managed = True unique_together = (('party_a', 'party_b'), ('party_b', 'party_a')) The pair of party_a and party_b has to be unique; which party is which doesn't matter. So, Party 123 and Party 456 can only be integrated once. The unique_together doesn't help me out much here, so I setup a validator to do that. class IntegrationSerializer(serializers.HyperlinkedModelSerializer): party_a = serializers.PrimaryKeyRelatedField(queryset=Party.objects.all()) party_b = serializers.PrimaryKeyRelatedField(queryset=Party.objects.all()) class Meta: model = Integration fields = ('id', 'party_a', 'party_b', 'enabled', 'active_date') def validate(self, data): if len(Integration.objects.filter(party_a=data['party_a'], party_b=data['party_b'])) > 0 or \ len(Integration.objects.filter(party_a=data['party_b'], party_b=data['party_a'])) > 0: raise serializers.ValidationError('Integration already exists') return data I'm wondering if this is the best way to model this relationship? My current solution seems to work okay, but as I test, I keep finding things I need to fix. Like I forgot the validator would trigger on a PUT. Any suggestions are appreciated... -
create plugin from polls aplication
I installed app Polls from with pip install -e git+http://git@github.com/divio/django-polls.git#egg=pollsfrom. Application is saved /me/env/src/polls/ . I run server from /me/project/. I get an error Poll Plugin cant be imported. How can i define that Polls app use own models. Now i want to create plugin and placeholder in my template. cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from polls.models import PollPlugin as PollPluginModel from django.utils.translation import ugettext as _ class PollPlugin(CMSPluginBase): model = PollPluginModel # <--not sure what to put here. name = _("Poll Plugin") # Name of the plugin render_template = "polls/plugin.html" # def render(self, context, instance, placeholder): context.update({'instance':instance}) return context plugin_pool.register_plugin(PollPlugin) # register the plugin polls/models.py class Poll(models.Model): question = models.CharField(max_length=200) def __unicode__(self): # Python 3: def __str__(self): return self.question class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __unicode__(self): # Python 3: def __str__(self): return self.choice_text -
Why does the signal not trigger?
Sitting over a day on it. Really can't understand why this signal is not triggered when a user is activated, no error log, no exception in the admin on activation. Can anybody help? The following code should result in a log message in the apache error.log when a user, right? import logging from registration.signals import user_activated @receiver(user_activated) def registered_callback(sender, **kwargs): logger = logging.getLogger("user-activated") logger.error("activated here") same with user_registered -
How can I add a second form to my Django Project?
I am new about Django , Python and in general web programming. I have a maybe a stupid problem but I am here trying to fix it from a week ago. I have a Django project about food , I want two forms, first one is register a user(membresia or usuario) this works fine. and the other one is register a restaurant. My Django version is 1.10 models.py from django.db import models from django.utils import timezone # Create your models here. class Membresia(models.Model): nombre = models.CharField(max_length=100) cedula = models.CharField(max_length=100) celular = models.CharField(max_length=100) email = models.CharField(max_length=100) ciudad = models.CharField(max_length=100) direccion = models.CharField(max_length=100) creado_en = models.DateTimeField( default=timezone.now) class Restaurante(models.Model): nombre = models.CharField(max_length=100) nombre_responsable = models.CharField(max_length=100) direccion = models.CharField(max_length=100) celular = models.CharField(max_length=100) ciudad = models.CharField(max_length=100) email = models.CharField(max_length=100) creado_en = models.DateTimeField( default=timezone.now) forms.py from django import forms from .models import Membresia, Restaurante class membresiaform(forms.ModelForm): class Meta: model = Membresia fields = ('nombre', 'cedula','celular','email','ciudad','direccion') widgets = { 'nombre': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Tu nombre'}), 'cedula': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Tu número cédula'}), 'celular': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Tu número celular'}), 'email': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Tu correo electrónico'}), 'ciudad': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Ciudad donde vives'}), 'direccion': forms.TextInput(attrs={'class': 'form-control','placeholder': 'Tu dirección'}), } class restauranteform(forms.ModelForm): class Meta: model = Restaurante fields = ('nombre','nombre_responsable','direccion','celular','ciudad','email') widgets = … -
can a file be downloaded from django development server
I am developing a simple website, where users can input some data through a form and by using the data some work will be done which will generate some image and text files in a folder in server. Now, during the submission of the form the user will be provided with a job id and the resulting folder path would be annotated with the same id. In a search box user will be able to download their results by id. The problem is, how to provide those resulting files to the user to download? I have used the following code in my html to make the download link: {% extends "personal/header.html" %} {% block content %} <h4>Here is the result for you</h4> <h4>Last name: {{ resultRow.last_name }}</h4> <hr> <h4>path: {{ complementRow.path_for_folder }}</h4> <a href='C:\Users\path\to\heatmap.png' download="img">Heatmap</a> {% endblock %} By doing this, the download link appears in the page of django development server but clicking the link does not download the file and shows "Failed: Network error". So, the question is, is the error because of development server or am I doing something wrong? Note: I will use "complementRow.path_for_folder" for specifying the file. Here I have used an instantiation of the … -
Customize the prefix of all tables Django creates, including the sessions table for django.contrib.session
How can I universally change all of the table prefixes for a Django application, including tables for built-in models, like for Sessions? I'm familiar with the Model-specific Meta.db_table method, but I'm looking to also set custom prefixes for tables created by built-in models, like django.contrib.sessions.models.Session. This old question seemed like a good option, but as Suor pointed out, it no longer works post Django 1.7 (we're on 1.10). It seems django_sessions is hard-coded in django.contrib.sessions.models.session.Meta.database_name, but it's unclear how this could be overidden later Attempts to do the obvious as in the above SO question, give an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is there a new way to accomplish the same thing, or a universal way to set / add table prefixes? Thanks -
Distinct changes in a QuerySet By Day/Month/Year ignoring Hour and Minutes
I need to get the diferent unique changes made in a same day, the data_time_change is a DateTimeField(). The majority of changes will occur in the same hour minute and second but not all, so my code below doesn't work the way I want: qnt = len(Report.objects.all().distinct('date_time_change') It counts 02/11/2016 10:00:00 and 02/11/2016 10:00:01 as two changes and I want it to count as the same One change. So I tried to do: qnt = len(Report.objects.all().distinct('date_time_change__day').distinct('date_time_change__month').distinct('date_time__year') And I throw the error: Cannot resolve keyword 'day' into field. Join on 'date_time_change' not permitted. -
Package's namespace polluted by Django?
Django 1.8 For no obvious reasons, global variable defined in package's module is replaced between its initial assignment and deferred function call. Minimal Django project is created with django-admin startproject. New empty application added with django-admin startapp simplelib. New app simplelib added to INSTALLED_APPS of project's settings.py. Bellow is the only added code: # content of myproject.simplelib.__init__.py from django.db import models from django.db.models.signals import class_prepared def myhandler(sender, **kwargs): print 'models from myhandler: {}'.format(models) def direct_call(): print 'models from direct_call: {}'.format(models) class_prepared.connect(myhandler) print 'models from top namespace: {}'.format(models) direct_call() When project is run with manage.py runserver, following output is produced: models from top namespace: <module 'django.db.models' from '/home/<snip>/Projects/Python/django-projects/lib/python2.7/site-packages/django/db/models/__init__.pyc'> models from direct_all: <module 'django.db.models' from '/home/<snip>/Projects/Python/django-projects/lib/python2.7/site-packages/django/db/models/__init__.pyc'> models from myhandler: <module 'simplelib.models' from '/home/<snip>/Projects/Python/django-projects/myproject/simplelib/models.pyc'> ^^^^^^^^^^^^^^^^ See, when signal handler function is invoked, modules global variable is changed. There is no other project's code. It has to be altered by Django itself. Note: above described effect applies only when simplelib is placed at the start of INSTALLED_APPS tuple. When added at the end, models still points to django.db.models, as expected. Any idea what's going here ? -
Django Redux Registration Incorrect Password / Username when it is correct
I created an application and am using Django Redux Registration to handle authentication and creation of users, but I am not able to login unless it is a super user I created through the console. When I click "Register" again with the same username is says the name is already taken, but cannot login despite the password being correct. I can still login with superusers but nothing else. Settings.py """ Django settings for yoloq project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p(n=h+*3#9&c)qyyaa^fz3d0(w&hkzqr9p!k9y8@uld*0bz1is' # 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.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'SearchGame', 'registration', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'yoloq.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': … -
Creating superuser in a docker container for a django app
So I am trying to create a superuser for my django app in the docker container. I enter the container as follow docker exec -it <container name> /bin/bash I get to the folder where the manage.py file is and I use python manage.py createsuperuser. I create the superuser and I try logging,however, after a decent amount of waiting I get 504 Gateway timeout. I checked the nginx logs and I found the following error: [error] 10#10: *12 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 192.168.99.1, server: 192.168.99.100, request: "POST /admin/login/?next=/admin/ HTTP/1.1", upstream: "http://192.168.99.100:8000/admin/login/?next=/admin/", host: "192.168.99.100", referrer: "https://192.168.99.100/admin/login/?next=/admin/". My nginx.conf file looks like this: upstream django { server 192.168.99.100:8000; # for a web port socket } server { listen 80 default_server; listen 443 ssl; server_name 192.168.99.100; # substitute your machine's IP address or FQDN add_header Strict-Transport-Security "max-age=31536000"; charset utf-8; ssl on; ssl_certificate /path/to/certificate.crt; ssl_certificate_key /path/to/key.key; client_max_body_size 75M; # adjust to taste access_log /var/log/nginx/lb_access.log; error_log /var/log/nginx/lb_error.log; location /media { alias /path/to/media; # your Django project's media files - amend as required } location /static { alias /path/to/static; # your Django project's static files - amend as required } location / { proxy_set_header X-Proxy-Forw-Proto $scheme; proxy_pass … -
Configuring Django static folder for python anywhere
I am new in Django, previously I had a test site in which my static files were placed in static folders. There was a static folder for every app. But now I want to make a site, which will be deployed to python anywhere and so I have to have only one static folder. This is the project folder: https://github.com/martin-varbanov96/fmi-fall-2016/tree/master/django/click_bait/miranda You can see that in the settings file I have: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") in my target html file I have <link rel="stylesheet" href="{% static 'home/css/style.css' %}" type="text/css"> which returns 404. What is wrong how should I arrage my folders so that they are best working for the pythonanywhere host? -
Pass context data from generic.DetailView
How can i pass the context data which is coming from a forms.py to my views class which is using generic detailView, i need to pass forms.py to my product detail page. Here is the code for my view class class ProductView(generic.DetailView): model = Product cart_product_form = CartAddProductForm() context = {'cart_product_form': cart_product_form} template_name = 'shopping/product.html' query_pk_and_slug = True Please let me know if this is incorrect