Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django social-auth (vk)
Backend: Django with Django Rest Fraemwork Frontend: Angular 2 I didn't have much trouble setting up oauth2 authorization and registration using "Django OAuth Toolkit" (docs) But I have problems with social authentication (vk). I use social-auth-app-django (docs). Set up vk application using api docs, set redirect_uri (http://localhost:8000/.../social/complete/vk-oauth2/). My Django config file: AUTHENTICATION_BACKENDS = ( 'social_core.backends.vk.VKOAuth2', 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) # keys from vk registered app SOCIAL_AUTH_VK_OAUTH2_KEY = '...' SOCIAL_AUTH_VK_OAUTH2_SECRET = '...' SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_VK_OAUTH2_SCOPE = ['email'] NEW_USER_REDIRECT_URL = '/my/profile' LOGIN_URL = "/my/profile" And I add url('', include('social_django.urls', namespace='social')) to my urlpatterns. After that I send request to http://localhost:8000/.../social/login/vk-oauth2 from angular, and everything is going well: - browser redirects to https://oauth.vk.com/authorize. - I log in to vk and give access to my page. - browser redirects to http://localhost:8000/.../my/profile, and I get 401. But in database appears new user, token for him and so on. I'd appreciate any help. -
Query all objects belonging to user
I have the following two models (only included their relationship to each other). This is a job board site, a business owner can create one or more Business objects (on the off chance they own more than one small business) and then post as many Job objects as they please. class Business(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Job(models.Model): business = models.ForeignKey(Business, on_delete= models.CASCADE) How can I get all Job objects belonging to a User? I know I can get all Job objects belonging to a Business but a user can create multiple businesses. I know I have to build some kind of chain filter, I am just not sure how to go about that. Edit: I am trying to achieve this so I can display all of a user's posts in a dashboard type of view. -
Filtering models based off of the concatenation of a field on a one to many relationship in django
Say I had some models defined as such: Class Document(models.Model): pass Class Paragraph(models.Model): text = models.CharField(max_length=2000) document = models.ForeignKey(Document, related_name="paragraphs") And I wanted to find all of the Documents that have the word "foo" contained in any of their paragraphs text fields. Something like: Document.objects.annotate(text=[Concatenation of all paragraphs text]).filter(text__icontains='foo') How would I go about this in a Django way, not writing direct SQL queries. -
Speed up SQL to dictionary in python
How can I speed up the creation of a dictionary form SQL query: After running a django query on which connects few tables which are one to many I get a lot of repeated data which I want to transform in a nice json format. [ {'id':1, 'version':1, 'key3':'something different'}, {'id':1, 'version':1, 'key3':'something different'}, {'id':1, 'version':1, 'key3':'something different'}, {'id':2, 'version':1, 'key3':'something different'}, {'id':2, 'version':1, 'key3':'something different'}, {'id':3, 'version':1, 'key3':'something different'}, ] I wanna build it to look like so: { '1':{ 'version':1, 'key':['something different', 'something different', 'something different'] }, '2':{ 'version':1, 'key':['something different', 'something different'] }, '3':{ 'version':1, 'key':['something different'] } } The function I have right now takes about 1s for about 2000 formatted records, from about 8000 SQL records. My function is something like def func(data): new_dict = {} for d in data: id = d['id'] if id not in new_dict: new_dict[id]['version'] = d['version'] new_dict[id]['key'] = [] new_dict[id]['key'].append(d['key']) return new_dict Resulting dictionary does not need to be exact match the one I designed, I can modify displaying function to match dictionary. -
Django and navigator.serviceWorker.register is working only localhost
In my project I have such line of code navigator.serviceWorker.register('{% static "js/firebase-messaging-sw.js" %}') But if I launch my project not on localhost, I got an error Uncaught TypeError: Cannot read property 'register' of undefined -
Sending Asynchronous Mail in Django - without writing to database?
I'm looking to speed up loading time for my website by sending my mail asynchronously. Currently, my code looks something like this: def myFunction(content): result = modify(content) send_mail('My Subject', result, 'me@example.com') return render(request, 'page.html', result) Using Django-Mailer, I've figured out that I can cut loading time by writing the email to the database instead of sending it immediately, then having cron + Django mailer work through the emails in my database asynchronously. However, I like to keep my database as free from potentially sensitive information as possible, and would like to avoid writing any of the emails sent through my app to my database. Even if the data is just being written for a short time, with automatic backups there's a possibility something might be saved. I understand if there's no solution here, but is there a way to send emails asynchronously without every writing them to a database? I really don't think this is possible, but my ideal hope would be if there was a way to return the response, and then send the email. def myFunction(content): result = modify(content) return render(request, 'page.html', result) send_mail('My Subject', result, 'me@example.com') -
django widget tweaks form control not action
when Making django board, I met the problem. django version is 3. I wanted form like this. but my code can't alert me "This field is required" But widget tweaks form-control wasn't working. which part is problem? My code is like this {% extends 'base.html' %} {% load widget_tweaks %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted"> {{ field.help_text }} </small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} -
NOT NULL constraint failed: users_details.user_id
I've tried to add another details form that have address and birth date on my registration form page. Every time i tried to sign up i get the NOT NULL constraint failed error. models.py class Details(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=60, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) views.py def register(request): if request.method == 'POST': r_form = UserRegisterForm(request.POST) o_form = DetailsForm(request.POST) if r_form.is_valid and o_form.is_valid(): r_form.save() o_form.save() username = r_form.cleaned_data.get('username') messages.success(request, f'Your account has been created!') return redirect('login') else: r_form = UserRegisterForm() o_form = DetailsForm() context = { 'r_form' : r_form, 'o_form' : o_form } return render(request, 'users/register.html', context) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email','password1', 'password2'] class DetailsForm(forms.ModelForm): address = forms.CharField() birth_date = forms.DateField() class Meta: model = Details fields = ['address', 'birth_date'] ERROR -
django email, customize helo parameter
I am using django email to send emails in the following manner: email = EmailMessage( 'Object', 'body', my_from_addr, args.emails, [], reply_to=['my_from_addr'], #ehlo=settings.EMAIL_HELO, ) I need to set the helo/ehlo parameter to comply with the email server, I didn't found a variable django uses, is there any good way of doing so? -
Parsing an activation_key in url patter
anyone who knows how i can parse an activation key for an email_activation_view in django 2.2 , I have tried as below but am getting a 404: path('accounts/activate/<activation_key>\w+/$', accounts_views.ActivationView, name='activate') Test url: http://127.0.0.1:8000/accounts/activate/jkhkgjklhfdrtiufyrcd -
Fullcalendar Event save on click - Django
I suppose that this is pretty simple to someone who knows JavaScript, but I just can't figure it out on my own. I've implemented FullCalendar into my Django application, and what I want is simple Event save on users click(saving events to the database after user's action, after the click release and drawn event). I can add an event using Django form, and have no problem with that, but I want to save the event on click, as I said before. So the user clicks on the desired time, draw the event 'bubble' and let the click off. So when that event is drawn, it needs to be saved directly to the database or passed to the Django form. I don't have much experience in JS so please don't mind me. Thank you in advance. PS: I repeat, everything works fine, I can add an event, delete it, etc, but only with my form. Let's start with the zakazi.html (page where all the events are created) : {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block title %} Zakaži {% endblock title %} {% block content_row %} <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> … -
How to implement a custom detail serializer on django-rest-auth and serialize it
I want to create a profile user when an instance of user is created, i get it but when i run the server it gives me TypeError saying that "NoneType" object is not iterable, i created a post_save signal in UserProfile model: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() my UserProfile model is: class UserProfile(TimeStampedModel): MALE = 'M' FEMALE = 'F' NOT_SPECIFIED = 'NS' GENDER_CHOICES = ( (MALE, _('Male')), (FEMALE, _('Female')), (NOT_SPECIFIED, _('Not specified')) ) VALIDATOR = [validators.RegexValidator(re.compile('^[\w]+$'), _('Only can has letters'), 'invalid')] user_profile_id = models.AutoField(primary_key=True) user = models.OneToOneField(auth_user, verbose_name=_('user'), blank=False, null=False, on_delete=models.CASCADE, related_name='profile') first_name = models.CharField(max_length=125, verbose_name=_('first name'), validators=VALIDATOR, blank=True, null=False) last_name = models.CharField(max_length=125, verbose_name=_('last name'), validators=VALIDATOR, blank=True, null=False) location = models.ForeignKey(Locations, on_delete=models.DO_NOTHING, verbose_name=_('location'), related_name='location', blank=True, null=True) profile_image = models.ImageField(verbose_name=_('profile image'), null=True) gender = models.CharField(verbose_name=_('gender'), max_length=2, choices=GENDER_CHOICES, blank=True, null=True, default=NOT_SPECIFIED) DOB = models.DateField(verbose_name=_('date of birth'), blank=True, null=True) occupation = models.TextField(verbose_name=_('occupation'), blank=True, null=False) about = models.TextField(verbose_name=_('about'), blank=True, null=False) I'm using django-rest-framework, django-rest-auth and django-allauth. It's my UserProfileSerializer: class UserProfileSerializer(UserDetailsSerializer): # profile_image = ImageSerializer() user = UserSerializer(source='profile', many=True) class Meta: model = UserProfile fields = '__all__' read_only_fields = ('created_at', 'updated_at',) def update(self, instance, validated_data): instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', … -
DJANGO Install application on runtime
I have an application which is made of several apps. The thing is that by default, only 1 app is installed. I called it 'base'. This base app enable the user to manage users, groups (but that isn't the point here) AND should enable users to install other apps on runtime (that is the point). I created an Application model. In my UI, I list all the applications with a button install aside of it. The idea is, when I click on this button, to : Mark the application as installed Add it to the App registry on runtime (that's the blocking point) Apply the migration for this app So here are some samples of code : My Application model : from django.apps import apps from django.conf import settings from django.core import management from django.db import models class Application(models.Model): class Meta: db_table = 'base_application' name = models.CharField(max_length=255, unique=True) verbose_name = models.CharField(max_length=255) version = models.CharField(max_length=255, null=True, blank=True) summary = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) is_installed = models.BooleanField(default=False) is_uninstallable = models.BooleanField() My install() method would look like : I know there are mistakes in it and that is the point of this question. I don't understand how the App Registry actually works. … -
django - CBV - pass in multiple values from url
I am utterly confused and mortified by CBVs, seeking for help. So I've designed the model structure and decided the url patterns as following, but simply can't write a valid CBV to facilitate the urls: models.py class Category(models.Model): '''Category for men's and women's items''' men = models.BooleanField() women = models.BooleanField() name = models.CharField(max_length=100) description = models.CharField(max_length=300, blank=True) uploaded_date = models.DateTimeField( auto_now_add=True, null=True, blank=True) class Meta(): verbose_name_plural = 'Categories' def __str__(self): return ("Men's " + self.name) if self.men else ("Women's " + self.name) class SubCategory(models.Model): '''Sub-category for the categories (not mandatory)''' category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=300, blank=True) uploaded_date = models.DateTimeField( auto_now_add=True, null=True, blank=True) class Meta(): verbose_name = 'Sub-category' verbose_name_plural = 'Sub-categories' def __str__(self): return ("Men's " + self.name) if self.category.men else ("Women's " + self.name) class Item(models.Model): '''Each item represents a product''' category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100) description = models.TextField(blank=True) price = models.IntegerField(default='0') discount = models.IntegerField(null=True, blank=True) uploaded_date = models.DateTimeField( auto_now_add=True, null=True, blank=True) class Meta: ordering = ['-uploaded_date'] def __str__(self): return self.name def discounted_price(self): '''to calculate the price after discount''' return int(self.price * (100 - self.discount) * 0.01) class ItemImage(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) image = models.ImageField(upload_to='itemimages', … -
Vue PWA login works in dev but returns 401 in production
I have a Vue.js PWA with a Django Rest Framework backend which works correctly locally on my laptop (using a browser). When I deploy it to production it continues to work correctly when I log in using a browser, however it fails to login when opened as a PWA (ie: on a phone or a PWA saved in a browser). Here's my login code: axios .post("/api/get-token/", user) .then(res => { localStorage.setItem('user-token', res.data.token); axios.defaults.headers.common['Authorization'] = res.data.token; commit(AUTH_SUCCESS, res.data); resolve(res); }) .catch(err => { commit(AUTH_ERROR, err); reject(err); }); As mentioned, everything works locally and in production when logging in via a browser. The problem comes when trying to log in using the PWA. When trying to login to the PWA, I get the following: POST https://www.example.com/api/get-token/ 401 (Unauthorized) Doing a console log of the error received from the server I get: { detail: "Invalid token header. No credentials provided." __proto__: Object status: 401 statusText: "Unauthorized" headers: {allow: "POST, OPTIONS", connection: "keep-alive", content-length: "59", content-type: "application/json", date: "Thu, 06 Feb 2020 15:00:11 GMT", …} config: url: "/api/get-token/" method: "post" data: "{"username":"test@example.com","password":"password"}" headers: Accept: "application/json, text/plain, */*" Authorization: "Token " Content-Type: "application/json;charset=utf-8" __proto__: Object transformRequest: [ƒ] transformResponse: [ƒ] timeout: 0 adapter: ƒ (t) xsrfCookieName: … -
Implementing a Django templatetag aware of instances of itself in extended templates
I've started working on a Django templatetag that takes a set of parameters and builds a list. It sets context variables to output that list after some tweaking. I would like to output that list in the base template of my project. base.html {% load mytemplatetag %} {% mytemplatetag 'foo' 'bar' %} <!DOCTYPE html> <html> <head> </head> <body> {{ mytemplatetag_output }} </body> </html> After rendering the base view the output should be something like: foo bar I would like my templatetag to be aware when used in derived templates: view.html {% extends 'private/base.html' %} {% load mytemplatetag %} {% mytemplatetag 'foo' 'baz' %} After rendering the new view the output should be something like: foo bar baz At the moment my implementation is somewhat similar to the following code: mytemplatetag.py from django import template register = template.Library() @register.tag def mytemplatetag(parser, token): paramters = token.split_contents() tag_name = paramters[0] items = paramters[1:] for item in items: if not (item[0] == item[-1] and item[0] in ('"', "'")): raise template.TemplateSyntaxError( "%r tag's argument should be in quotes" % tag_name ) items = [m[1:-1] for m in items] return MyTemlpateTagNode(items) class MyTemlpateTagNode(template.Node): def __init__(self, items): self.items = unique(sort(items)) def render(self, context): context['mytemplatetag_output'] = '\n'.join(self.items) return … -
How to setup django db in conftest so that each test case will run under the setup in the conftest
I would like to run test cases under django db without using reuse-db flag. I plan to use -no-migrations flag plus conftest setup to make sure my tests cases run in a correct test db set up. I have some sample like this in conftest.py I planned to use, def setup_django_test_db(db): schemas = ['test1', 'test2', 'test3'] with db.connection.cursor() as cursor: for schema in schemas: cursor.execute(f"create schema {schema}") cursor.commit() My test cases rely on these schema. But this code doesn't really work when I actually run all tests. It still raise me schema doesn't exsits error. Can someone help me out if I am missing something while set up the test db? Or is there any way to do things like pytest.mark.django_use("schema_name") to decorate the test case so that that test can run with specific schema name. And how can I wrap up the customized marker with the schema setup? Thanks in advance! -
m2m table not changing column name after model name change
I just switched out the django User model for a CustomUser model. I've got a field called contributor_id in a Project model which is a m2m field connected to the User model. I've told the m2m field to point to the CustomUser model and have run makemigrations and migrate but the user_id field has not changed to customuser_id. This is causing the following error: Unknown column 'projects_project_contributor_id.customuser_id' in 'field list' I found these bug reports: bug1 and bug2 but they both appear to have been fixed in 2.0. Obviously I can just run an alter table query on my database, but I don't know if: a) There's away to get the django orm to do the change, and b) if altering the tables directly will get my migrations out of wack. -
Error with wsgi.py while deploying django app on cpanel
I am trying to deploy my django app on cpanel and keep encountering this error message when I run python manage.py migrate SyntaxError: invalid syntax (gradboost:3.7)[thegqvow@server232 gradboost]$ python manage.py migrate File "manage.py", line 8 def passenger_wsgi.py(environ, start_response): This is what I have in my python setup app on cpanel Application root: public_html/gradboost Application startup file: manage.py Application Entry point: passenger_wsgi.py and this is what I have in passenger_wsgi.py import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'manage.py') application = wsgi.passenger_wsgi.py and this is the structure of my app public_html -->gradboost >>manage.py >>passenger_wsgi.py -
Django password reset page loading issue
I have implemented Forgot Password functionality in my web Blog. I have used Django and my gmail account as mailbox. I tried both the settings in my gmail account by enabling less secure apps/2 step authentications. Blog Flow: User Signup (by providing email id) --> Login (If Forgot Password --> get password reset link on email) --> Home Page Now the issue is, After giving email id for password reset i am not getting success page. My web page is keep loading, even neither getting the email nor error. Following are the codes: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/home' LOGIN_URL = '/login' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('',include("users.urls")), path('login/',auth_views.LoginView.as_view(template_name = 'users/login.html'), name = 'login'), path('logout/',auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name = 'logout'), path('password-reset/',auth_views.PasswordResetView.as_view(template_name = 'users/password_reset.html'), name = 'password_reset'), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name = 'users/password_reset_done.html'), name = 'password_reset_done'), path('password-reset-confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name = 'users/password_reset_confirm.html'), name = 'password_reset_confirm'), ] urlpatterns += [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) password_reset.html {% extends "users/base.html" … -
API value in range?
I'm new to django and to python. I'm trying to re-create an air condition app in django. Due to the fact my APIs haven't a good, moderate etc. condition I would like to set a range for the number.. Example: 50-100 = GOOD 100-200 = moderate etc. I was trying to do something like: {% if api.data.aqi in range(0, 50)) %} <p>Good</p> {% elif api.data.aqi in range(50, 100) %} <p>Moderate</p> But of course I get an error. Is there anyone who can help me? -
How do I properly pass form.errors after an invalid form submission
I have created a registration view where I want ValidationError(s) to be displayed after a form is submitted but it happens to be invalid form.is_valid() == False. ChefRegisterationForm is a subclass of UserCreationForm. If the form is valid, a flash message will do. With what I have, it gets the job done, but there has to be a cleaner way than having two render statements in the view. How could this be refactored so that there is only one render statement? def register_chef(request): if request.method == 'POST': new_user_form = ChefRegisterationForm(request.POST) if new_user_form.is_valid(): user = new_user_form.save() login(request, user) messages.info( request, f"Logged in: {user}!" ) return HttpResponseRedirect(reverse("menu:menu_list")) return render(request, 'chef/register_chef.html', {'form': new_user_form}) new_user_form = ChefRegisterationForm() return render(request, 'chef/register_chef.html', {'form': new_user_form}) {% extends 'index.html '%} {% block content %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} {% endfor %} {% endif %} <form action="{% url 'chef:register' %}" method="post"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <button>Register</button> </form> {% for key in form.errors %} {{ key }} {% endfor %} {% endblock %} -
How do you add existing objects to a ManyToMany field using Serializer?
I am trying to create an API with Artists and Songs, with a ManyToMany relationship between the two. Using the API to create a Song with an Artist that is not in the database works fine. The problem arises when I attempt to use the POST method to create a new Song with an Artist that already exists in the database. I tried overwriting the SongSerializer create() method using get_or_create() based on another post here, but I kept getting Bad Request errors when the Artist already exists in the database. The relevant code snippets: models.py class Artist(models.Model): artist_name = models.CharField(max_length=200, unique=True) class Meta: ordering = ['artist_name'] def __str__(self): return self.artist_name class Song(models.Model): song_title = models.CharField(max_length=200) artists = models.ManyToManyField(Artist, related_name='songs') class Meta: ordering = ['song_title'] def __str__(self): return self.song_title serializers.py class ArtistNameSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ('artist_name',) def to_representation(self, value): return value.artist_name class SongTitleSerializer(serializers.ModelSerializer): songs = serializers.PrimaryKeyRelatedField(read_only=True, many=True) def to_representation(self, value): return value.song_title class Meta: model = Song fields = ('songs',) class ArtistSerializer(serializers.HyperlinkedModelSerializer): songs = SongTitleSerializer(read_only=True, many=True) class Meta: model = Artist fields = ('id', 'artist_name', 'songs') class SongSerializer(serializers.HyperlinkedModelSerializer): artists = ArtistNameSerializer(many=True) class Meta: model = Song fields = ('id', 'song_title', 'artists',) def create(self, validated_data): artist_data = validated_data.pop('artists') … -
Load static files in Django Admin panel using Python in CPanel
I have already set up a Django Python application in my server with CPanel. The wsgi is correctly configured, the index.html (which doesn't have any css) runs properly but the admin panel doesn't load correctly the css. I have been reading that I need to properly set the static files routes and none of this seems to work. My settings.py file have the static directive in the installed apps and this lines at the end, where my static files of the python virtualenv is. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') #after collect static is run all the static files will be put in this folder STATICFILES_DIRS = (['/home/djangouser/virtualenv/api/3.5/lib/python3.5/site-packages/django/contrib/admin/static/admin/']) I have tried restaring the application but none of this work and my admin page still loading without css. My index.html doesn't have any css so I don't know if this is only a problem of the admin... But I need to fix this up. Thank you. -
Dynamically write django filters
I have a Django filters for couple of models. but they both have same filtering how to make it DRY. class TestFilter(django_filters.FilterSet): field_list = Test._meta.get_fields() for field in field_list: field_name = (field.__str__().split('.'))[-1] if type(field) is model.CharField: field_name__contains = field_name + '__contains' vars()[field_name] = django_filters.CharField(field_name=field_name, lookup_expr='iexact') vars()[field_name] = django_filters.CharField(field_name=field_name, lookup_expr='icontains') class Meta: model = Test fields = '__all__' class Test2Filter(django_filters.FilterSet): field_list = Test2._meta.get_fields() for field in field_list: field_name = (field.__str__().split('.'))[-1] if type(field) is model.CharField: field_name__contains = field_name + '__contains' vars()[field_name] = django_filters.CharField(field_name=field_name, lookup_expr='iexact') vars()[field_name] = django_filters.CharField(field_name=field_name, lookup_expr='icontains') class Meta: model = Test2 fields = '__all__' both classes have same code. I tried to move code part in utils like generic_filter function and import the function to filters file but filters are not working.