Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot add ManyToManyField objects in Django
I am unable to add ManyToManyField objects in Django 1.11 on Python 3.6 even after following the doc models.py class Label(models.Model): ... name = models.CharField(blank=False, max_length=100) class Template(models.Model): ... labels = models.ManyToManyField(Label, blank=True, related_name="labels") And then >>> from content.models import Label, Template >>> l1 = Label.objects.get_or_create(name='one') # saves in db >>> l2 = Label.objects.get_or_create(name='two') # saves in db >>> t1 = Template.objects.get(pk=1) # loads existing >>> t1.labels.set([l1,l2]) # fails throws this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1007, in set self.add(*new_objs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add self._add_items(self.source_field_name, self.target_field_name, *objs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items '%s__in' % target_field_name: new_ids, File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1276, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/path/env3tt/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1206, in build_filter condition = lookup_class(lhs, value) File "/path/env3tt/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__ self.rhs = self.get_prep_lookup() File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp> self.rhs = [target_field.get_prep_value(v) for v in self.rhs] File "/path/env3tt/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value return int(value) TypeError: … -
How to validate and provide cleaned_data for a dynamically introduced field in forms.modelform?
I would like to make it clear. I am aware inlineformset would solve this however for another purpose I was wondering how this would be done. Here are some models.py class Address(models.Model): address_0 = models.CharField("address", max_length=64) address_1 = models.CharField("address cont'd", max_length=64, blank=True) city = models.CharField("city", max_length=64) state = USStateField() # django_localflavor_us.models zip_code = USZipCodeField() # django_localflavor_us.models class ContactInfo(models.Model): name = models.CharField(max_length=50) address = models.ForeignKey(Address, null=True, blank=True) phone = models.CharField(max_length=50, blank=True) This is my modelviews.py class AddressModelForm(forms.ModelForm): class Meta: model = Address fields = '__all__' class ContactInfoModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContactInfoModelForm, self).__init__(*args, **kwargs) for k, v in AddressModelForm.base_fields.items(): self.fields['address_{}'.format(k)] = v class Meta: model = ContactInfo exclude = ('address', ) I have tried playing around with is_valid and clean, but I can never seem to get it accept the new fields. I am unsure which method to validate it myself and get a cleaned_data version of the new input. Which I believe it is because address is missing, but I am trying to replace address with an Address form myself. -
How do I deploy Django app to (AWS) domain name?
I've only been working with Django for a few weeks, and just learned deployment. I have an AWS EC2 Instance, which I'm able to deploy my Django website/app to (i.e., if I go to the IP address in my browser, I'm able to access my website). However, I can't figure out how to deploy that same website to my domain name, which is registered on AWS. I followed AWS's documentation (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-ec2-instance.html), and https://cachecheck.opendns.com/ shows that my domain name routes to my EC2 instance. However, when I go to my domain name in my browser, it shows a 400 Bad Request. Is there something else I need to do when I setup nginx or gunicorn? I've tried replacing the {{yourEC2.public.ip}} in the nginx code to be my domain name instead of the IP address. I haven't been able to find any other resources online regarding deployment to domain names, specifically with AWS. :/ If anyone has any advice, I'd really appreciate it! This is what I have for deploying to the EC2 instance: settings.py DEBUG = False ALLOWED_HOSTS = ['{{yourEC2.public.ip}}'] STATIC_ROOT = os.path.join(BASE_DIR, "static/") (venv) ubuntu@54.162.31.253:~myRepoName$ python manage.py collectstatic gunicorn [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/{{repoName}} ExecStart=/home/ubuntu/{{repoName}}/venv/bin/gunicorn --workers 3 … -
Cloning ec2 linux instance on aws in local environment
I have a production server running on aws ec2 instance. Since, I was beginner when I started everything I hadn't use virtual env etc. Now, there are many dependencies and packages that I have installed somehow. Now is there a way to clone entire aws ec2 instance environment with all the packages into my local machine for dev work. I know from pip freeze I can get all the python dependencies (I have a running django server). But is there a way to clone everything (from docker etc.). -
How does transaction work? does it lock resources?
I thought transaction.atomic make the block either commit as a whole and roll all back to original. It seems transaction.atomic doesn't lock tables( or objects). I wonder if it doesn't lock all these referenced resources, how does it roll back? -
Variable not found. Declare it as envvar or define a default value
I am very new to Django and trying to configure python-decouple to use .env variables. I am getting DB_PASSWORD not found. Declare it as envvar or define a default value. when trying to run the server. The .env file is located in the root directory. Here is my code: settings.py import os from decouple import config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_development', 'USER': "db_user", 'PASSWORD': config('DB_PASSWORD'), } } my_app.env DB_PASSWORD=my_password -
Add User related objects in User model in Django Admin
I'm working on a Django 1.10 project, in which I have a model called Tagged article which is related to a user with the related_name as "tagging", now I want to display a table of TaggedArticle objects when we open a user object in Django admin.How can I achieve that functionality in Django Admin? Here's my models: TaggedArticle: class TaggedArticle(models.Model): user = models.ForeignKey(User, related_name='tagging') email = models.EmailField(max_length=255) category_fit = models.CharField(choices=choices, max_length=255) article = models.ForeignKey(Article, related_name='articles') link = models.URLField(max_length=255,) relevant_feedback = models.TextField(blank=True) category = models.CharField(max_length=255,) created_at = models.DateTimeField(default=timezone.now, editable=False) Help me, please! Thanks in Advance! -
What is selected_choice in views.py in dango Tutorials?
In django Tutorial polls/views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from .models import Choice, Question # ... def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice=question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I couldn't find a brief explanation how selected_choice,selected_choice.vote works ? please explain me in novice terms . Thank you for your time and effort !! -
def __str__(self) return doesnt work - python 3.6/ Django 1.11.6
The following is my code in the models.py file: from django.db import models # Create your models here. class RestaurantLocation(models.Model): name = models.CharField(max_length=120) location = models.CharField(max_length=120, null=True, blank=True) category = models.CharField(max_length=120, null=True, blank=True) def __str__(self): return self.name Instead of returning the restaurant name, it returns "RestaurantLocation object" in the output window of the admin section. Where am I going wrong? -
Possible to use WhiteNoise with Django-Compressor?
I'm new with Django, and I'm trying to automate and optimize my deployment for production. At this moment I use WhiteNoise to handle static files, but as far as I know he just handle and compress the static files. Recently I found out about this tool: https://github.com/django-compressor/django-compressor , but I don't know if it really worth it to drop WhiteNoise in order to use this Django-Compressor, since I've never heard of it and every guide recommends to use WhiteNoise for safety and stability reasons. It's possible to use both in the same project? If yes, how? If not, worth changing it to use in a PaaS like Heroku? -
group by SKU using date range filter in Django Admin
I have the following model: from django.db import models class KPIReport(models.Model): Date = models.DateField() ASIN = models.CharField(null=True,blank=True,max_length=200) ItemSKU = models.CharField(max_length=200,blank=True,null=True,default='sku') Account = models.CharField('ACCT',null=True,blank=True,max_length=200) Country = models.CharField('MKT',null=True,blank=True,max_length=200) Sessions = models.IntegerField('SESS',blank=True,null=True) Session_Pct = models.DecimalField('SESS %',max_digits=8,null=True,blank=True, decimal_places=2) Page_Views = models.IntegerField('P.VIEWS',blank=True,null=True) Page_Views_Pct = models.DecimalField('P.VIEWS %',max_digits=8,null=True,blank=True, decimal_places=2) Buy_Box_Pct = models.DecimalField('B.B. %',max_digits=8,null=True,blank=True, decimal_places=2) Units_Ordered = models.IntegerField('UNITS ORD',blank=True,null=True) Units_Ordered_B2B = models.IntegerField('U.O. B2B',blank=True,null=True) Unit_Session_Pct = models.DecimalField('U.SESS %',max_digits=8,null=True,blank=True, decimal_places=2) Ordered_Product_Sales = models.DecimalField('ORD SALES', max_digits=8,null=True,blank=True, decimal_places=2) Ordere_Product_Sales_B2B = models.DecimalField(max_digits=8,null=True,blank=True, decimal_places=2) Total_Order_Items = models.IntegerField('TOTAL',blank=True,null=True) Total_Order_Items_B2B = models.IntegerField('T. ITEM B2B',blank=True,null=True) BSR = models.IntegerField(blank=True,null=True) Actual_Sales = models.IntegerField('SALES',blank=True,null=True) Selling_Price = models.DecimalField('PRICE', max_digits=8,null=True,blank=True, decimal_places=2) Notes= models.CharField(max_length=200,null=True, blank=True) class Meta: ordering = ['-Date','-Country','Account','BSR','ItemSKU',] verbose_name_plural = "-KPI REPORT" def __str__(self): return self.ItemSKU I am using a date range filter and it is working as expected. I use this model manager to get filtered results excluding objects without Sessions (sessions=None) class CAN_Manager(models.Manager): def get_queryset(self): return super(CAN_Manager, self).get_queryset().filter(Country='CAN').exclude(Sessions=None) class KPI_CAN(KPIReport): objects = CAN_Manager() class Meta: verbose_name_plural = "Marketplace: Canada" proxy = True Is there a way to use the rangeFilter, or, make a custom range filter that would -sum the values that are aggregate (sessions, totals) -average the values that are not aggregates (average %) -and display the values that are the same (SKU, account, etc) Here is my … -
Two forms one view: model variable loses value
Here's my code @login_required def upload(request): form_type = '' transcript = Transcript() transcript.file_path = '' if request.method == 'POST': if 'file_form' in request.POST: file_form = FileForm(request.POST, request.FILES) if file_form.is_valid(): path = handle_uploaded_file(request.FILES['file'], request.user) transcript.file_path = path transcript.user = request.user export_form = InfoForm() form_type = 'info_form' elif 'info_form' in request.POST: if transcript.file_path: info_form = InfoForm(request.POST) if info_form.is_valid(): transcript.user = request.user transcript.title = info_form.cleaned_data.get('title') transcript.instructions = info_form.cleaned_data.get('instructions') transcript.save() return HttpResponseRedirect('thanks') else: raise ValueError('Transcript object has no file path attribute') else: export_form = FileForm() form_type = 'file_form' return render(request, 'transcription/upload.html', {'form': export_form, 'form_type': form_type}) always, the file-form is called before the info-form, so the code in the if statement if transcript.file_path: #... should always execute. But the ValueError always gets raised, meaning transcript.file_path is reset. How does this happen, and how can it be fixed? def handle_uploaded_file(file, user): id = randint(0, 10000) user_dir = settings.MEDIA_ROOT + '/' + str(user.id).replace(".", "") + '/' path = user_dir + file.name.replace(".mp3", str(id) + ".mp3") if not os.path.exists(user_dir): os.makedirs(user_dir) with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) file = File(destination) info = {'path': path, 'file': file} return path -
Django - manytomany relation between User.Profile and another model, ValueError: Cannot add
user/models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Bread(models.Model): title = models.CharField(max_length=40) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) picture = models.ImageField(upload_to="photos/", default="photos/none/default.png") bread = models.ManyToManyField(Bread) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I trying to add a simple object to Profile model, but it does not work. >>> from user.models import Bread >>> from user.models import Profile >>> from django.contrib.auth.models import User >>> p1 = Bread(title="Example") >>> p1.save() >>> Profile(User).bread.add(p1) ValueError: Cannot add "<Bread: Example>": instance is on database "None", value is on database "default" >>> u1 = Profile(User) >>> u1.save() TypeError: _prepare() takes 1 positional argument but 2 were given Seeing similar previous questions I tried to save profile model, as u can see, I know its related with User and his id, but i have no idea how to fix it easily -
django.urls.exceptions.NoReverseMatch Class Based List Views
I am attempting to set up a website on cookeicutter, I created a new app called "bots" and added a class called Trade and Unit within models. I created two class based views inside of views.py; detail and list view. The trade detail view works fine and directs to the correct trade, but when I attempt to visit the html page that references the trade list view, the page returns the following error. django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'trade-detail' with arguments '('1',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I believe something is wrong with the get_absolute_url, because when i remove it from the model.py the list error above goes away and the page renders, but then the links don't work. Most of my code is from this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views Models.py from django.db import models from datetime import date from django.urls import reverse from django.urls import reverse_lazy from django.conf import settings import uuid class Unit(models.Model): TRADE_UNIT = ( ('ETH', 'Ethereum'), ('BTC', 'Bitcoin'), ('LTC', 'Litecoin'), ('IOT', 'IOTA'), ('OMG', 'OmiseGo'), ('BCH', 'BitcoinCash'), ) sell = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='ETH', help_text='Currency to Sell') buy = models.CharField(max_length=3, choices=TRADE_UNIT, blank=True, default='BTC', help_text='Currency to Buy') def get_absolute_url(self): """ Returns the url to access a … -
Django Allauth migration error
I've run across this issue before and I think I had to go into the library installed by pip to manually delete the migrations to fix it. Does anyone have a better idea? ./manage.py makemigrations Traceback (most recent call last): File "./manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 95, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 268, in build_graph raise exc File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/loader.py", line 238, in build_graph self.graph.validate_consistency() File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 261, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 261, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/Users/josh/.pyenv/versions/one_raft_first_site/lib/python3.5/site-packages/django/db/migrations/graph.py", line 104, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration socialaccount.0001_initial dependencies reference nonexistent parent node ('sites', '0001_initial') -
Django: Search Function If No Initial Data
def search(request): query = request.GET.get('q') .... .... return render(request, 'search.html', {'list': list}) form looks like this, <form method="get" action="{% url 'new:search' %}"> <input type="text" name="q" value="{{ request.GET.q }}"> <input type="submit" value="Search" /> </form> Everything is working fine here but if a user simply press the "Search" button it shows all data instead of doing nothing. So, how can I make this search function do nothing when user directly press the Search button without entering initial data? -
Values get corrupted in template tag
I am developing an app which enables me to show multiple markers when I click on the markers it should show me an image along with some details. My current code is : google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent( contentString = '<div id="content">'+ '<p>'+ 'sensor image:' +'<br/>' + '<img src="{% static "test/imgs/sen1.jpg" %}">'+ + '<br/>' + 'sensor light level :' + j[i][4] +'<br/>' + 'sensor battery level :' + j[i][5] + '</p>'+ '</div>' ); infowindow.open(map, marker); } })(marker, i)); and I get the desired output: !https://imgur.com/a/Q1lPU I have an array, j which contains name of the image I want to load, previously i hardcoded the url '<img src="{% static "test/imgs/sen1.jpg" %}">'+ I tried to make this dynamic by using '<img src="{% static "test/imgs/'+ j[i][3] +'.jpg" %}">'+ But i got an error , on using F12 it appears GET localhost:8000/static/test/imgs/'%2B%20j%5Bi%5D%5B3%5D%20%2B'.jpg 404 (Not Found) a lot of garbage was generated instead of the value sen1. I am not able to understand why this is happening and would like some help. -
Format Django QuerySet output with arrays
I have data in a table that look like this: src_id, dst_id, params int , int , array I'm querying the data to extract some values from the array with the following Django query dataset = query_set.values_list('src_id', 'dst_id', *[e.field for e in settings]) I need to output the data like this: [ [1,2,[a,b,c,d], [3,4,[a,c,d,e], ... ] but the values_list returns a list of tuples like (1,2,a,b,c,d)(3,4,a,c,d,e)... So I've been doing: [[d[0], d[1], d[2:]] for d in dataset] It works fine, but I have 1M+ rows, and it is slow. It is also using a lot of memory. Is there a way to optimize this code? I looked at using a loop, or lambda but that doesn't make much of a difference. I looked at using array but it only takes primitive types, so no much luck with array of arrays. I am looking for a way to query the DB and output the data directly in the right format, if possible in Django, otherwise I'd have to use raw SQL. Any hint on how to format output of a query? is it possible, or just too esoteric for Django? Thanks -
Integrate multiple dictionaries in django
Really having trouble about list these days, I'm a developer from php looking a place in python. My question is in relation to my previous question I now have a dictionary group by id_position and flag that contains order [Top, Right, Bottom, Left, Center]: A = {41: [0, 0, 0, 0, 1], 42: [0, 0, 1, 0, 1], 43: [0, 0, 0, 0, 1], 44: [0, 0, 0, 0, 1]} and other dictionary that contains my id_position and status: B = {'44': 'statusC', '42': 'statusB', '41': 'statusA', '43': 'statusC'} I want to include dict A in my code to save dict B below. for pos, stat in B.items(): MyModel.objects.create(position=pos, status=stat, Top = "" , Right="" Bottom = "", Left= "") How can I make this wok? Can you recommend study list where I can start to work from php to django. -
Modifying Oscar on an pre-existing non-oscar app
I had an app without oscar, I then installed oscar. I updated my main app settings with the credentials of oscar's. When I go to my admin page, I am able to see the products pages and such. I can add the products BUT I see nothing on main page What I did so far, pip install django-oscar, created a new app django-admin startproject myshop, modified settings.py in my main app per the directions in oscar's. I pointed my urls.py to myshop. urls.py from oscar.app import application admin.autodiscover() urlpatterns = i18n_patterns( url(r'^partner/', include(application.urls)), ... Now I'm expecting myshop to be integrated to oscar. I went to my website.com/myshop I see my default template. I go to website.com/myshop/dashboard same template, no oscar. -
compressor aws compressor error
I installed a module and it installed dependencies. (I seriously am not enjoying these dependencies) anyways, looking around to solve this. Did what people posted. my error: s3link isn't accessible via COMPRESS_URL cloudfrontlink also tried AWS_S3_CUSTOM_DOMAIN =https://xxx.cloudfront.net settings.py STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' COMPRESS_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_HOST = 'https://xxxxxxxxx.cloudfront.net' if not DEBUG else '' STATIC_URL = STATIC_HOST + '/static/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') # STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "app/static"), ) STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, "solid/static"), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'compressor.finders.CompressorFinder' ) COMPRESS_ROOT = STATIC_ROOT COMPRESS_ENABLED = True COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ] COMPRESS_PARSER = 'compressor.parser.HtmlParser' COMPRESS_URL = 'https://xxxx.cloudfront.net/static/' -
Facing issues to provide download link to shared files in django application
I am developing file sharing app using Django. I have 3 models to store 1: User information 2: Information about there uploaded files 3: Information about file shared with them by another user model number 2 and 3 are, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) def get_absolute_url(self): return '/img/%s' % self.Browse.name user_list = (User.objects.all()) class share_files(models.Model): select_file = models.CharField(max_length=300) from_user = models.CharField(max_length=50) select_user = models.CharField(max_length=50,default=None) I have written below function in view for sharing of file, def user_share(request): user_data=User.objects.all() file_data = user_files.objects.filter(user_uploaded=request.user) select_user=request.POST.get('dropdown1') select_file=request.POST.get('dropdown2') if request.method=="POST": user_form = Share_file(request.POST) data=share_files(select_user=select_user,select_file=select_file) data.save() return redirect('share') else: user_form=Share_file() return render(request, 'accounts/share.html',{'user_form':user_form, 'user_data':user_data, 'file_data':file_data}) and the form for it is, class Share_file(forms.ModelForm): class Meta: model = share_files fields = ('select_file', 'select_user') I am displaying shared files in template , from model share_files but i also want to provide download option for that file. How can i achieve that? Thanks in advance. -
Django multi host url configuration per app
I searched around here on SO for how I would setup different domains for apps within a single django project. e.g.: news.io, jobs.io, etc for a news, job, etc app within the main project. The app will also have authentication where the user will need to remain signed in across the domains if this matters. e.g. - billing platforms, etc. The recommendation was to use a MultiHostMiddleware found here which is obviously outdated. Similarly, the other recommendation was to use django-multihost which is also really old. I'm on Django 1.11 and Python 3.6. Is there anything more recent or better yet how would I roll my own? -
Where are stack-traces for my Django / uWSGI vassal logged?
I am running my Django site as a vassal of UWSGI emperor. I have created /etc/uwsgi-emperor/vassals/mysite.ini as follows: [uwsgi] socket = /var/opt/mysite/uwsgi.sock chmod-socket = 775 chdir = /opt/mysite master = true virtualenv = /opt/mysite_virtualenv env = DJANGO_SETTINGS_MODULE=mysite.settings module = mysite.wsgi:application uid = www-data gid = www-data processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/log/uwsgi/app/mysite.log vacuum = true But the only logs I get are things like this: [pid: 2887|app: 0|req: 7/7] 1.2.3.4 () {52 vars in 936 bytes} [Fri Oct 13 20:46:04 2017] POST /mysite/login/ => generated 27 bytes in 2453 msecs (HTTP/1.1 500) 4 headers in 126 bytes (2 switches on core 0) [pid: 2887|app: 0|req: 8/8] 1.2.3.4 () {44 vars in 702 bytes} [Fri Oct 13 20:52:24 2017] GET / => generated 1561 bytes in 2 msecs (HTTP/1.1 200) 4 headers in 124 bytes (2 switches on core 0) Where's the stack-trace for the 500 error? (Is there a module I need to enable?) -
Django render json response with html elements
I'm learning ajax. for example I want to fetch some items. As the json only contains dict-like data, I have to render them as complicated html elements. I'm thinking about where to do the render job. If done in frontend, using javascript to render such complicated html element will be painful. So I thought it will be better to leverage Django template. And What I need is to render it using html template, and put the whole html elements into a string in json, and return the json. So my frontend will easy fetch the rendered element like data['element'] and append it to my page. But I don't know how to do this in Django, ususally I render a html page and return it directly. But how can it render the html elements and put it into json? Or is there better way to do this?