Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting http 500 error in android devices when uploading
So I have deployed an app(website) using django, uwsgi and nginx. This app has a form page which can be attached by some images. When I try to fill the form and upload an image using my laptop(which I have window 10 on it) everything is OK. But when I try to fill the form from an android phone and attach an image to it I begin to get 500 error (Internal server). But when I don't attach any images I don't get this error. I have read the logs of my uwsgi and also my nginx. There is nothing specialy there. For instance this is what I found in my nginx access.log files! 141.101.76.75 - - [06/Aug/2018:12:32:14 -0400] "GET /login/?next=/create/ HTTP/1.1" 500 27 "http://example.com/" "Mozilla/5.0 (Linux; Android 8.0.0; SM-A530F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.70 Mobile Safari/537.36" also here is my nginx config file: upstream django { server unix:///home/alfabet/path/mysite.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 80; # the domain name it will serve for server_name example.com www.example.com; # substitute … -
Django: Image is stored twice
In my web application I have a model called Photo that contains a field image and thumbnail. When a user uploads an image, I'm resizing and compressing it using pillow. Unfortunately, I just noticed that both the normal image (image field) and the thumbnail (thumbnail field) are stored twice in the file system. Here you can see the code in my models.py for the Photo: class Foto(models.Model): image = models.ImageField(upload_to=RandomFileName(directory="photos"), validators=[ FileExtensionValidator(allowed_extensions=['png', 'gif', 'jpg', 'jpeg']), FileSizeValidator(mb=10), ]) thumbnail = models.ImageField(editable=False, upload_to=RandomFileName(directory="photos/thumb")) def save(self, *args, **kwargs): # Compress the uploaded image compressed_image_binary, file_extension = compress_image(max_width=1500, max_height=1300, quality=83, original_image=self.image) # Because of the 'upload_to' parameter, the filename here does not matter. Only extension needed! self.image.save("_." + file_extension, ContentFile(compressed_image_binary), save=False) del compressed_image_binary # Just let's make sure memory can be freed # Now create a thumbnail thumbnail_binary, file_extension = compress_image(max_width=320, max_height=300, quality=60, original_image=self.image) # Because of the 'upload_to' parameter, the filename here does not matter. Only extension needed! self.thumbnail.save("_." + file_extension, ContentFile(thumbnail_binary), save=False) super().save(*args, **kwargs) def compress_image(max_width, max_height, quality, original_image): MAX_WIDTH = max_width MAX_HEIGHT = max_height image = Image.open(original_image) image.thumbnail((MAX_WIDTH, MAX_HEIGHT), Image.ANTIALIAS) image_type = image.format if image_type not in ('JPEG', 'GIF', 'PNG'): raise Exception("Image has wrong file type: " + image_type) # Save … -
Google OAuth 2.0 web application looking up redirect URIs for the wrong project
I'm trying to build a web application in Django which requests users to manage their calendars using the Google Calendar API. I'm following the steps described in https://developers.google.com/identity/protocols/OAuth2WebServer, but in Django instead of Flask. So far, I've written a view called google_calendar() which gets an authorization URL and redirects to it: from django.conf import settings from django.shortcuts import redirect import google.oauth2.credentials import google_auth_oauthlib.flow # Client configuration for an OAuth 2.0 web server application # (cf. https://developers.google.com/identity/protocols/OAuth2WebServer) CLIENT_CONFIG = {'web': { 'client_id': settings.GOOGLE_CLIENT_ID, 'project_id': settings.GOOGLE_PROJECT_ID, 'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 'token_uri': 'https://www.googleapis.com/oauth2/v3/token', 'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs', 'client_secret': settings.GOOGLE_CLIENT_SECRET, 'redirect_uris': settings.GOOGLE_REDIRECT_URIS, 'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}} # This scope will allow the application to manage your calendars SCOPES = ['https://www.googleapis.com/auth/calendar'] def get_authorization_url(): # Use the information in the client_secret.json to identify # the application requesting authorization. flow = google_auth_oauthlib.flow.Flow.from_client_config( client_config=CLIENT_CONFIG, scopes=SCOPES) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI is required. flow.redirect_uri = 'http://localhost:8000' # Generate URL for request to Google's OAuth 2.0 server. # Use kwargs to set optional request parameters. authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for … -
How to convert html form to Django form and preserve styling?
I have a pure html form which I wish to use to collect sign-in information using a Django backend. Here is my pure non-Django html form: <form id="contactForm" method="POST"> <div class="row"> <div class="form-group"> <div class="col-md-12"> <label>Username or E-mail Address</label> <input type="text" value="" class="form-control"> </div> </div> </div> <div class="row"> <div class="form-group"> <div class="col-md-12"> <a class="pull-right" href="#">(Lost Password?)</a> <label>Password</label> <input type="password" value="" class="form-control"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <span class="remember-box checkbox"> <label for="rememberme"> <input type="checkbox" id="rememberme" name="rememberme">Remember Me </label> </span> </div> <div class="col-md-6"> <a href="#" class="btn btn-primary btn-orange uppercase pull-right">Login</a> </div> </div> </form> Here is what it looks like with all the styling: In order to process this form I have created a view: def login_page(request): form = LoginForm(request.POST or None) context = {'form': form} next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) return redirect('/') else: print('Error') return render(request, 'users/login.html', context) I am aware that I need a form.py class which I have created and is as follows: class LoginForm(forms.Form): username = forms.CharField() password = … -
Database JSON updated Entries, FireBase, Angular, Django? What should I use?
My goal is to build a website or PWA that loads a user from a database and their Information. Some of their information is from a JSON string. I have a few caveats here. I don't think the Json String keeps monthly time records, So I will have to add that as an entry, so I can give a yearly and Monthly amount. What is the best way or is that a common problem in data basing to use jsons to update database entries? My other question is I know that this is usually a form of preference, but I would like the users to be able to load the information and have graphs to show stats based on their entries in the database. Angular, Django, React, or if anyone has any experience with FireBase. I would love some pro's or con's for this project on that. I have already made some examples but before going forward I wanted to get an opinion. Sorry, I am kind of new to web development -
able to save fields into a variable and use into queryset.value() ? django
I know that when we call querysets, we can use values() to get fields needed such as values('name', 'other_model__title') and such. But I am wondering if it is possible to save it into a variable for example: value_fields = ('name', 'other_model__title') model.objects.filter().values(value_fields) I tried this already which failed, also tried using list instead of tuple which failed too, giving me error saying object has no attribute split Thanks in advance for any help. -
fname must be a PathLike or file handle
I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title. This is my view: import django from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np import matplotlib.pyplot as plt import io def mplimage(request): fig = Figure() canvas = FigureCanvas(fig) x = np.arange(-2, 1.5, .01) y = np.sin(np.exp(2 * x)) plt.plot(x, y) buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = django.http.HttpResponse(content_type='image/png') canvas.print_png(response) return response and here the link in urls.py: import mpl.views url(r'mplimage.png', mpl.views.mplimage) -
My Third "Grab Object in Django" Post
Clearly I am struggling with various permutations of grabbing objects in Django. Here's another. This is for the same library app I've been working on (in case you have seen my other questions). On the home page, I display the active user's name and information (this works fine). Then I wish to display all of the reviews that the active user has written. I am basically able to do this as well, except it just shows the reviews with no reference to the books they are supposed to describe. So... I need to be able to grab the Book object by its Review object. In other words, each time I display a Review, I want to be able to grab the Book (title and author) that it pertains to. Keep in mind that I can't grab the Book by the User (using created_by), because a user can write reviews for books that they did not add to the db. I hope this makes sense but I'm sure you can see that I am struggling with such problems. In models.py, I set up my tables like this (keep in mind that the User table is in a different app): class Book(models.Model): … -
Error while migrating in django
I'm sorry, I don't think the title of my question is comprehensible as I'm absolutely a noob trying to understand django after LPTHW. Anyway, I'm following a tutorial in setting up Django to use MariaDB. But unfortunately when I run python manage.py migrate I get humongous block of error message. Here's the block: System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 412, in _query rowcount = self._do_query(q) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 375, in _do_query db.query(q) File "/home/noob/Documents/projects/python/django/myproject/myprojectenv/lib/python3.5/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1050, "Table 'django_content_type' already exists") The above exception was the direct cause … -
Netezza DB connection in Django
I am new to Django and I am confused on how to connect to Netezza DB and query data from it. I tried different packages and made appropriate changes in the settings.py file. I looked into django-netezza (https://github.com/msabramo/django-netezza) but this package is 7 years old and the person who created this doesn't seems to be wokring on the package anymore. I also looked into django-pyodbc but it did not work either. I ended up getting a version error. I have Django 2.0.6. I then took a step back and tried to connect to a SQL server. I got an error there as well asking for Visual Basic C++ 14.0 Build Tools. I am working on this right now, but I still need to figure out a way to connect to Netezza. Has anyone found success in connecting to Netezza? Also, the only way I know is the models route. Is there a different approach that I can take? -
Enforcing model limit in GenericForeignKey
I'm have a simple model using a GenericForeignKey object. I would like to limit the allowed content_objects to a specific, static set of models. Lets say, I would only like it to accept ModelA and ModelB from app_a and app_b, respectively. I ran across this question that essentially describes what I'm trying to achieve. I implemented the proposed solution, and I end up with a model that looks something like this: class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() limit = models.Q(app_label='app_a', model='modela') \ | models.Q(app_label='app_b', model='modelb') content_type = models.ForeignKey(ContentType, limit_choices_to=limit) content_object = GenericForeignKey('content_type', 'object_id') This actually appears to work correctly when using the /admin/ panel to add the object, the content_type pulls from my available options. However, when I write unit tests, or using the shell, it doesn't seem to enforce this. For instance, I would expect: TaggedItem.objects.create(content_object=(ModelZ())) To raise an exception. However, it doesn't. Is there any django-istic way to enforce the content_objects to be an instance of a model given in the limit_choices_to? -
Select a valid choice. is not one of the available choices
forms.py LANGUAGE_CHOICE = ( ('C', 'C'), ('cplus', 'C++'), ('csharp', 'C#'), ('html', 'Html'), ) language = forms.ChoiceField(choices=LANGUAGE_CHOICE, label= "Programming Language you know:",widget= forms.CheckboxSelectMultiple()) templates/formview.html <div class="row"> <div class="col-sm-6 label_field"> <label for="{{form.language.id_for_label}}"{{form.language.label}}</label> </div> <div class="col-sm-6"> {% for checkbox in form.language %} {{checkbox}}<br> {% endfor %} </div> </div> Validation Error Select a valid choice. ['C', 'csharp', 'html'] is not one of the available choices. Could anyone please help me to solve this validation error of CheckboxSelectMultiple -
Django 2.1 startproject throws weird error
I am trying to start my first app in Django 2.1 on Python 3.4. It's the first time with this versions, previously I worked only with Django 1.10 and Python 2.7. Everything on Ubunutu 14.04 I created a virtualenv, mostly following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-ubuntu-16-04 However with slight changes of my own because first a locale issue appeared and was fixed like this: sudo locale-gen "en_US.UTF-8" Afterwards I changed the aliases like this: alias python=python3 alias pip=pip3 That's all. After installing django==2.1 and runing: django-admin.py start project myproject This error appeared: Traceback (most recent call last): File "/home/ubuntu/workspace/skw/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line File "/home/ubuntu/workspace/skw/lib/python3.4/site-packages/django/core/management/__init__.py", line 11, in <module> from django.conf import settings File "/home/ubuntu/workspace/skw/lib/python3.4/site-packages/django/conf/__init__.py", line 18, in <module> from django.utils.functional import LazyObject, empty File "/home/ubuntu/workspace/skw/lib/python3.4/site-packages/django/utils/functional.py", line 12 return _curried_func(*args, *moreargs, **{**kwargs, **morekwargs}) ^ Inside this file functional.py in django my lint is showing a syntax error exactly at the line 12 ... but not sure if that's relevant, since I didn't change the syntax to python3 yet. Because of this I can not start a new project, how to solve this? -
Django: URLField for image: URL from remote or local static file
I have the following field in my Article model: picture_url = models.URLField(null=True) article_as_dict is a dictionary obtained from an external source. If it contains an image URL, I want to save that as my URL. However, If there is no URL from external path, I want to reference a local .jpg as a URL (so I can save it to the field). How can this be achieved? -
Why is Django shell running a function using not the inputted parameters?
I have a function that is supposed to update Django objects, which each have two date fields, named "production" and "development". The function reads from a python object, containing a list of Django objects along with their new dates, as well as a single label indicating for the entire list whether the fields to be updated are "production" or "development". For testing, I have two python objects, containing two different lists of django objects and dates, one for "production" and one for "development". When I call the function on one of these objects, no matter what, it's the list and dates in the "production" object that get updated, though whether the info goes to the "development" or "production" fields in those django objects still depends on the label of the initial python object being called on. I have no idea why this is happening. Python class and initialization of two python objects: import pytz import datetime class timess(): #Reflects update statuses for the two servers lists = { "none" : [], "uploaded" : [], } servername = "" def __init__(self, nonay, uplay, servertype): self.lists["none"] = nonay self.lists["uploaded"] = uplay self.servername = servertype timezone = pytz.timezone("America/Chicago") d1 = datetime.datetime(1999, 8, 12, … -
{% if } use to hide the table view in Django. HTML-file
I have a small problem in creation correct formula '{if}' in my html file. I would like to have a view for all table which it was not available if the user not searches something. But in my situation it is always available, and I can not hide it.I will be grateful for any help. My html file {% extends 'base.html' %} {% load widget_tweaks %} {% block title %} <hr class="featurette-divider"> <h1><center>Wyszukiwarka firm</center></h1> <hr class="featurette-divider"> {% endblock %} {% block content %} <form method="get"> <div class="well"> <h4 style="margin-top: 1"><center>Wpisz nazwę firmy</center></h4> <div class="row " > <div class="form-group form-group-lg " > <div class="col-sm-12 " > {{ filter.form.label_tag }} {% render_field filter.form.name class="form-control" %} </div> </div> <div class="form-group col-sm-8 col-md-6"> {{ filter.form.groups.label_tag }} </div> </div> <button type="submit" class="btn btn-primary btn-block"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> <table class="table table-bordered"> <thead> <tr> <th>Nazwa</th> <th>Rating</th> <th>Ilość opinii</th> <th>Dodatkowe informacje</th> <th>Miasto</th> </tr> </thead> <tbody> {% for wine in filter.qs %} <tr> <td><h4><a href="{% url 'reviews:wine_detail' wine.id %}"> {{ wine.name }} </a></h4></td> <td>{{ wine.average_rating | floatformat }} average rating</td> <td>{{ wine.review_set.count }} reviews</td> <td>{{ user.date_joined }}</td> <td> {% for group in user.groups.all %} {{ group }} {% empty %} <em class="text-muted">Brak inf. o miescie</em> … -
django: cant import models from global app
Trying to import models from different app in views.py: from global.models import Global Console raise an error: from global.models import Global ^ SyntaxError: invalid syntax I checked a lot of information, but cant find what iam doing wrong. global.models.py from django.db import models # Create your models here. class Global(models.Model): phone = models.CharField(max_length=50, blank=True) email = models.EmailField(max_length=50, blank=True) adress = models.CharField(max_length=100, blank=True) class Meta: verbose_name = 'Глобальные настройки' verbose_name_plural = 'Глобальные настройки' def __str__(self): return 'Глобальные настройки' projects.views.py from django.shortcuts import render, redirect, get_object_or_404 from global.models import Global from .models import Advertising, Films, Presentations, AuthorsLeft, AuthorsRight, BackstageImg from django.utils import timezone in my editor 'global' has blue color, and if i try to import another app it works normally. Could it be that 'global' reserved by django, or i simply doing something wrong? -
Django translation doesn't work
I'm trying to use django translation, but nothing happens. I can't find my mistake. Could anyone please help me? Some Details: I've added LocaleMiddleware; I've added the context_processors; LANGUAGE_CODE = 'pt-br'; LANGUAGES = ( ('pt', 'Portuguese'), ('en', 'English') ); LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')]; My django.po e .mo are created and looks correctly. Some suggestion? -
Django : Count, Group By and Order By with many to many fied
I have two models : class Actors(models.Model): name = models.CharField(max_length=128) ... class Movies(models.Model) title = models.CharField(max_length=128) casting = models.ManyToManyField("actors.Actors", related_name="casting") ... I am looking for ordering actors by using the number of movies they played in. Django autogenerated a table with actors_id and movies_id, named movie_movie_casting : +-----+-----------+-----------+ | id | movies_id | actors_id | +-----+-----------+-----------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 2 | 1 | | 4 | 3 | 1 | ... Here actor #1 played in movies #1, #2 and #3. And actor #2 played only in movie #1. Here is the request used in MySQL to get what I want : SELECT actors_id, COUNT(movies_id) as count FROM movies_movies_casting GROUP BY actors_id ORDER BY count; The result is : +-----------+-------+ | actors_id | count | +-----------+-------+ | 15 | 29 | // actor #15 played in 29 movies | 12 | 21 | | 24 | 17 | | 3 | 16 | | 20 | 15 | | 21 | 14 | ... What is the request used in Django to get this result ? -
Django forms: changing a single text file upload to a multiple text file uploads
currently my form allows the user to upload a single file (which creates a single object with the file contents as its attribute). I would like to add a button beneath the form named "add another file" which duplicates the form to allow a user to submit more than one file upon clicking "Create". Each upload should create its own object specific to the logged in user. Please comment if you need further code. Thanks :) views.py class CreateSuspiciousView(CreateView): template_name = 'external_plag/corpus_form.html' model = Suspicious fields = ['corpus', 'suspicious_file_names', 'suspicious_file'] success_url = reverse_lazy('ext-list-corpus') class CorpusCreateView(CreateView): model = Corpus fields = ['corpus_name'] success_url = reverse_lazy('ext-list-corpus') def form_valid(self, form): corpus = form.save(False) corpus.user_id = self.request.user.id corpus.save() return HttpResponseRedirect(self.success_url) forms.py from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() class SuspiciousSelectionForm(forms.Form): corpus = forms.IntegerField(widget=forms.HiddenInput) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.CorpusListView.as_view(), name='external_plagiarism'), url(r'^external/(?P<pk>\d+)$', views.CorpusDetailView.as_view(), name='ext-show-corpus'), url(r'^external/create$', views.CorpusCreateView.as_view(), name='ext-create-corpus'), url(r'^external/list$', views.CorpusListView.as_view(), name='ext-list-corpus'), url(r'^external/suspicious/create-new$', views.CreateSuspiciousView.as_view(), name='ext-create-suspicious'), url(r'^external/start-detection/$', views.start_detection, name='ext-start-detection'), url(r'^multistep/$', views.multistep_process, name='ext-multistep') ] corpus_form.html {% block content %} <div class="jumbotron" > <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_p }} <tr> <td colspan="2" align="right"><input type="submit" value="Create"></td> </tr> </table> </form> </div> {% endblock %} models.py … -
Django error - matching query does not exist (used django1.10 on windows server 2016)
OS and configuration: Python36/Django1.10 OS : Windows Server 2016 (used wfastcgi) Database: MSSQL 2014 the code as follows: # models.py class School(models.Model): SchoolName = models.CharField(max_length=100) Address = models.CharField(max_length=200, null=True, blank=True) Website = models.URLField(null=True, blank=True) Example data like: "Harvard University" | Address1 | Website1 "University of Michigan, Ann Arbor" | Address2 | Website2 "Ben-Gurion University of the Negev" |...etc "Chang'an University" |...etc "Université Libre de Bruxelles" |...etc I want search school name can request schoolinfo(Address and Website) My url.py and views.py as follows: # url.py url(r'^bySchoolName/(.*)', bySchoolName), # views.py def bySchoolName(request, SchoolName): SchoolData = models.School.objects.get(SchoolName=SchoolName) return render(request, 'bySchoolName.html', locals()) (Browser URL encodeing) /bySchoolName/Harvard%20University (Have Response) /bySchoolName/University%20of%20Michigan,%20Ann%20Arbor (Have Response) /bySchoolName/Ben-Gurion%20University%20of%20the%20Negev (Have Response) /bySchoolName/Chang'an%20University (Have Response) Other than is error ... /bySchoolName/Université%20Libre%20de%20Bruxelles error messages: DoesNotExist at /bySchoolName/ School matching query does not exist. I have already determined database have 'Université Libre de Bruxelles' After that I found out Request information... PATH_TRANSLATED : 'D:\\WebSite\\SchoolAPP\\bySchoolName\\Universit? Libre de Bruxelles' REQUEST_URI : '/bySchoolName/Universit? Libre de Bruxelles' I don't know which side has a problem (test environment have Response, IIS environment is error) ...maybe the string transfer process has a problem decoding? -
Django 2 - syntax of using create view to autopopulate fields
I have a training project I am working on that involves a school administration web app with Django 2. I have set up 4 modules School, Student, Course, Text. As you may have guessed, there is a many to many relationship between the Course model and the rest of the models. To avoid this created a CourseInfo model that have foreign keys for all the other models. The model looks like this: class CourseInfo(models.Model): course = models.ForeignKey(Course,related_name='courses', on_delete="Protect") school = models.ForeignKey(School,related_name='schools', on_delete="Protect") student = models.ForeignKey(Student,related_name='students', on_delete="Protect", required=False) text = models.ForeignKey(Text,related_name='texts', on_delete="Protect", required=False) I made a create view to setup a course and want to be able to associate a student or school to the course detail without having to put in redundant information. I am having trouble with the syntax. For example, once I create a course and go to the course detail page. I want to be able to associate a student to the CourseInfo model and have the school associated with that student automatically added for the end user. My main question is how do I make a create view to do this? Maybe something like this (still new to Django syntax): class CourseAddStudentView(CreateView): model = models.CourseInfo fields … -
Query for days since I saved data in db in DJango
in my db i have a field date that register the date when the respective data is saved. I want to see how many days past since I saved that data,how can i do that in django?(I want to make something like 'Today's date-respectiv data = x days') This is my model : class Comment(models.Model): created_date = models.DateTimeField() comment = models.CharField(max_length=500, default='', blank=True) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) post =models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE) -
PyCharm 2018 Python Unresolved Reference 'django' VirtualEnv
I have the newest PyCharm version (2018) and the latest Django version (2.1) and Python (3.6) When I want to import something in PyCharm from Django: from django.urls import url I get an error message under django stating: Unresolved reference 'django'. I created a virtual environment and I ran a project on it, the most famous one (polls) and it ran very well. But now I noticed that I have this error, what is the solution? Thank you in advance. -
How to connect a ReactJS Form to a Django model to automatically obtain fields (foreignkeys, choices etc.)
I have a quite complex Django model that is connected to my ReactJS frontend through a DRF API. Inside this model, many instances are ForeignKey or CharFields that include an array of options to be selected. Can you please tell me if there's a way I can have my React form to inherit the information of all the fields, instead of writing out the form manually? I'd need the frontend form in React to "read" through the right API call and get all the fields from there. How can I achieve this?Thank you very much in advance!