Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save multiple model-forms (which are in 1:1) simultaneously in a view (Django)
how to save multiple model-forms (lAWYER AND CATEGORY) (which are in 1:1) simultaneously in a view (Django) class Lawyer(models.Model): category = models.ForeignKey(Category, related_name='lawyer', on_delete=models.CASCADE) profile = models.ForeignKey(Profile, related_name='profiles', on_delete=models.CASCADE) name = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) class Category(models.Model): profile = models.ForeignKey(Profile, related_name='profile', on_delete=models.CASCADE) category_name = models.CharField(max_length=10, db_index=True,choices=CATEGORY_CHOICES) slug = models.SlugField(max_length=150, unique=True, db_index=True) city = models.CharField(max_length=20) IN VIEWS.PY def lawyer_list(request, category_slug=None): if request.method == 'POST': cat_form = CategoryForm(request.POST) if cat_form.is_valid(): cat_obj = cat_form.save(commit=False) cat_obj.profile = request.user.profile cat_obj.save() lawyer_form = LawyerForm(request.POST) if lawyer_form.is_valid(): lawyer_form = lawyer_form.save(commit=False) lawyer_form.profile = request.user.profile lawyer_form.category = cat_obj lawyer_form.save() ALSO HAVE TWO FORMS 1) class LawyerForm(forms.ModelForm) 2)class CATEGORYForm(forms.ModelForm) IN VIEWS I DONT WANT TO MAKE TWO OBJECT -
How to use Django template as a component?
I have 5 templates: index.html, detail.html, tag.html, login.html, register.html and a base.html All 5 templates will extend base.html. index.html, detail.html, tags.html have a same <section>...</section> html code section with the same data from backend.I want to add this section to base.html, so that don't need to repeat it 3 times in 3 different templates. But the problem is,the login.html and register.html do need this section. I know if it is React.js or Vue.js it will be very easy to use component to solve it. Any good way to solve this question in Django? -
Django + Webpack + Vue + Code splitting - How to change load url of chunk files
I am using Django with Webpack and Vue, And Code splitting in Webpack. Webpack split chunk files from source code of .vue files. But, I can't load chunk files on Web browser because url is incorrect in my project structure. I want to change load url of chunk files but I don't know these. How to change load url of chunk files? Chrome console logs: GET http://localhost:8123/mycomponent.chunk.js 404 (Not Found) main.js:12 Error: Loading chunk 2 failed. (error: http://localhost:8123/mycomponent.chunk.js) at HTMLScriptElement.a (main.js:1) I need url of '/static/js/mycomponent.chunk.js'. webpack.config.js: const path = require("path") const webpack = require('webpack') const BundleTracker = require('webpack-bundle-tracker') const VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { context: __dirname, entry: './src/main.js', output: { path: path.resolve('../static/js/'), filename: "[name].js", chunkFilename: '[name].chunk.js', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader' }, ], }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new VueLoaderPlugin(), ], resolve: { alias: { 'vue': path.resolve('./node_modules/vue/dist/vue.js'), } }, } -
DJango: authenticate function vs verifying username, password and is_active
I am working on a Django Project: I have a login form with username and password Generally i observed authenticate function is used to authenticate a user and pass i.e user = authenticate(username, password) I tried to understand the authenticate function but i found it is not so easy. Instead of using the authenticate function i want to check the authentication the following way: 1) check if the username exists 2) check if the password matches 3) check if is_active is true. Which i can do by the following way: username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') # check if user exists try: user = User.objects.get(username=username) except User.DoesNotExist: user = None #check if user is_active if user.is_active: user_active = true else user_active = false #check the password if user_active: password_match = user.check_password(password): else: password_match = false if password_match: msg = "Login Successful" else: msg = "Login Failed" Will the above serve the same purpose as authenticate function or is there something else to be checked. -
Nginx not serving static files with Waitress+Django on Windows
I have installed django 2.0 on a virtualenv with python 3.4 and because gunicorn cannot be installed in windows i found waitress that is ok with his work, mi problem is that nginx (probably a bad configuration by my part) is not serving the static files but i do not find to much about nginx on windows. This is my settings.py: 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__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '4e&6aw+(5&cg^_!05r(&7_#dghg_pdgopq(yk)xa^bog7j)^*j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['myip','mydomain.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apáname' ] 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 = 'helloworld.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 = 'helloworld.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = … -
How do I limit the nested queryset in a related serializer to a subset of the related model instances?
I have tracks and albums. I would like the ability to mark tracks as deleted but not remove them from the database. I would like tracks that are marked as deleted (is_deleted=True) not to show up in the API in my nested serializer. I have tried a custom "get_queryset" method on TrackSerializer.py but it is not called. serializers.py class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) ### How do I limit tracks in the related/nested serializer to tracks on this album that have not been deleted? models.py class Track(models.Model): name = models.CharField() is_deleted = models.BooleanField(default=False) album = models.ForeignKey(Album, related_name="tracks") class Album(models.Model): name = models.CharField() -
Django - Help me to understand how to structure my query
I'm working on project that simple web site. I thought it was simple but one thing is very confusing I don't know the question title if I wish know it will be answer from this question. So here is the thing. I have model that called Product. The Product model have type field. As a user if I creating a new product and when I choose product's type, how can I change product's questions. For example: Type: Cars ---> Ask from user about brand_name, Mileage, year of production, colors of door etc Type: Laptop ---> Ask from user about price, gigabytes of ram, cpu, display size etc -
Apache2 WSGI Django - Directory access
I have an Django(10.5) WSGI application running on Unbuntu(16.04). The application works completely except for one piece of functionality. The functionality is located in the views.py file and it tries to get a list of file names in a directory but is unable too. apache2 is running under the user www-data and the directory is owned by another user. I have tried to chown and chmod the directory so that it is owned by www-data but this didn't make a difference. I have also added the following to the sites-available file: Require all granted NOTE: The functionality works if I run it in Django's dev server: python3 ./manage.py runserver 0:80 -
Django Channels: Get stuck after period of time
I run code from https://github.com/andrewgodwin/channels-examples/tree/master/multichat for around 50 users. It goes to get stuck without any notice. Server is not down, access log has nothing special. When I stop daphne server (with Ctrl+C), it takes about 5-10 minutes to completely go down. Sometime I have to run kill command. It is very weird when I put daphne inside supervisord, I restart it every 30 minutes using crontab, websocket can be connected normally. It's hacky but working. My config: HAProxy => Daphne daphne -b 192.168.0.6 -p 8000 yyapp.asgi:application --access-log=/home/admin/daphne.log backend daphne balance source option http-server-close option forceclose timeout check 1000ms reqrep ^([^\ ]*)\ /ws/(.*) \1\ /\2 server daphne 192.168.0.6:8000 check maxconn 10000 inter 5s Debian: 9.4 (original kernel) on OVH server. Python: 3.6.4 Daphne: 2.2.1 Channels: 2.1.2 Django: 1.11.15 Redis: 4.0.11 I know this question may be too general, but I really have no ideas with this. I tried upgrade python, re-install all the packages but it didn't work. -
Django Allowed Host Best Setting
I'm making a website using Django for the usage of my university, I want it to be accessible whether you are inside the campus or not. My current SETTINGS.py has ALLOWED_HOSTS = ['*'] But I read that leaving it on wildcard can lead to potential security issues... Is there any better way to configure this so that anyone may access to My Website? Aditional information: I currently use Database Sessions which expire within 10 minutes I'm planning on using apache with mod_wsgi as the main server As far as I know my application never uses the requesting host name for anything (unless django backends use it in some way I'm not aware of) -
Django and Cropper; How to set the parameter
I'm creating a project using Django and I was trying to adapt cropper into my project. I was following this tutorial https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html but I found out the cropped image cannot be uploaded and the original image is shown up. views.py def edit_profile_image(request): try: image = ProfileImage.objects.get(user=request.user) except: image = None if request.method == 'POST': form = EditProfileImageForm(instance=image, data=request.POST, files=request.FILES) if form.is_valid(): resized_image = form.save(commit=False) resized_image.user_id = request.user.id resized_image.save() return HttpResponseRedirect(reverse_lazy('blog:my_profile')) else: form = EditProfileImageForm(instance=image) return render(request, 'blog/edit_profile_image.html', {'form': form, 'image': image}) forms.py class EditProfileImageForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = ProfileImage fields = ('file', 'x', 'y', 'width', 'height', ) def save(self, *args, **kwargs): photo = super(EditProfileImageForm, self).save(*args, **kwargs) x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.file) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.file.name) return photo I tried something using the tutorial's code and I found out if form.is_valid(): resized = form.save(commit=False) resized.save() return redirect('photo_list') this way doesn't work as my code does if form.is_valid(): form.save(commit=False) form.save() return redirect('photo_list') and this way does work but I still cannot understand how I can fix this. How can I associate the … -
OperationalError at /no such table: django_session error on public server, site works fine on local server
I am trying to send data taken from a form to another views page to process it. I am using sessions to send that data. It works fine on a local host, the data is sent and received successfully, however, on a public server it crashes. I found a couple of posts regarding the same problem but their issue is mostly related to database integration which is not the case here. This is the code that is causing the error its inside views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.templatetags.static import static from plots.forms import plotform from django.http import JsonResponse #from rest_framework.views import APIView #from rest_framework.response import Response import numpy as np import csv import math import json def plots2(request): if request.method == 'POST': form = plotform(request.POST) if form.is_valid(): frequency_min = form.cleaned_data['frequency_min'] frequency_max = form.cleaned_data['frequency_max'] distance = form.cleaned_data['distance'] humidity = form.cleaned_data['humidity'] temp = form.cleaned_data['temp'] request.session['frequency_min'] = frequency_min request.session['frequency_max'] = frequency_max request.session['distance'] = distance request.session['humidity'] = humidity request.session['temp'] = temp return redirect('plots/') form = plotform() #includes the form inside plots.html #render(request, 'plots/plots2.html', {'form':form}) #return redirect(request.POST.get('next','plots/')) #return redirect('plots/plots') return render(request, 'plots/plots2.html', {'form':form}) def plots(request): frequency_min_input = request.session['frequency_min'] frequency_max_input = request.session['frequency_max'] distance_input = request.session['distance'] humidity_input = request.session['humidity'] temperature_input = … -
Why is my "if project_form.is_valid() and p_formset.is_valid()" not working?
So I have been trying to implement a feature on my website to be able to post with multiple images in it. I am not sure why if I make an if statement for both project_forms.is_valid() and p_formset.is_valid() my code is not working. But if it is just either one of them they work fine. I don't have any errors popping up its just that it is not doing what it is supposed to do. No images or posts go to my database. The way I implemented my multiple image upload is to have a separate table for the posts and multiple image upload but are linked with a foreign key. Here are my code: views.py def create_projects(request): # Special case if the request method is not POST project_form = ProjectsForm(request.POST, request.FILES) p_formset = P_ImageForm(request.POST, request.FILES) # Checks if the form is valid before save if project_form.is_valid() and p_formset.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() p_photos = p_formset.save(commit=False) p_photos.save() data = {'is_valid': True, 'name': p_photos.p_file.name, 'url': p_photos.p_file.url} return JsonResponse(data) else: data = {'is_valid': False} context = { 'project_form': project_form, 'p_formset': p_formset, } return render(request, 'projects/forms.html', context) models.py from django.db import models from django.utils import timezone from django.forms import ModelForm … -
Modifying a form's fields after user authentication
I have a view that inherits from UpdateView and UserPassesTestMixin. Two types of user can access it - either a superuser or a normal one. I determine which one it is in test_func() and store the result in self.superuser. Now I want to modify the displayed form depending on the level of the user (namely disable almost all fields in the form if the current user is not a superuser, otherwise leave them all enabled). Which view method should I override to modify the view's form (in this case disable the necessary fields)? Or is this idea wrong and I should approach this differently? -
Django 2.0: back button redirecting to different pages based on where you came from
I'm using Django 2.0 and have a model A with a list view and a detail view. You can go from the list view to the detail view in the following manner: Button on ListView Html page to go to detail view <td><a href="{{ a.get_absolute_url }}" class="btn btn-primary" class>View</a></td> Models.py def get_absolute_url(self): return reverse("a:detail", kwargs={'a_id': self.a_id}) Then in the DetailView Html Page I have a button to go back to the detail view. <a href="{% url 'a:list' %}" class="btn btn-primary" class>Back</a> where a:list takes you to ListView Html That is pretty straight forward. However, what if I made this same process for another html page. Then I'd need a second 'back' buttons to go to this new html page. It gets cumbersome really quick. Is there a way that you can create a button that will go back to whatever page the user came from? This can either be to any page that has a button to go to this page (and you pass in some information that allows you to backtrack this) or maybe you typed in the url and want the back button to go back to whatever page you came from. I'm open to either way. -
django:views not grabbing ID from url DJANGO REST FRAMEWORK
hello guys i want to create a like function for my posts in DRF Creating a "like" url/button for Django Rest Framework i have followed the above question from stack overflow here is my models.py class status(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=False) # user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) content=models.TextField(blank=True,null=True) image=models.ImageField(upload_to="upload",null=True,blank=True) updated=models.DateTimeField(auto_now=True) time=models.DateTimeField(auto_now_add=True) likes=models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name='post_likes') def __str__(self): return self.content serializers.py class statusSerializer(serializers.ModelSerializer): # user_name = serializers.ReadOnlyField(source='user.username') user=UserPublicSerializer(read_only=True) # rating=RatingSerializer(required=False) # rating=RatingSerializer() class Meta: model=status fields=['id','user','content','image','likes'] views.py @api_view(['POST']) def LikesApi(self,request,id): # status = get_object_or_404(id=request.POST.get('id', '')) status = get_object_or_404(id=id) status.likes.add(request.user) serializer = statusSerializer(status) return Response(serializer.data, status=status.HTTP_201_CREATED) i have tried both the ways with regards of that question from stack @api_view(['POST']) def LikesApi(self,request,id): serializer=statusSerializer(data=request.DATA) if serializer.is_valid(): serializer.object.content_object=get_object_or_404(status,id=request.POST.get('id', '')) serializer.object.likes.add(request.user) serializer.save() return RestResponse(serializer.data, status=status.HTTP_201_CREATED) return RestResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) here is my urls.py urlpatterns = [ # url(r'^$/', StatusListSearchApi.as_view()), url(r'^list/', StatusListSearchApi.as_view()), url(r'^user/', UserPost.as_view()), url(r'^like/(?P<id>\d+)/$',LikesApi), post objects are present in my api/list/ url http://127.0.0.1:8000/api/list/like?id=35 when i fired this url i cant see any incremination of likes in my browasable api detailview http://127.0.0.1:8000/api/like?id=35 tried this as well but rather got a page not found 404 error i dont know where the issue is and how can i grab the id of a particular post through urls and proccess the view -
Heroku/Django error on collectstatic : OSError: [Errno 2] No such file or directory
I'm beginning to fear I'll never get my site launched. I've launched an app on heroku, but I can't run heroku run python manage.py collectstatic without getting an OSError: Traceback: Running python manage.py collectstatic on ⬢ tallymusic... up, run.1934 (Free) Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect for path, storage in finder.list(self.ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 112, in list for path in utils.get_files(storage, ignore_patterns): File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files directories, files = storage.listdir(location) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 397, in listdir for entry in os.listdir(path): OSError: [Errno 2] No such file or directory: '/app/tallymusicsite/assets' Here's my settings.py static settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'tallymusic/assets'), os.path.join(BASE_DIR, 'tallymusic/assets/css'), os.path.join(BASE_DIR, 'tallymusic/assets/images'), os.path.join(BASE_DIR, 'tallymusic/assets/js'), os.path.join(BASE_DIR, 'tallymusic/assets/venue_images') ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' I'm pretty confident the error comes from my STATICFILES_DIRS setting, but I can't figure it out. I've read so many answers on this error … -
Django Inline formsets - Inline model delete not working; deleted_forms empty
I'm unable to delete an inline model or access formset.deleted_forms property in the backend correctly using django inline formsets. The parent model is a document and the child model is a reference. Here is the POST data in the request. The inline formset prefix is reference_set. {u'file_upload': [u'40'], u'reference_set-0-author_names': [u'sdg'], u'reference_set-INITIAL_FORMS': [u'1'], u'title': [u'ertwer'], u'reference_set-MAX_NUM_FORMS': [u'1000'], u'reference_set-0-publication_title': [u'wtrw'], u'author_name': [u'vbcxb'], u'reference_set-0-publisher': [u'fhjgfhj'], u'reference_set-MIN_NUM_FORMS': [u'0'], u'reference_set-0-id': [u'18'], u'reference_set-0-DELETE': [u'on'], u'csrfmiddlewaretoken': [u'AhWofrDZUTxzHFK3FVoST4ALMHFOYOLsG8Kmd7kDyOe6Bz3olNQy69AfUgZATyHp'], u'reference_set-0-publication_year': [u'3245'], u'reference_set-0-document': [u'17'], u'reference_set-TOTAL_FORMS': [u'1']} Even though the form-x-DELETE field is set to on. The model isn't deleted. Additionally, when I try to print the value of reference_formset.deleted_forms after calling is_valid(), I get an empty list. It might be worth mentioning that I can edit, and add new references just fine using the inline formset. Also I'm using django-dynamic-formset in frontend but I think this is a django problem since the form is not being marked for deletion despite having DELETE field. I've been stuck in this problem for hours now, any help will be greatly appreciated. If any further code is required, do let me know. -
Adding a python script to the PATH environment variable when installing with pip
When installing django via pip, the PATH environment variable is modified to let the user access django-admin directly in the terminal. (django-admin startproject project_name) I would like to the same for my pip package. I looked at how modifying environment variable using python but os.environ["PATH"] wont get saved once the python script is ended. Any suggestion ? -
Sample Response & Request model for swagger to documenting the API in DRF
I want to document my API using swagger generator tool django-rest-swagger in DRF right now I am writing views by inheriting rest_framework.views.APIView I don't want to write views using viewsets nor serializer. Here is the view code sample from rest_framework.views import APIView class SomeView(APIView): ''' get: some description post: some other description ''' def get(self, request, format=None): a = self.request.query_params.get('a',None) b = self.request.query_params.get('b',None) c = self.request.query_params.get('c',None) return Response({},status='200') def post(self, request, format=None): a = self.request.data.get('a',None) b = self.request.data.get('b',None) c = self.request.data.get('c',None) return Response({},status='201') Right now I am able to add description for each endpoint. and I want to add request & response schema like below and I am wondering, how to achieve this without using serializers & viewsets. -
Two foreign keys pointing to the same model but different fields
I am faced with a problem of creating a model with two of the fields pointing to (as foreign keys) to another model. Table A: class Abc(models.Model): transac_number = models.AutoField(primary_key=True, ...) transac_dt = models.DateField(auto_now=True, ...) #more field defn. Table B: class Xyz(models.Model): payt_doc = models.AutoField(primary_key=True) payt_transac_doc = models.ForeignKey(Abc, on_delete=models.SET_NULL, ..) payt_transac_dt = models.ForeignKey(Abc, on_delete=models.SET_NULL, ..) # Some more field defns... The relationship should be as under (model.field relnship): Xyz.payt_transac_doc --> Abc.transac_number Xyz.payt_transac_dt --> Abc.transac_dt Going thru' docs available at hand and SO questions, I get it that I have to use the related_key but not sure how to do it. In a form, I could achieve this, but trying out transactions in Admin, I have to remove the FK relationship for one of the fields (say, the date field). My question is: how do I create a relationship between two sets of fieds of one table with corresponding fields of another table? -
Error: 'User' object has no attribute 'get' in django-tables
My aim is to print data from database as a table. Can i do it with simple forms? views.py` from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render from .models import * class IndexView(ListView): template_name = 'Dashboard/index.html' def get_queryset(self): return ccc class CourseView(DetailView): model = Course template_name = 'Dashboard/course.html' class TeacherView(): def teacher(request): return render(request, 'Dashboard/teacher.html', {'table' : User.objects.all()}) teacher.html {% load render_table from django_tables2 %} <!doctype html> <html> <head> <title>All Teachers</title> </head> <body> {% render_table table %} </body> </html> urls.py from django.urls import path from . import views app_name = 'Dashboard' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.CourseView.as_view(), name='detail'), path('teacher/', views.User, name='teacher'), ] models.py from django.db import models class User(models.Model): unam = models.CharField(max_length=200) uid = models.AutoField(primary_key=True) umob = models.IntegerField() umail = models.EmailField() uimg = models.CharField(max_length=1000, default='null') def __str__(self): return self.unam settings.py INSTALLED_APPS = [ 'django_tables2', 'Dashboard.apps.DashboardConfig', My aim is to print data from database as a table. Can i do it with simple forms? -
django how to get old value and new value in pre_save fucntion
Image I have a model A, which has a field called name. How can I get previous value and new value in pre_save signal? @receiver(pre_save, sender=A) def signal_product_manage_latest_version_id(sender, instance, update_fields=None, **kwargs): if 'name' in update_fields: print(instance.name) This name will be the old value or the new value when I call a = A.objects.create(name="John") a.name = "Lee" a.save() -
Updating django result_list fields timezone
I have a model with a click_time field that is a DateTimeField. In my admin it is displayed as 'UTC'. My goal is to display the click_time in the admin as the logged in users timezone which is being set in user.userprofile.timezone. Currently I created a capture tag that looks like this from django import template from datetime import datetime import pytz register = template.Library() @register.simple_tag def convert_time(user_timezone, click_time): time = datetime.strptime(click_time, '%Y-%m-%d %H:%M:%S') local_tz = pytz.timezone(user_timezone) user_time = time.replace(tzinfo=pytz.utc).astimezone(local_tz) return user_time Also I have created a admin/app/change_list.html that looks like this {% extends "admin/change_list.html" %} {% load i18n admin_static admin_list %} {% load capture_tags %} {% block result_list %} {% if action_form and actions_on_top and cl.full_result_count %}{% admin_actions %}{% endif %} {% result_list cl %} {% convert_time request.user.userprofile.timezone '2018-08-08 16:01:05' %} {% if action_form and actions_on_bottom and cl.full_result_count %}{% admin_actions %}{% endif %} {% endblock %} My question is how can I apply my convert_time tag to the result_list cl? Or is there a better way to go about doing this? -
Heroku Django Database Error
So this is my first Python project and I'm trying to deploy it to Heroku. I've taken a look at quite a few questions regarding this, and I haven't found a solution regarding my exact problem. I'm receiving the following error. Exception Type: ProgrammingError Exception Value: relation "articles_cover" does not exist LINE 1: ..."profession", "articles_cover"."description" FROM "articles_... I suspect this has something to do with how I've handled the views and models within the file structure. My models are inside the app, and the app is within the overall project folder, and I'm attempting to give certain views outside of the app access to the models. This works perfectly fine locally. Here's the structure. ├───articles │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───articles(<==template tags applies to various elements in files) │ |───__pycache__ | |____models.py (<==models here) ├───assets ├───MyProject │ |───__pycache__ | |___views.py (<==models applied here) ├───media └───templates (<==template tags applied to various elements in files) So I was thinking it was a reference issue having to do with importing the models to views.py. Once again the following seems to work locally, and after looking all over Django's documentation I haven't found another way to do the following. views.py …