Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Internationalization--without gettext
There is a way to make 2 language site by copying the same site, and changing the urls and templates without using gettext and standard internationalization steps. Due to some sorts of errors my mac can't cope with gettext etc. Is there a simple way not to use gettext etc? I am thinking of copying the app and doing 2 sites one for en and one for my language. I would really appreciate it if you have also some videos that show how i can do that. Thank you! -
CreateView + dynamic form display with AJAX
I'm working on a simple django project for expenses management. I got a manage_operations view which is responsible for displaying all Operations and it generates page which looks like this: Clicking on add new operation link results in loading new page with a new Operation form. Below you can find my current code: views.py class OperationCreate(CreateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def get_form_kwargs(self): # some irrelevant kwargs updating ... return kwargs def form_valid(self, form): # some irrelevant operations using values given by user in the form ... return super(OperationCreate, self).form_valid(form) models.py class Operation(models.Model): types_tuples = ((-1, 'expense'), (1, 'earning')) def get_category_color(self): return Category.objects.get(pk=self.category.id).color user = models.ForeignKey(User) account = models.ForeignKey(Account) category = models.ForeignKey(Category) date = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2) type = models.IntegerField(choices=types_tuples) currency = models.CharField(max_length=3) color = property(get_category_color) forms.py class OperationForm(ModelForm): class Meta: model = Operation fields = ['account', 'type', 'category', 'date', 'amount'] def __init__(self, user, *args, **kwargs): super(OperationForm, self).__init__(*args, **kwargs) self.fields['account'].queryset = Account.objects.filter(user=user) self.fields['category'].queryset = Category.objects.filter(user=user) operation_form.html <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save" /> </form> What I'm currently trying to achieve is that new Operation form is being displayed as a bootstrap modal on top of my `manage_operations' … -
OSError: mysql_config not found
I tried installing mysqlclient on python today but it gets all messy and gives me this error raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found then I tried to edit the mysql.config file by adding #Create options libs="-L$pkglibdir" libs="$libs -lmysqlclient -lssl -lcrypto" but still it gives me the same error. I am on mac version 10.6.8. The details of the error are: ****Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "", line 1, in File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/private/var/folders/s4/s4O4m-85EgGDXYYsUzcvNU+++TQ/-Tmp-/pip- build-s7w0agk6/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found**** I will really appreciate any help. -
can't connect to Selenium server from vagrant machine
i built my first web project on a vagrant machine. I would like to run some browser tests with selenium. i have the tests (and rest of project) on virtual machine. it appears that I can use selenium server standalone to connect to my local machine and run the browsers on the local machine. On the local machine, I run the following: java -jar selenium-server-standalone-3.8.1.jar I get a bunch of successful code including: osjs.AbstractConnector:main: Started ServerConnector@709a8be8{HTTP/1.1,[http/1.1]}{0.0.0.0:4444} Presumably, that is where i can connect from my virtual machine. I then have a small python script: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities driver = webdriver.Remote( command_executor='http://0.0.0.0:4444', desired_capabilities=DesiredCapabilities.CHROME) driver.get("http://www.python.org") I get the following error: urllib.error.URLError: <urlopen error [Errno 111] Connection refused> I can't find much more detail on this process than these steps. If someone could help with this problem, I'd be grateful. -
Redis Server In EC2: Elastic Beanstalk, Django, Django Channels
I would love to have a development AWS environment run completely free, but this means that I must confine all my services into one ec2 instance. Currently, my stack consists of a Django web process running on port 80, a Daphne instance running on port 5000 and a redis server running on a different ec2 instance all together on port 6397. I am in the process of moving the aforementioned redis server into the same ec2 that my Django and Daphne processes run on. I had everything working on two separate ec2 instances, however, when I merged the redis server into the same instance, my web socket urls started to return 404 errors. Does anyone know if this is possible to run all services within the same ec2 as I have described? If so, what could I be doing incorrectly based on my configuration below? My only red flag that I see is in the netstat command results below... It appears that there are many different targets for the redis process being that it is listening on a certain IP and established on a different IP. Let me know if there are other logs that you would like to see. … -
Error with command $python3 manage.py migrate
I'm new to Django and I am running Django inside a virtualenv on MacOS with python 3.6. The command $python3 manage.py migrate but I keep getting an error asking me to install mysqlclient. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.20.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class … -
Django Internationalization---compilemessages error:AttributeError: module 'locale' has no attribute 'normalize'
I am just before finishing line and feel that i don't finish yet! I created and compiled all of the messages in order to have a site with 2 languages and i received this error when running the server: AttributeError: module 'locale' has no attribute 'normalize'. Can someone please help me? Traceback (most recent call last): File "/Users/ionutcohen/Dropbox/PycharmProjects/chn/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/ionutcohen/Dropbox/PycharmProjects/chn/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/ionutcohen/Dropbox/PycharmProjects/chn/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 306, in execute parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False) File "/Users/ionutcohen/Dropbox/PycharmProjects/chn/venv/lib/python3.6/site-packages/django/core/management/base.py", line 47, in __init__ super().__init__(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/argparse.py", line 1633, in __init__ self._positionals = add_group(_('positional arguments')) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/gettext.py", line 606, in gettext return dgettext(_current_domain, message) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/gettext.py", line 570, in dgettext codeset=_localecodesets.get(domain)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/gettext.py", line 505, in translation mofiles = find(domain, localedir, languages, all=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/gettext.py", line 477, in find for nelang in _expand_lang(lang): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/gettext.py", line 206, in _expand_lang loc = locale.normalize(loc) AttributeError: module 'locale' has no attribute 'normalize' Process finished with exit code 1 This is how my locale folder looks like: -
Docker Compose - https with Nginx/Gunicorn
I have the following Nginx config and docker-compose.yaml. Before I adding the following block, server { listen 443; server_name localhost; ssl on; ssl_certificate /etc/nginx/conf.d/privkey.pem; ssl_certificate_key /etc/nginx/conf.d/mynginx.key; location / { proxy_pass http://web/; } } everything thru HTTP works fine. After I added the above code block, everything stopped working, I can't access the site thru HTTP/HTTPS. mynginx.conf upstream web { ip_hash; server web:8000; } # portal server { location / { proxy_pass http://web/; } listen 8000; server_name localhost; } # portal (https) server { listen 443; server_name localhost; ssl on; ssl_certificate /etc/nginx/conf.d/privkey.pem; ssl_certificate_key /etc/nginx/conf.d/mynginx.key; location / { proxy_pass http://web/; } } docker-compose.yaml ubuntu@ip-172-31-9-162:~/django_docker$ cat docker-compose.yml version: '2' services: nginx: image: nginx:latest container_name: ng01 ports: - "80:8000" - "443:443" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: dg01 command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn composeexample.wsgi -b 0.0.0.0:8000" depends_on: - db volumes: - ./src:/src expose: - "8000" db: image: postgres:latest container_name: ps01 Folder Structure . ├── config │ ├── nginx │ │ ├── mynginx.conf │ │ ├── mynginx.conf~ │ │ ├── mynginx.crt │ │ ├── mynginx.key │ │ └── privkey.pem │ └── requirements.pip ├── docker-compose.yml ├── docker-compose.yml~ ├── Dockerfile └── src ├── composeexample … -
Insert JSON data into database for python
I'm currently doing a system that scrap data from foursquare. Right now i have scrap the review from the website using python and beautiful soup and have a json file like below {"review": "From sunset too variety food u cant liked it.."}{"review": "Byk motor laju2"}{"review": "Good place to chill"}{"review": "If you wan to play bubble and take photo, here is the best place"}{"review": "Scenic view for weekend getaway... coconut shake not taste as original klebang coconut shake..."}{"review": "Getting dirtier"}{"review": "Weekend getaway!"}{"review": "Good for casual walk & watching sunset with loved ones since my last visit macam2 ade kat sini very packed during public holidays"}{"review": "Afternoon time quite dry..beach is normal. Maybe evening/night might be better. The coconut shake they add vanilla ice cream,hmmm"}{"review": "Pantai awesome beb"}{"review": "Nice place for picnic"}{"review": "Cannot mandi here. Good place for recreation.. Calm place for weekdays! Haha"}{"review": "Very bz place. Need to go there early if you want to lepak. If not, no parking for you"}{"review": "So many good attraction here, worth a visit"}{"review": "Beautiful place for sunset"}{"review": "New beach! Like all beaches, awesome view & windy. Some stretch got many small crabs."}{"review": "There is bustel \"hotel in a bus\" can get coconut shake or … -
Django multitenant: how to customize django setting "ACCOUNT_EMAIL_VERIFICATION" per tenant?
Django==1.11.7 django-tenant-schemas==1.8.0 django-allauth==0.34.0 Multi tenant site using django-tenant-schemas (postgres). On different tenants, different settings are required. More specifically, different setting is required for ACCOUNT_EMAIL_VERIFICATION 1 tenant needs ACCOUNT_EMAIL_VERIFICATION = "optional" while another one needs ACCOUNT_EMAIL_VERIFICATION ="mandatory" Looking in the source code, the setting looks not customisable, it is fixed for the whole django site. -> How can this be done? -
How to access an entire table row based on annotation with Max()
I have a model that stores the cover images for different magazines (publications). In a simplified version it looks like this class Publication(models.Model): name = models.CharField(max_length=100) website = models.CharField(max_length=100) class PublicationIssue(models.Model): publication = models.ForeignKey(Publication, null=False) issue_number = models.IntegerField(null=False) cover_image = models.CharField(max_length=100) In SQL I can execute something like this: select publication_id, max(issue_number) current_issue, cover_image from conditionalsum_publicationissue group by publication_id This looks for the max issue number for a publication and easily gives me the current issue number and the associated cover image. The output looks something like this: publication_id current_issue cover_image 1 12 ae43fb33.jpg 2 26 445fbb45.jpg 3 213 db8489e3.jpg I know I can use rawsql in a Django query, but I wanted to see if there are solutions that avoid this. It's easy enough to get the current issue: PublicationIssue.objects. \ values('publication_id'). \ annotate(current_issue=Max('issue_number')) This returns the publication_id with the current_issue. But this look like a dead end as far as adding the cover_image. Adding 'cover_image' to the values clause does not work and any further annotation will similarly expand the queryset in ways incorrect for my purposes. I have attempted going with a subquery, but that is getting fairly long and complicated for a relatively simple SQL statement. … -
Select related many-to-many field in Django in model
I have the following classes in my model: class Dish(models.Model): name = models.CharField(max_length=200) def get_ingredients(self): return #what to return? class DishIngredient(models.Model): dish = models.ForeignKey(Dish, on_delete=models.PROTECT) ingredient = models.ForeignKey(Ingredient, on_delete=models.PROTECT) number_of_units = models.IntegerField('number of units') class Ingredient(models.Model): name = models.CharField(max_length=100) unit = models.ForeignKey(Unit, on_delete=models.PROTECT) I want Dish.get_ingredients() to return DishIngredient.number_of_units, Ingredient.name, Ingredient.unit Anybody know how to do this? -
Populating a form field in a view
I am working on an imageboard application, which has two views. An index view and a thread view. Views.py def ThreadView(request, thread_id): template = loader.get_template('thread.html') form = MessageForm(request.POST) if request.method == 'POST': #form = MessageForm(initial={'thread': thread_id}) #form.fields['thread'].initial = thread_id if form.is_valid(): form.save() form = MessageForm() else: form = MessageForm() context = { 'message': Thread.objects.get(id=thread_id), 'replies': Message.objects.all().filter(thread=thread_id), 'form':form } return HttpResponse(template.render(context, request)) Models.py class Thread(models.Model): msg = models.TextField(max_length=9001) timestamp = models.DateTimeField(auto_now_add=True) class Message(models.Model): msg = models.TextField(max_length=9001) timestamp = models.DateTimeField(auto_now_add=True) thread = models.ForeignKey('Thread', on_delete=models.CASCADE) Forms.py class ThreadForm(forms.ModelForm): class Meta: model = Thread fields = [ 'msg' ] class MessageForm(forms.ModelForm): class Meta: model = Message fields = [ 'msg' ] The problem is this: Message model has a foreign key to Thread model, and when I am posting to a certain thread, I need to prepopulate the "thread"-field in Message model with thread_id in views.py (because a message has to belong to a certain thread). The two lines that I have commented out are my attempts of passing the field value to a form, both unsuccessful. Is this even possible in function-based views? (Python 3, Django 2.0) I'm sorry if I missed something, I'm really tired of coding all day. Feel free to … -
Django, Validation Error not showing up in template
I was creating a form to register users, I added the validation error to check if the email already exists in the database. However, when you feed in an email which is already in the database, the form doesn't show up the error, it just resets. forms.py: class SignUpForm(UserCreationForm): institute = forms.CharField(max_length=255) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) # Making name required self.fields['email'].required = True self.fields['first_name'].required = True self.fields['last_name'].required = True class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'institute' ) def clean_email(self): email = self.cleaned_data.get('email') try: match = User.objects.get(email=email) except User.DoesNotExist: return email raise forms.ValidationError("Cannot use this email. It's already registered") return email And this is my views.py: def register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.profile.institute = form.cleaned_data.get('institute') print(user.profile.institute) user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return render(request,'home.html') form = SignUpForm() context = { 'form' : form, } return render(request,'register.html', context) I am using crispy forms -
Django Comments: How to update page based on model instance returned by successful post?
When a user posts a new comment, I want to display that comment immediately on the page with information derived from the new comment model instance. (For example, including a live 'favorite' button that requires the instance id) I know that when Django Comments successfully posts content to the {% comment_form_target %} url it performs the comment_was_posted signal. How do I capture this signal so that the I can insert html featuring information from this model instance into the page? If I was doing this with ajax, I would pass the model instance or its pk back as part of the success message. But I don't know how to do this with the django comments library. -
How to write a custom template for paginated data in Django Rest Framework?
With Django Rest Framework, I'm trying to write a custom template for paginated list of snippets. I understand that list function in my view must return paginated response. So I get the page first and send the paginated response. However how can I specify the template name? get_paginated_response does not have template_name argument. Code: def list(self, request): page = self.paginate_queryset(self.queryset) if page is not None: serializer = self.get_serializer(page, data=request.data) serializer.is_valid() # fct has no template_name argument! return self.get_paginated_response(serializer.data) -
Django: No Such Table
I'm running into an error while trying to extend my user model. I have a model created that takes in some more fields that I would like to be attached to the user as seen here: accounts/models.py class Customer(models.Model): US_STATES_OR_CAN_PROVINCES = ( ('AK', 'Alaska'), ('AL', 'Alabama'), ('AR', 'Arkansas'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DC', 'District of Columbia'), ('DE', 'Delaware'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('IA', 'Iowa'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('MA', 'Massachusetts'), ('MD', 'Maryland'), ('ME', 'Maine'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MO', 'Missouri'), ('MP', 'Northern Mariana Islands'), ('MS', 'Mississippi'), ('MT', 'Montana'), ('NA', 'National'), ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('NE', 'Nebraska'), ('NH', 'New Hampshire'), ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NV', 'Nevada'), ('NY', 'New York'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'), ('PR', 'Puerto Rico'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'), ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VA', 'Virginia'), ('VI', 'Virgin Islands'), ('VT', 'Vermont'), ('WA', 'Washington'), ('WI', 'Wisconsin'), ('WV', 'West Virginia'), ('WY', 'Wyoming'), ('AB', 'Alberta'), ('BC','British Columbia'), ('MB', 'Manitoba'), ('NB', 'New Brunswick'), ('NL', 'Newfoundland and Labrador'), ('NT', 'Northwest Territories'), ('NS', 'Nova Scotia'), ('NU', 'Nunavut'), ('ON', 'Ontario'), ('PE', 'Prince Edward Island'), … -
Using PK2 in a context where pk2 is not available
I am having an issue I am not sure how to solve. I have a two page one which is a user list with a "detail" link that lead to the user detail view. In that user detail view I make some calculation in my views using the pk2 of the user in the url in the form http://127.0.0.1:8000/website/project/applicant/57/44 where pk1= 57 is the current project and pk2 = 44 which represent the user. Now in my list view I would like to show that score that was calculate in the detail page. my html look like this : <table class="table table-hover"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Survey Date</th> <th>Score</th> <th>Team Score</th> <th>Details</th> </tr> </thead> <tbody> {% for i in app_with_resp %} <tr> <td>{{i.first_name}}</td> <td>{{i.last_name}}</td> <td>17/06/86</td> <td>{{applicant_score}}</td> <td>{{team_score}}</td> <td> <a href="{% url 'website:CandidateDetails' pk1=current_project_id pk2=i.id %}"> Details</a></td> </tr> {% endfor %} </tbody> </table> my view is the following: class RecruitmentPage(generic.ListView): #import pdb; pdb.set_trace() model = Project template_name = "recruitment_index.html" def get_object(self, queryset=None): return get_object_or_404(Project, id=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(RecruitmentPage, self).get_context_data(**kwargs) current_project_id = self.kwargs['pk1'] applicant_list = Project.objects.get(id = current_project_id).applicant.all() team_score = get_team_cohesivenss_score(self)[0] # applicant_score =get_applicant_cohesivenss_score(self)[0][0] # diff_score = get_applicant_cohesivenss_score(self)[0][0] - get_team_cohesivenss_score(self)[0] app_with_resp = [] app_without_resp = [] for … -
Override form widget and/or Form for ManyToMany TabularInline
Suppose I had two models as follows (example from Django Docs) from django.db import models class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, related_name='groups') And the following admin panel: from django.contrib import admin class MembershipInline(admin.TabularInline): model = Group.members.through class PersonAdmin(admin.ModelAdmin): inlines = [ MembershipInline, ] class GroupAdmin(admin.ModelAdmin): inlines = [ MembershipInline, ] exclude = ('members',) Now, suppose that my database built up over the years, and I have lots and lots of Persons, but very little Groups. So for Groups, I can use the default widget, but I need a custom widget for Person inside GroupAdmin. My question is, inside MembershipInline, how do I modify it so that the Person's widget is overridden? I know this is possible with django-autocomplete-light for ForeignKey admin.TabularInlines, but how do I modify this to come up with something for ManyToMany admin.TabularInlines? In other words, how do I modify the form going one way but not the other? -
Get server URL in django docker
I am running Django project in docker. I have 3 docker container. For Django App For Postgres For Nginx My docker-compose.yml file is as follow version: "3" services: db: restart: always container_name: tts-db image: postgres:9.6 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=tts expose: - "5432" nginx: image: nginx:latest container_name: tts-nginx ports: - "8000:8000" volumes: - ./nginx/site-enabled:/etc/nginx/conf.d depends_on: - web web: build: . container_name: tts-app environment: - DATABASE=db - DEBUG=False - STATICFILES_STORAGE=whitenoise.storage.CompressedManifestStaticFilesStorage depends_on: - db expose: - "8888" entrypoint: ./entry_point.sh command: gunicorn urdu_tts.wsgi:application -w 2 -b :8888 restart: always In my django app, I need to access host address. I used request.get_host() which works in localhost. When I run this in Docker, I get url like http://web/media/voice/voice.wav. My nginx configuration is as follow. upstream web { ip_hash; server web:8888; } server { location ^/static/ { autoindex on; alias /static/; } location ~ ^/media/?(.*)$ { try_files /media/$1 /mediafiles/$1 =404; } location / { proxy_pass http://web; client_max_body_size 20m; } listen 8000; server_name localhost; } How can I get server url in Docker? -
django website is giving 404 error for static files
Having problem with staticfiles in Django 2. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, "templates") STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR + '/static/' STATICFILES_DIR = [ (BASE_DIR + "static/"), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] And my static structure is like below I am getting 404 for statics. Tried different things but no success. btw collectstatic has been already performed. Another thing is when i make changes in the static folder, collectstatic is not collecting anything. it says "unmodified". i am newbie in Django. appreciate for your help. -
django 2.0 file(view) changes does not effect in frontend
In my django 2.0 application, when I change something in view, it does not effect in frontend even closing the server by ctrl+c or ctrl+z. I am using windows. It works when I manually close python process from task manager. It's not good process to code and restarting server each time in development. If I have a simple HttpResponse of string like return HttpResponse('test') and changes the string(test) to any thing, it does not show the updated string, instead it shows test. How to overcome this, any idea will be appreciated. Thanks -
Testing Uploaded File Django
I m working on an Upload file example in Django. The user uploads a file, and I need to run a test on that file (compiling..) and launch a python script using that file. But I don't knw how to keep track of the uploaded file to use it. Here is my views.py from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponseRedirect from django.urls import reverse from myproject.myapp.models import Document from myproject.myapp.forms import DocumentForm def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() # A empty, unbound form # Load documents for the list page documents = Document.objects.all() # Render list page with the documents and the form return render( request, 'list.html', {'documents': documents, 'form': form} ) -
fp.write writes extra newlines to file
So I have a form in Django, where user inputs some text. Then I write this text to a file. My views.py looks something like this: if request.method == "POST": code = request.POST.get('code', False) fp = open('mp/somefile.txt', 'w') fp.write(code) fp.close() However this causes extra newline characters. (I am using windows) for example aaaaaaaa bbbbbbbb cccccccc results in aaaaaaaa bbbbbbbb cccccccc Is there a way to prevent these extra newline characters? -
Django - forloop.counter numbers not resetting when using nested for loops
I have a need for counting the standings of a sport team based on the total points they have their division. Each team has a total points and division assigned to them. My django template code is as follows: {% for division in divisions %} <h4>{{ division }}</h4> <table class="table"> <tr> <td align="center">Place</td> <td>Team</td> <td align="center">Points</td> </tr> {% for stat in stats %} {% if stat.division == division %} <tr> <td width="10%" align="center">{{ forloop.counter}}</td> <td width="70%">{{ stat.team }}</td> <td width="20%" align="center">{{ stat.points }}</td> </tr> {% endif %} {% endfor %} </table> {% endfor %} The problem right now is that say i have 6 teams and 3 are in Division A and 3 are in Division B. Because it is separating the teams based on division it is showing the forloop.counter as 1 through 6 on the first forloop for divisions. What I want it to do is only do the forloop counter for the nested forloop ( the second one for stats ) so that it shows places 1 through 3 for Division A and 1 through 3 for Division B. The results I am getting are: Division A Place Team Points 1 Timberlea Beverage Room 1 7 3 …