Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django import code from other apps
I have a project whith multiple apps. So when I want some code from another app I use from app.pyfile import * or from app.pyfile import specific_function To be more specific: I have an app called 'commonapp' where I have some common stuff that I use in all the other apps. In this app I have a common.py file where I have some functions, including a function called my_response(request,template,context) ,which is the one causes a NameError. Now this particular function is always being called inside other functions. for example: from commonapp.common import * def myInfo(request): context = {} data = '' data = SomeModel.objects.all() template = 'path/to/info.html' context['data'] = data a = my_response(request,template,context) return a This raises a NameError "global name my_response is not defined" I know what a NameError is, but why here? I would expect an ImportError if something could not be imported or even "global name a is not defined" . What am I missing here? -
How to upload pdf file on CMS django?
I did upload in django on admin side. How to change the path for saving pdf?For example uploads/files. It is loaded to project folder. When I open the pdf in cms it gives me Page not found (404). How to open it? The main goal is to upload pdf from cms and download from web-side. models.py class PostLecture(models.Model): title = models.CharField(max_length = 200) pdf = models.FileField() time = models.DateTimeField(auto_now_add = True) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class Meta: ordering = ['-time'] admin.py class PostLectureAdmin(admin.ModelAdmin): list_display = ('title', ) admin.site.register(PostLecture, PostLectureAdmin) -
forms - Django error - matching query does not exist
I'm getting DoesNotExist at /home/contact/ GameDetails matching query does not exist. as per my knowledge, there is no relation between this form and GameDetail model. sometimes form starts working and sometimes it shows this error. forms.py from django import forms from django.forms import ModelForm from home.models import GymkhanaFormModel class GymkhanaForm(forms.ModelForm): class Meta: model = GymkhanaFormModel fields = ['name', 'roll_no', 'year', 'email', 'events', 'message'] views.py def GymkhanaFormCreate(request): if request.method == 'POST': # to pull last filled details form = GymkhanaForm(request.POST) # cleaned form after submit # form = GymkhanaForm() if form.is_valid(): form.save() form = GymkhanaForm() else: form = GymkhanaForm() data = {'form': form} return render(request, 'home/eventform.html', data) def gamer(request, page_name): all_games = GameDetails.objects.all() game = GameDetails.objects.get(game_title=page_name) all_posts = GameDetails.objects.get(game_title=page_name).postholders_set.all() sam = 'home/' + page_name + '.html' context = {'all_posts': all_posts, 'game': game, 'all_games': all_games} return render(request, sam, context) Models.py class GymkhanaFormModel(models.Model): name = models.CharField(max_length=20) roll_no = models.IntegerField() year = models.CharField(max_length=6) email = models.EmailField(max_length=20) events = models.CharField(max_length=20) message = models.TextField(max_length=100) def __str__(self): return self.name urls.py url(r'^contact/$', views.GymkhanaFormCreate, name='GymkhanaFormCreate'), -
Django 1.11 - Validate ListSerializer
I am using a serializer to validate data inputs with is_valid() method, But in case of getting many objects I am using MySerializer(data, many=True) When calling my serializer with many=True I am getting ListSerializer Object. How can I use that object to validate (as is_valid() does) the list of data objects. Thank you ! -
How to implement the official django polls example equivalently by using forms?
The offical django polls tutorial is simple, but it has to handle the POST exceptions manually, as well as hardcode the front-end. How to make the same outcome by using forms? @csrf_protect def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) if request.method == 'GET': return render(request, 'polls/detail.html', { 'question': p, }) if request.method == 'POST': try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) #urls.py url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), #models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text # polls/templates/polls/detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> I want to ease the process by doing: if form.is_valid(): ... votes += 1 and {{ form … -
do not show salaries in the table - django permissions
I've had a table in which different expenses are displaying which are bills, rents, salaries, etc, and I want to hide salaries from my staff, so I'm adding new filter to my queryset which needs to restrict that to them, but when I test it with different users, it is still there, I'm not entirely shure why is this happening, so can someone please explain me what am I doing wrong here. This is my custom permission: @staticmethod def can_view_salaries(user): return user.is_staff and user.has_perm('cms_expenses.can_view_salaries') You can see my restapi views in which I'm doing the filtering. class ExpenseViewSet(viewsets.ModelViewSet): def get_queryset(self): only_recurrent = self.request.query_params.get('recurrent', False) queryset = models.Expense.objects.get_expenses_list(self.request.user) if only_recurrent: queryset = queryset.exclude(scheduled_recurrence__isnull=True) if self.check_object_permissions(self.request.user, queryset): queryset = ExpenseAccessService.can_view_salaries(self.request.user) return queryset serializer_class = ExpenseSerializer filter_backends = ( filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter ) filter_fields = ('paid', 'generated',) ordering_fields = ( 'value', 'currency', 'category', 'attachment', 'created', 'scheduled_recurrence', 'paid', 'scheduled_recurrence__interval', 'scheduled_recurrence__next_occurrence', 'payment_proof', 'description') search_fields = ( 'value', 'currency', 'category', 'attachment', 'created', 'paid', 'scheduled_recurrence__interval', 'scheduled_recurrence__next_occurrence', 'payment_proof', 'description') pagination_class = StandardResultsOffsetPagination permission_classes = [ permissions.IsAuthenticated, expenses_permissions.ExpensesPermissions ] -
Django password_change view raising NoReverseMatch exception
app_name = "myadmin" urlpatterns = [ url(r'^change-password/$', auth_views.password_change, { 'template_name': 'myadmin/password_change', 'current_app': 'myadmin', }, name='password_reset' ), url(r'^password-change-done/$', auth_views.password_change_done, {'current_app': 'myadmin'}, name='password_change_done' ), ] When I visit 127.0.01:8001/myadmin/change-password it raises the follow error: NoReverseMatch at /cadmin/change-password/ Reverse for 'password_change_done' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] As you can see I am already passing app_name to password_change() view but It is not reaching inside the view. Here are Local vars at the point of raising exception. -
AWS credentials : unable to locate credentials in django python
I have configured credentials using aws configure. aws configure list looks fine.Python/django is able to locate the credentials in the shell_plus but unable to locate credentials when django is being run through gunicorn / supervisor. This is weired -
how to get chart's data and labels
I would like to represent my data in a form of a chart, but i am having a problem making the right queries to display the chart's labels and series , and basically i have a Book model , and a User model and i want to display the number of books(series) that belongs to a particular user(labels) . models.by class Book(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) template_tag @register.simple_tag() def chart_data(): users = books = return json.dumps({ 'labels':[user.username for user in users], 'series':[[book.name for book in books]] }) -
Ajax Request to Django Application
I am trying to submit a form by using jquery post method. Every time the form is submitted, the request parameters (request.POST) is empty. I am not sure why the ajax request is failing to send the parameters. The js code: <script> $('#myform').on('submit', function(e){ let username = $("#username").val(); let password = $("#password").val(); let url = $('#myform').attr('action'); $.post(url, { username:username, password:password }, function(d){ alert('success'); }); }); $('#login').click(function(e){ e.preventDefault(); $('#myform').submit(); }); What am I doing wrong in this step? If needed, I can most the html form and, the view function dealing with the form's action url. -
how to make distinct in django orm extra?
I want to select distint from this query, to show the "month" cekbulan = Transaksi.objects.filter(tanggal__range=["2016-07-01", "2017-06-30"], unit='03').extra( select={'month': "month(date)"}).distinct() it is my template <table> {% for bulanmaxs in cekbulan %} <tr> <td>{{ bulanmaxs.month }}</td> </tr> {% endfor %} </table> but it didn't work to distinct value, it still list all date from my database, how to resolve it? -
how to split a dataframe to form a multiple dataframe in a single context in django python
How can i split by big dataframe into smaller dataframe and able to print all the dataframe separately on web? any idea on edit code can place a loop in context? here is my code: def read_raw_data(request): Wb = pd.read_excel(r"LookAhead.xlsm", sheetname="Step") Step1 = Wb.replace(np.nan, '', regex=True) drop_column = Step1_Result.drop(['facility','volume','indicator_product'], 1) uniquevaluesproduct = np.unique(drop_column[['Product']].values) total_count=drop_column['Product'].nunique() row_array=[] for name, group in drop_column.groupby('Product') group=group.values.tolist() row_array.append(group) i=1 temp=row_array[0] while i<total_count: newb = temp + row_array[i] temp=newb i = i + 1 b = ['indicator', 'Product'] test=pd.DataFrame.from_records(temp, columns=b) table = test.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render() context = { "result": table} return render(request, 'result.html', context) -
TypeError: get_context_data() argument after ** must be a mapping, not tuple
I created the list in the view's get_context_data method: def get_context_data(self, *kwargs): """Add list of customer ids to the context""" context = super(PerceptionIndexView, self).get_context_data(**kwargs) customer_ids = [] # Since this is a ListView, I believe you can change the loop to # 'for item in context['object_list']:', and remove the perc queryset perc = Perception.objects.all() for item in perc: customer_id = item.loan.reqest.customer_id if customer_id not in perc: customer_ids.append(customer_id) context['customer_ids'] = customer_ids return context Then in my template, I loop through the list <ul> {% for customer_id in customer_ids %} <li>customer_id</li> {% endfor %} </ul> From there, I got the error TypeError: get_context_data() argument after ** must be a mapping, not tuple. How could I fix that? -
Django. Accessing Model.objects
class SeoBasic(models.Model): slug = models.SlugField(verbose_name='URL', blank=True, null=True) ... def save(self, *args, **kwargs): duplicate = SeoBasic.objects.filter(slug=self.slug).exclude(pk=self.pk).count() > 0 if duplicate: #update slug to be unique super(SeoBasic, self).save(*args, **kwargs) class ModelA(SeoBasic): pass class ModelB(SeoBasic): pass Is it possible to update save method of SeoBasic, so that ModelA and ModelB will search for duplicates only in they own class? Sure i can add save() method into ModelA and ModelB. But is there any way to write code in the parent class without modifying code in child classes? -
Joining 2 tables with count in Django
I have activity and comments for users stored in separate models: class Activity(models.Model): user_id = models.CharField(max_length=50, primary_key=True) activity_id = models.CharField(max_length=5) activity_completed_time = models.DateTimeField() group = models.CharField(max_length=70, primary_key=True) class Comment(models.Model): id = models.IntegerField(primary_key=True) author_id = models.CharField(max_length=50) group = models.CharField(max_length=70, primary_key=True) I need to form a queryset that returns the following with some conditions: Columns: user_id/author_id COUNT(Activity.activity_id) COUNT(Comment.id) The two separate queries with conditions that return the necessary data are: Activity.objects.values('user_id') .filter(group='value') .filter(activity_completed_time__isnull = false) .annotate(**{'total_completed': Count('activity_id')}) Comment.objects.values('author_id') .filter(group='value') .annotate(**{'total_comments': Count('id')}) I need to join them where Activity.user_id = Comment.author_id and show both counts. Thanks for helping point me in the right direction. -
Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox
I have researched and read quite a few Stackoverflow posts on the same issue. None have resolved my issue. My problem is that I am getting the "...No 'Access-Control-Allow-Origin' header is present on the requested resource..." error in my console. I am using: Chrome Version 57.0.2987.133 Firefox Version 52.0.2 Python 2.7 Django 1.11a1 AngularJS I am using MAMP to serve my front-end Angular stuff, and the django server for the backend stuff. In my django settings I have included the cors middleware and tried both the whitelist approach and just setting all to true: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True On google chrome I still get this error: localhost/:1 XMLHttpRequest cannot load {my endpoint url}. Redirect from {my endpoint url} to {my endpoint url with a } has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin {requesting url} is therefore not allowed access. It works appropriately on Firefox, and I can't figure out why it won't work for google chrome. I haven't tried any other types of browsers. Any help will be very appreciated, thank you. -
Django ModelForm with Foreignkey and Manytomany relations
I'm quite new to Django and currently on my first own website project, which I am really stuck on. I'd really appreciate some input or simply a little nudge in the right direction. I am trying to create a Database entry (PostgreSQL if it matters) from a ModelForm which contains one models.ForeignKey and 2 models.ManyToManyField, but the ForeignKey and ManytoManyFields wont work as i want them to. I've tried several different combinations of using Model.objects.get_or_create() and Model.objects.all(). Whenever i Post something to any of the ForeignKey or ManytoMany fields i get a ValueError; for instance Cannot assign "'SBGOÖ'": "Member.regional_group" must be a "RegionalGroup" instance. Maybe the way i handle the choices doesn't work, and i need to initialise my database with placeholder values? But i didn't really find any Documentation on that. I can't figure out what's wrong with my approach. models.py from django.db import models class RegionalGroup(models.Model): REGIONAL_GROUP_CHOICES = ( ('GRAZ', 'RG Graz'), ('SBGOÖ', 'RG Salzburg/Oberösterreich'), ('WIEN', 'RG Wien'), ('TIROL', 'RG Innsbruck'), ('LEOBEN', 'RG Leoben') ) name = models.CharField(choices=REGIONAL_GROUP_CHOICES, max_length=10, default='WIEN') class FocusGroup(models.Model): FOCUS_GROUP_CHOICES = ( ('IT', 'AG IT'), ('FR', 'AG Fundraising'), ('PR', 'AG PR') ) name = models.CharField(choices=FOCUS_GROUP_CHOICES, max_length=10, default='IT') class ProjectGroup(models.Model): PROJECT_GROUP_CHOICES = ( ('TT', 'PG Tailoring … -
Django - display informations from different models into the same HTML template
I am using Django with a MySQL database So I know that that 1 view in views.py is associated to 1 HTML template and that I cannot associate 2 different views to the same template. I tried to create a view "about" containing some stats about my database. Unfortunately it doesn't work. Here is what I've done so far for my view "about": from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import Pdb, StructSec def about(request): namelist = ['Quentin LETOURNEUR', 'Yoann PAGEAUD'] pdbcount = Pdb.objects.count() structcount = StructSec.objects.count() context = { 'namelist': namelist 'pdbcount': pdbcount 'structcount': structcount } return render(request, 'pdbapp/about.html', context) And here is the Error returned in my terminal: Unhandled exception in thread started by <function wrapper at 0x7f25cf87a9b0> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = … -
Can the 'webagg' backend for matplotlib work with my django site?
I've searched a lot on this topic but I'm not a web developer so I know I'm missing some concepts. When I run matplotlib locally and specify the 'webagg' backend, running plt.show() starts a lightweight webserver and opens the plot in my browser with full interactive functionality. import matplotlib as mpl mpl.use('webagg') from matplotlib import pyplot as plt import numpy as np f,ax = plt.subplots(1) ydata = np.random.randint(0,100,100) xdata = np.linspace(1,100,100) ax.plot(xdata,ydata,picker=5) ax.set_title('Click the line to change the color') def onpick(event): event.artist.set_color('red') f.canvas.draw_idle() f.canvas.mpl_connect('pick_event', onpick) plt.show() My question is: Is it possible to use the webagg backend with my django website to serve neat interactive matplotlib figures to users? In other words, can I use the above code somewhere in my django site such that the plot will embed in a web page? (I know about tools like mpld3, which are very cool, but don't fully recreate the widget/picker functionality in matplotlib). -
SuspiciousFileOperation: The joined path is located outside of the base path component
I have 2 ways to upload an image, one via files (image) and one via url (imageURL). If the user chooses url, I have a model method to download the file from the url: class Post(models.Model): ... image = models.FileField(null=True, blank=True) imageURL = models.URLField(null=True, blank=True) def download_file_from_url(self): print('DOWNLOAD') #prints # Stream the image from the url try: request = requests.get(self, stream=True) except requests.exceptions.RequestException as e: # TODO: log error here return None if request.status_code != requests.codes.ok: # TODO: log error here return None # Create a temporary file lf = tempfile.NamedTemporaryFile() # Read the streamed image in sections for block in request.iter_content(1024 * 8): # If no more file then stop if not block: break # Write image block to temporary file lf.write(block) return files.File(lf) views def post(request): ... if form_post.is_valid(): instance = form_post.save(commit=False) if instance.imageURL: instance.image = Post.download_file_from_url(instance.imageURL) instance.save() Uploading an image from file works fine..however when uploading via url, the model method returns this error: SuspiciousFileOperation at /post/ The joined path (/var/folders/t9/7v8mki3s3h39fzylxfpsk9640000nn/T/tmpmvb9wxq6) is located outside of the base path component (/Users/zorgan/Desktop/app/draft1/media) Can someone explain what this means? It's obviously not uploading to the media folder, but I have no idea what /var/folders/ is. All my media files upload … -
Reproduce in a Django's template
In [24]: list = [] In [25]: for item in perc: ...: if item.loan.request.customer_id not in list: ...: print(item.loan.request.customer.user.last_name, item.loan.requ ...: est.customer.user.first_name) ...: list.append(item.loan.request.customer_id) ...: (u'Kshlerin', u'Dwight') (u'Boyer', u'Keshaun') I would like to reproduce such loop in the template. Here is the view related to that template : class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' #row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' #def get_icon(self, req): # return icon(req.get_icon(), css_class=get_request_color(req, text=True)) def active(self, obj): if obj.is_active: return icon(obj.get_icon(), css_class='green-text', tooltip=_('Active')) else: return icon(obj.get_icon(), css_class='red-text', tooltip=_('Inactive')) def get_customer(self, req): return 'test' #url = reverse('customers:profile', kwargs={'cust': req.customer.user.pk}) #return '<a href="%s">%s</a>' % (url, req.customer) def notes_count(self, obj): return obj.notes.count() notes_count_label = _('Notes') def get_change_url(self, obj): return obj.get_absolute_url() class Meta: ordering = ('-created', '-modified') sortable = ('start_date', 'end_date', 'created', 'state', 'modified') list_filter = ('state', 'is_active') list_display = ( 'loan', 'state', 'start_date', 'end_date', 'current_balance', 'operation_error', 'modified', 'created', 'notes_count', 'active' ) and here is the model related to that template : @python_2_unicode_compatible class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) I thought I could … -
Django: relative path for media_root not located within project directory
I have a Django app that displays surveillance video thumbnails (as hyperlinks to their respective videos) created by another surveillance app in a way that works better for me than the surveillance app displays them natively. Basically I have a script that moves the files every half hour from the surveillance app storage location to the location that production server will serve them to the Django app. Say these files are moved to this location on the server: /media/djangoAppMedia/ For development thus far, I've had my MEDIA_ROOT hard-coded to this path: MEDIA_ROOT = '/media/djangoAppMedia/' I'd like to change this to a relative path going forward, but all examples that I can find always reference a media root that is within the main Django app project. EX. MEDIA_ROOT = os.path.join(ENV_PATH, 'media/'). How can I set my media root to a relative path that's not within my Django directory? -
Adding javascript code to pick up data from file for python django dashboard
Trying to pick up a data file with data I need to add to dashboard. Whenever I add this code the entire JavaScript file kills my django server. The data file exists. I tried to add this code outside the function and also tried with it inside and get the same results. /* global $, Dashboard */ var dashboard = new Dashboard(); dashboard.addWidget('clock_widget', 'Clock'); dashboard.addWidget('current_valuation_widget', 'Number', { var request = new XMLHttpRequest(); request.open('GET', 'text.txt'); request.onreadystatechange = function() { if (request.readyState === 4) { var textfileContent = request.responseText; // continue your program flow here } } request.send(); getData: function () { $.extend(this.scope, { title: 'Current Valuation', moreInfo: 'In billions', updatedAt: 'Last updated at 14:10', detail: '64%', value: '$35', icon: 'fa fa-arrow-up', dept: 'POIT' }); } }); dashboard.addWidget('buzzwords_widget', 'List', { getData: function () { $.extend(this.scope, { title: 'Buzzwords', moreInfo: '# of times said around the office', updatedAt: 'Last updated at 18:58', data: [{label: 'Exit strategy', value: 24}, {label: 'Web 2.0', value: 12}, {label: 'Turn-key', value: 2}, {label: 'Enterprise', value: 12}, {label: 'Pivoting', value: 3}, {label: 'Leverage', value: 10}, {label: 'Streamlininess', value: 4}, {label: 'Paradigm shift', value: 6}, {label: 'Synergy', value: 7}] }); } }); dashboard.addWidget('convergence_widget', 'Graph', { getData: function () { $.extend(this.scope, … -
Django - Fields from different models in one form
Say I have two different models like... class Model1(models.Model): field1 = models.CharField(max_length=32) field2 = models.CharField(max_length=16) class Model2(models.Model): field3 = models.CharField(max_length=32) field4 = models.CharField(max_length=16) However, upon a sign up form for example I want them to input information that corresponds to field1, field2 and field3; of course which spreads over two separate models. In forms.py class Form1 (forms.ModelForm): ... class Meta: model = Model1, Model2 fields = ['field1', 'field2', 'field3'] How might I get this to work so that I can receive data from two different models on the same one form? Thanks! -
New to Django gateway timeout 504
I'm getting a Gateway Timeout 504 when trying to access http://127.0.0.1:8000/ which is the default when doing the runserver command in python. I already did a migrate and no such luck. This is on a CENTOS7 machine. Here is my settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.10.6. 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! # Deleted the security key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } …