Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test unmanaged models using pytest-django
In my django project, I have 5 applications, with total 15 models,and all of them are unmanaged. I've written some tests in pytest-django, and when I run them, they fail due to not being able to find tables. How can I create database entries for all these models so that the tests don't fail? -
How can I implement the dash.callback_context function in django_ploty_dash environment?
I would like to know which Input is requiring the callback. This solution works well with dash. @app.callback( Output('medcode', 'value'), [Input('pie-toptenR', 'clickData'), Input('pie-toptenM', 'clickData')]) def update_medcode(clickData, clickData2): ctx = dash.callback_context if (clickData==None) & (clickData2==None): return '' else: pie = ctx.triggered[0]['prop_id'].split('.')[0] if pie == 'pie-toptenR': return clickData['points'][0]['label'] else: return clickData2['points'][0]['label'] -
ImportError: cannot import name 'UserForm' from apps.common.forms
I'm using a code for a project and the code has worked before and I can't seem to make it work. It looks like there is a problem in forms.py being not able to draw information. Other than that I'm not really sure why I'm getting this error. I have tried to work on this for quiet a long time and seems to me a fresh pair of eyes might be able to figure out the solution. Please help. Error Traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = … -
How to add scopes to explicit HTTP requests to Google Calendar API?
I am try to called the Calendar REST api using python's requests library in a django web application. I have made use of django-social-auth to login the user using Google accounts. Following the related code for requests - def index(request): if request.user.is_authenticated: social = request.user.social_auth.get(provider='google-oauth2') response = requests.get('https://www.googleapis.com/calendar/v3/users/me/calendarList', params={'access_token': social.extra_data['access_token']}) print(response.text) return render(request, 'main/index.html') I am getting the following error message in the response body - Insufficient Permission: Request had insufficient authentication scopes. I am guess we have to add a scopes variable to the request but not quite sure how to do that. -
Django URL pattern For Category > Subcategory > Sub-subcategory, and so on
I want to keep this question very simple. Can re_path be used to represent the below patterns in a single URL pattern? I'm at the juncture now where I want to add blog post slug names to the end of these patterns and that will duplicate them all which seems unweildy and just not good. urlpatterns = [ path('<slug:topic1>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/<slug:topic4>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/<slug:topic4>/<slug:topic5>/', MyView.as_view(), name='user_home'), ] I have considered getting all the topics as one long string, splitting by /, but that approach more python and less Django-best-practices. Looking for the most logical and best-practiced approach to this problem. -
Django inheritance and OneToOneField problems: Field defines a relation with model 'Dish', which is either not installed, or is abstract
I have a parent class Dish and a child Pizza (among other dish types). I am trying to make Dish abstract now, have deregistered it from admin.py, because ultimately every Dish is of some type and every Pizza is exactly one Dish (corresponds to 1 dish ID) - hence my OneToOneField logic (if that makes sense). I had Dish concrete first, but when I add class Meta: abstract = True, I get the following errors: orders.Pizza.dish: (fields.E300) Field defines a relation with model 'Dish', which is either not installed, or is abstract. orders.Pizza.dish: (fields.E307) The field orders.Pizza.dish was declared with a lazy reference to 'orders.dish', but app 'orders' doesn't provide model 'dish'. I read other SO posts suggesting I should include the app name (orders) here: dish = models.OneToOneField('orders.Dish', etc.., but that doesn't work either and besides all models are in models.py in the same app orders. Below is my code. What's the issue here? class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' PASTASALAD = 'PASTASALAD' PLATTER = 'PLATTER' TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') ) name = models.CharField(max_length=64, blank=True) # blank makes name optional type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True) size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, … -
Django unit tests - querying test database content
Can someone point me to a resource, which shows how to query a Django test Database's specific table, during a unit test? I have the following test code: from django.test import TestCase from users.models import User class DisputeAssignerTestSuite(TestCase): databases = [ 'default', 'read_replica', ] @classmethod def setUpTestData(cls): cls.users = UserFactory.create_batch(50) def test_firstOne(self): print(users) print(User.objects.all()) UserFactory code: import factory from faker import Factory import pytz from users.models import User faker = Factory.create() class UserFactory(factory.DjangoModelFactory): class Meta: model = User django_get_or_create = ('first_name', 'last_name', 'timezone', 'locale') first_name = factory.LazyAttribute(lambda _: faker.first_name()) last_name = factory.LazyAttribute(lambda _: faker.last_name()) display_name = factory.LazyAttribute(lambda _: _.first_name + " " + _.last_name) timezone = factory.LazyAttribute(lambda _: faker.timezone()) locale = factory.LazyAttribute(lambda _: faker.random_choices(elements=('en-au', 'en-us', 'de-de', 'fr-fr'), length=1)) password = factory.LazyAttribute(lambda _: faker.password(length=12)) last_login = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-60d", tzinfo=pytz.timezone(faker.timezone()))) is_superuser = factory.LazyAttribute(lambda _: faker.boolean(50)) email = factory.LazyAttribute(lambda _: faker.email()) username = factory.LazyAttribute(lambda _: _.email) is_staff = factory.LazyAttribute(lambda _: faker.boolean(50)) is_active = factory.LazyAttribute(lambda _: faker.boolean(50)) date_joined = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-1y", tzinfo=pytz.timezone(faker.timezone()))) I do not understand, how I can query User table in the test Database created by Django for this TestCase run, and e.g. verify its contents to some specific requirement (e.g. presence of users by a specific first name etc.). … -
Django ManyToMany relationship avoid duplicates
I have been thinking about this issue for two days and I cannot wrap my head around it. So let say that I have a model called "Car" that has many to many relationships with my User model "Profile" meaning in my user model (Called Profile) I have: cars = models.ManyToManyField(Cars, related_name = 'profiles') Now the car model has many to many relationships called likes so whenever a user likes a car it will be added to the likes of that car by: car.likes.add(user) Now my "Car" model will have 4 fields which are model, year, name, color The issue is I want to query the database so that I can get the number of likes for all cars with certain models and years only. Meaning regardless of the name and color I want to get the number of likes. Now I know I can get likes if all models with certain model and year by writing: def get_total_likes(self): Car.likes.through.objects.filter(car__model=self.model, car__year=self.year).count() Now imagine a scenario where a user likes a car with model=A, year=1, color=r, name=something and then they decide to like a car with model=A, year=1, color=b, name=somethingelse. How can I NOT count duplicate users when getting the total … -
'xml.etree.ElementTree.Element' object has no attribute 'META'
I want to show pandas dataframe from xml file to HTML with django Views.py def dataframe(request): import pandas as pd import xml.etree.ElementTree as et parse_data = et.parse("dataset.xml") data = parse_data.getroot() content = main.data_view(data) return render(request, 'apps/dataframe.html', content) main.py def data_view(data): df_cols = ["DOCNO", "SONG", "ARTIST", "LYRICS"] rows = [] for node in data: s_docno = node.find("DOCNO").text if node is not None else None s_song = node.find("SONG").text if node is not None else None s_artist = node.find("ARTIST").text if node is not None else None s_lyrics = node.find("LYRICS").text if node is not None else None rows.append({"DOCNO": s_docno, "SONG": s_song, "ARTIST": s_artist, "LYRICS": s_lyrics}) DataFrame = pd.DataFrame(rows, columns = df_cols) return render(data, 'apps/dataframe.html', {'DataFrame': DataFrame}) dataframe.html <table> <tr> {% for data in DataFrame %} <th>{{ data }}</th> {% endfor %} {% for i, row in DataFrame.iterrows %} <tr> {% for value in data %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tr> But the result is error message 'xml.etree.ElementTree.Element' object has no attribute 'META' How to solve this? -
Inter dependent filter api in django rest framework
I want to expose the sample dataset through a single generic HTTP API endpoint, which is capable of filtering, grouping and sorting. In this I want API to be interdependent. For eg. If I have to show the number of impressions and clicks that occurred before the 1st of June 2017, broken down by channel and country, sorted by clicks in descending order. I know how to perform singular operation in django filter by using django ORM and django rest_framework_filters but I'm completely unaware of this problem statement. Any sort of help will be appreciated. -
Django celery referencing obsolete tables
So I have this interesting issue with celery and will appreciate another set of eyes. So I have model Ark. class Ark(models.Model): name = models.CharField(max_length) title = models.CharField(max_length) So I ran migrations and ran a couple of periodic tasks using the model After sometime I made a change to the model class Ark(models.Model): name = models.CharField(max_length) # title field was removed ran migrations again, restarted celery + beat. The issue is my current tasks are failing because they I get this error that says something like column ark.title does not exist now, I didn't have any migration issues when I removed title and have also been able to create new ark objects. It is also important to note that I have DELETED all previous instances of ark objects just to be sure no old data persists. What am I missing here? -
Django allauth redirect_url_mistmatch
Hello i have A problem with django allauth. I have A site and i wanna connect Google and github login via django allauth. If i want login via google/github have error: redirect_url_mistmatch. Sorry for my bad English. -
Double users created
I have an issue with my code in the sense that when a student registers, a double instance of the student is created. I don't know what's the problem with these block of code. Please help out,also I don't know how to make a link between a teacher and a student so as to allow the teacher to add results for students. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm,UserUpdateForm ,InformationUpdateForm,InformationForm def home(request): return render(request, 'student/home.html') def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) a_form=InformationForm(request.POST) # ####and a_form.is_valid() if form.is_valid() and a_form.is_valid(): user = form.save() # form.save() #finally this get links the models, forms and views for user input and all information is registered information = a_form.save() # a_form.save() user.information.majors=a_form.cleaned_data.get('majors') user.information.department=a_form.cleaned_data.get('department') user.information.nationality=a_form.cleaned_data.get('nationality') user.information.date_of_birth=a_form.cleaned_data.get('date_of_birth') user.information.passport_number=a_form.cleaned_data.get('passport_number') user.information.phone_number=a_form.cleaned_data.get('phone_number') user.information.sex=a_form.cleaned_data.get('sex') user.save() information.save() # for this type user input is for for username,last,first and email is registered # form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() a_form = InformationForm() context={'form':form,'a_form':a_form }#,'a_form':a_form return render(request, 'student/register.html', context) @login_required def profile(request): return render(request, 'student/profile.html')#,context @login_required def profile_update(request): if request.method == 'POST': u_form=UserUpdateForm(request.POST,instance=request.user) … -
Django model showing up multiple times in queryset
I have the following Django 3.0 models: class Profile(models.Model): id = ShortUUIDField(primary_key=True, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE) class Bounty(models.Model): id = ShortUUIDField(primary_key=True, unique=True) creator = models.ForeignKey('Profile', related_name="created_bounties", on_delete=models.SET_NULL, null=True, blank=True) original_completion = models.OneToOneField('ProfileTrophy', related_name="original_bounty",on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=50) class ProfileTrophy(models.Model): id = ShortUUIDField(primary_key=True, unique=True) profile = models.ForeignKey('Profile', related_name="bounty_completions", on_delete=models.CASCADE) bounty = models.ForeignKey('Bounty', related_name="bounty_completions", on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True, blank=True) So the premise is that there are profiles, and bountys. Profiles can create bountys (stored as creators on the bounty). Profiles can complete a bounty, which is stored as a ProfileTrophy (trophy for completing the bounty) and they can complete bountys they created or bountys created by others (bounties can have many completions, but the original by the creator is stored in original_completion). The problem I'm running into is that if I have two Profiles, Bob and Jim, and Bob creates a bounty called "Bounty 1" and completes it everything is fine. If Jim then completes "Bounty 1" everything works fine, except when I call Bob.created_bounties.all() I get <QuerySet [<Bounty: Bounty 1>, <Bounty: Bounty 1>]> and queryset[0]==queryset[1]. The database shows only one bounty, and everything looks as it should. If I look at the queryset SQL of Bob.created_bounties.all() I see … -
How to call urls.py fetching a value from a loop in Django
On my index page, I have an image gallery. When someone clicks on an image, it should show more information with more photos in another page. All are loading from MySQL database using a for loop. I'm unable to get the detail of clicked image from my data base. It loads all the data This page's process is like a news website -- all the news loading from a loop. if someone clicks on a news item it should only show details about the clicked item. Below is my index.html page, my urls.py and views.py source code also. I'm using Python, Django with MySQL; all latest versions. Home page, source code of my images gallery {% for x in destination %} <!-- Destination --> <a href="destination" id="{{x.id}}"><div class="destination item" > <div class="destination_image"> <img src="{{x.img.url}}" alt=""> {% if x.offer %} <div class="spec_offer text-center"><a >Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="">{{x.name}}</a></div> <div class="destination_subtitle"><p>{{x.short_description}}</p></div> <div class="destination_price">From ${{x.price}}</div> </div> </div></a> {% endfor %} from . import views from django.urls import path urlpatterns = [ path('destination', views.destination, name='destination'), path('', views.index, name='index') ] from django.shortcuts import render from .models import Destination def destination(request): dest = Destination return render(request, 'destination.html', {'sub_destination': dest}) -
Does Django have any built in mechanisms to prevent Web Parameter Tampering in Model Formsets?
When using the model formsets provided by Django, the forms are rendered with a required ID field which is hidden. However, if you use the dev tools in any web browser, you can easily change the ID and cause that commit to affect a completely different object in the database. Looking into the form validation logic, it doesn’t look like there is a built in way to confirm ownership over these objects, and the request does not even get passed to the validation function. How can you prevent tampering of these objects? -
While resetting the password in django using built-in support it is rendering password different page
Actually i new to django framework. In my practicing, while resetting the password using built-in support, i just created the template with name of "password_reset_form.html" in templates subfolder registration folder. When i run the server it is rendering the "password_reset/done" page, but showing with different content. but my "password-reset_done.html" content is different so please reffer the below snippet of password-reset_done.html. Here is the snippet of password-reset_done.html. {% extends 'base.html' %} {% block content %} <div class="row justify-content-center"> <div class="col-8"> <h2>Reset your password</h2> <p>We've emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.</p> <p>If you don't receive an email, please make sure you've entered the address you registered with, and check your spam folder.</p> </div> </div> {% endblock %} Here is the pic of rendering with different content. Here is the template of login {% extends 'base.html' %} {% load static %} {% block head %} <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" name="viewport"> <title>password change</title> <!-- General CSS Files --> <link rel="stylesheet" href="{% static '\css\app.min.css'%}"> <!-- Template CSS --> <link rel="stylesheet" href="{% static '\css\style.css'%}"> <link rel="stylesheet" href="{% static '\css\components.css'%}"> <!-- Custom style CSS --> <link rel="stylesheet" href="{% static … -
Cookie not sent when with request
I am pretty new to web development with API. So I have a function that send a request to the server with the code below. It get sent along with a token that I store in cookie. var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); myHeaders.append("Content-Type", "text/plain"); var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}"; var requestOptions = { method: 'POST', headers: myHeaders, body: raw, redirect: 'follow', credentials: 'include', }; fetch("http://127.0.0.1:8000/logs/log/", requestOptions) .then(response => response.json()) .then(result => console.log(result)) .catch(error => console.log('error', error)); However, I keep getting this error when I try to send it. https://i.stack.imgur.com/StU0q.png After a bit digging, I notice that my cookie is not being sent with the request (as shown by the picture below). This is pretty odd to me because I set "credentials" to "include" in the requestOptions. https://i.stack.imgur.com/Hp1mi.png However, when I comment out lines that append "Content-Type" to header so that the header becomes empty. The cookie is included in the header again, along with other headers that were not included in the first place. var myHeaders = new Headers(); // myHeaders.append("Content-Type", "application/json"); // myHeaders.append("Content-Type", "text/plain"); var raw = "{\n \"latitude\": \"69.23489236336972000\",\n \"longitude\": \"-69.08944702148439000\",\n \"log_start\": \"2020-05-03T09:37:41Z\",\n \"log_end\": \"2020-05-03T10:00:00Z\"\n}"; var requestOptions = { … -
How to get the private key of an object (from views.py) whose DetailView we are in?
I have 2 models: Patient and Location. Locations are connected to Patients 1-to-1. When a user goes into a PatientDetailView for a specific patient, he can query for the locations with same names between patients. The user is choosing the query location from a dropdown menu. Currently, the dropdown menu shows all the Location objects but I want to show only the locations connected to this specific patient whose DetailView we are in. Basically, I want this line to query locations which are connected to the patient whose DetailView we are in. queryset=Location.objects.all().order_by('location_name') View def profile_search(request,pk): if request.method == 'POST': query_form = QueryForm(request.POST) if query_form.is_valid(): model=Location location = query_form.cleaned_data['location'] location_str = str(location).split(',')[0] period = query_form.cleaned_data['period'] entry_list = list(Location.objects.all()) return_dict = {} for i in range(len(entry_list)): if location_str == entry_list[i].location_name and \ location.patient.idn != entry_list[i].patient.idn: print('match') return render(request, 'covidapp/query_page.html',{'return_dict':return_dict, 'query_form':query_form}) else: query_form = QueryForm() return render(request, 'covidapp/query_page.html',{'query_form':query_form}) Form: class QueryForm(forms.Form): period = forms.IntegerField() location = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) Models: class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, … -
Join queryes of ManyToMany Models on Django
I have to merge the all bands that all persons are in. here is the Models: class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, blank=True, null=True) aka = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) birthday = models.DateField(blank=True, null=True) birth_place = models.CharField(max_length=80, blank=True, null=True) photo = models.ImageField(blank=True, null=True) location = models.CharField(max_length=80, blank=True, null=True) gender_choices = [ ('m', 'Male'), ('f', 'Female'), ('u', 'Unknown'), ] gender = models.CharField(max_length=1 ,choices=gender_choices, default='u') class Band(models.Model): name = models.CharField(max_length=100) past_names = models.CharField(max_length=180 , blank=True, null=True) bio = models.TextField(blank=True, null=True) origin_country = models.CharField(max_length=30 , blank=True, null=True) location = models.CharField(max_length=80 , blank=True, null=True) formed_in = models.IntegerField(blank=True, null=True) genre = models.CharField(max_length=80, blank=True, null=True) themes = models.CharField(max_length=80, blank=True, null=True) members = models.ManyToManyField(Person) Since one person can have multiple bands, and a band can have multiple members, I assume it's rigth to create a ManyToMany relation with Person model on Band model Of course a relation table is created, but how I use this table on View assuming I whant make a query similar to this: select person.*, band.* from person inner join band_members on band_members.person_id = person.id inner join band_band on band.id = band_members.band_id order by band_person.id Rith now, my view have a query listing all perons, and a simpler … -
Python 3 venv interpreter not available
I am following this Django App Documentation and I ran into this error from models.py Error: Unable to import 'django.db' models.py code below from django.db import models I am new to python and django so I followed the following steps in creating the app for python 3. STEPS: Followed this video to change the PATH of Python 3. In the cmd I ran the following: >python --version [ RESULT: Python 3.8.2 ] >python -m venv polling-website >Scripts/activate [Successfully activated] >py -m pip install Django [Django version 3.0.6] >django-admin startproject mysite >python manage.py migrate >python manage.py startapp polls >py manage.py runserver I was able to activate the virtual environment and the django server ran successfully. I noticed that the virtual environment I made for the project cannot be identified by the Command Palette when I use Python: Select Interpreter command. Image of command palette with no venv option How will I be able to make the venv interpreter appear? What mistake was made in installing the Django App? Thanks in advance. -
Django Rest Framework Custom Register View (RegisterView) failing to return token + user data
I'm using allauth and rest_auth in my django rest framework app. When registering an user a token (key) is returned, what I'm trying to achieve is to return the token + user data after registration. To do so I've the following serializer: from rest_framework import serializers from rest_framework.response import Response from allauth.account import app_settings as allauth_settings from allauth.utils import email_address_exists from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from kofiapi.api.users.models import User, UserProfile from rest_framework.authtoken.models import Token from rest_auth.models import TokenModel class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('dob', 'phone', 'receive_newsletter') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create_token(self, user): token, created = Token.objects.get_or_create(user=user) return token def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token = self.create_token(user) UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.name) instance.save() profile.dob = profile_data.get('dob', profile.dob) profile.phone = profile_data.get('phone', profile.phone) profile.receive_newsletter = profile_data.get('receive_newsletter', profile.receive_newsletter) profile.save() return instance class TokenSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = TokenModel fields = ('key', 'user') def get_user(self, instance): request = self.context.get('request') serializer_context = { 'request': … -
How to link each title to an Image in Django
Hi I've been thinking about how to ask the right question to get the right answer. I am making a project where users upload images as posts in one phase . Next I want to change these posts to items in another models what is the steps I need to follow In App No. 1 called score. Users/designers can upload several images and that's the role of this model only. In another app called Core, I have a class in a model called item which from it I can post these images from the admin. I want to be able to select the name of the user Select the required title which is shortlisted to the selected user only The image related to the title which was previously uploaded (from the 1st app called CORE) to be selected (instead of uploading it one more time ). I am trying to simplify it as much as possible so if you have any questions please ask Here is the 1st model for Score where designers can upload images: class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def … -
Any better way to queryset objects from one app to another in wagtail/django?
I have a home app with HomePage model which gets object from BlogPage model in blog app. I use this code below the obtain the object from BlogPage to HomePage. blog app class HomePage(Page): primary_header = models.CharField(max_length=100, blank=True,) secondary_header = models.CharField(max_length=100, blank=True,) hero_banner_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+') def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) # Get object from Blog Page blogpages = self.get_children().get(title='Blog Page').get_children().live().public().order_by('-first_published_at') context['blogpages'] = blogpages return context I used get() to obtain the object by title, but I feel that it may not be the best way to do it. If I were to rename the BlogPage title field to for example, "The Blog Page", it will break the code since 'Blog Page' is no more used. Is there a better way to queryset from BlogPage to HomePage model? home app class BlogPage(Page): subpage_types = ['PostPage'] def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) category_slug = request.GET.get('category', None) context['categories'] = BlogCategory.objects.all() return context -
django-storages media file could not be retrieved by url
I'm using Django and django-storage with dropbox to store media files. my model is class MyModel(models.Model): pdf_file = models.FileField(upload_to='file/%Y/%m/%d', blank=False) But when I access the url like obj = MyModel.objects.get(...) obj.pdf_file.url `` It gives error like dropbox.exceptions.ApiError: ApiError('ff7d53ab72d6faead1b54b58d0f11343', GetTemporaryLinkError('path', LookupError('not_found', None))) Accessing the file from admin panel is working fine.