Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If i am trying to create a diray app using django, how can i get it show show me different diary entries based on the current logged in user?
im currently in the process of building a diary app in django. I have created multiple users (e.g User A and User B). However, when user A logs in, user A can see User B's entries. How can i lock it down, so only User B can see User B's entries and when User A logs in, User A can have a personal entry view? (do i need to create a different view?) views.py for my diary app: from django.urls import reverse_lazy from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView, ) from .models import Entry from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect # Create your views here. class ELV(ListView): model = Entry queryset = Entry.objects.all().order_by("-date_created") #takes all the entries and orders it by date template_name = 'entries\entry_list.html' class EDV(DetailView): model = Entry template_name = 'entries\entry_detail.html' class ECV(CreateView): model = Entry fields = ["title", "content"] success_url = reverse_lazy("entry-list") template_name = 'entries\entry_form.html' class EUV(UpdateView): model = Entry fields = ["title", "content"] template_name = 'entries\entry_update_form.html' def get_success_url(self): return reverse_lazy( "entry-detail", kwargs={"pk": self.object.pk} ) class EntryDeleteView(DeleteView): model = Entry success_url = reverse_lazy("entry-list") template_name = 'entries\entry_delete.html' Does it have anything to do with user sessions? - i'm not sure, please help! -
How to deploy django backend from subfolder of github repository in Railway?
I have created a project where I have my django backend and nextjs frontend in the same repository in different folders, I want to know if there is a way to deply my django backend from its subfolder and not have to make a separate repository for my backend. I put my requirements.txt, runtime.txt and Procfile in the root folder and made the Procfile point to backend.myblog.wsgi but it didn't work. -
NOT NULL constraint failed:
I am creating a website where people under the topics set by the administrator will be able to make their entries. Each record is linked to a user account, but when creating a new record, an error appears - NOT NULL constraint failed: menu_description.topic_id menu/views.py from django.shortcuts import render, redirect from .models import Topic, Description from .forms import DescriptionForm from django.contrib.auth.decorators import login_required def index(request): topic = Topic.objects.all context = {'topic': topic} return render(request, 'Menu/Menu.html', context) @login_required def description(request, topic_id): topic = Topic.objects.get(id=topic_id) description = topic.description_set.filter(owner=request.user).order_by('date_added') context = {'description': description, 'topic': topic} return render(request, 'Menu/Description.html', context) @login_required def new_description(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = DescriptionForm() else: form = DescriptionForm(data=request.POST) if form.is_valid(): new_description = form.save(commit=False) new_description.owner = request.user new_description.save() return redirect('description', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'Menu/new_description.html', context) @login_required def edit_description(request, entry_id): description = Description.objects.get(id=entry_id) topic = description.topic if request.method != 'POST': form = DescriptionForm(instance=description) else: form = DescriptionForm(instance=description, data=request.POST) if form.is_valid(): form.save() return redirect('description', topic_id=topic.id) context = {'description': description, 'topic': topic, 'form': form} return render(request, 'Menu/Edit_description.html', context) @login_required def delete_description(request, description_id): description = Description.objects.get(id=description_id) topic = description.topic description.delete() return redirect('description', topic_id=topic.id) my code fsdfsfdsfsfas sdfsadklnfajsnflksanfgiljsglidsehseoigusdhoigusdfhoigsdhoigudsfhgoidsfhgokjfdshdsoiughsodfighosidhgosidfghsdoiughdfoigushdfiogsfdhikg menu/models.py from django.db import models from … -
Django ModelForm `fields_for_model` references `_default_manager`, which is None
I am working on a Django project using standard models and ModelForms. I have the following models and forms: # models.py class ApplicationCore(TimestampedModel): user = models.ForeignKey(User, related_name="applications", on_delete=models.PROTECT) organization = models.ForeignKey(Organization, related_name="applications", on_delete=models.PROTECT) overall_status = models.TextField(choices=ApplicationOverallStatus.choices, default=ApplicationOverallStatus.in_progress.value) class Meta: abstract = True ... class Application(ApplicationCore): applicant = models.OneToOneField(ApplicantInformation, null=True, on_delete=models.PROTECT) item_one = models.OneToOneField(ApplicationItemOne, null=True, on_delete=models.PROTECT) item_two = models.OneToOneField(ApplicationItemTwo, null=True, on_delete=models.PROTECT) ... class ApplicationItemOne(ApplicationItemCore): choice = models.TextField(choices=ApplicationItemOneChoice.choices, null=True, blank=True) co_applicants = models.ForeignKey(ApplicantInformation, null=True, related_name="item_ones", on_delete=models.PROTECT) # forms.py class ApplicationForm(forms.ModelForm): has_item_one = False has_item_two = False def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.has_item_one = self.instance.item_one_id is not None self.has_item_two = self.instance.item_two_id is not None class Meta: model = Application fields = ('applicant',) class ApplicationItemOneForm(forms.ModelForm): class Meta: model = ApplicationItemOne fields = '__all__' When I try to run any Django command e.g. python manage.py makemigrations I get the following error: File "/home/noah/dev/github/silica/silica-docs/django/sample-app/application/urls.py", line 5, in \<module\> from application import views File "/home/noah/dev/github/silica/silica-docs/django/sample-app/application/views.py", line 7, in \<module\> from application.forms import CreateApplicationForm File "/home/noah/dev/github/silica/silica-docs/django/sample-app/application/forms.py", line 19, in \<module\> class ApplicationForm(forms.ModelForm): File "/home/noah/.virtualenvs/sample-app/lib/python3.8/site-packages/django/forms/models.py", line 261, in __new__ fields = fields_for_model( File "/home/noah/.virtualenvs/sample-app/lib/python3.8/site-packages/django/forms/models.py", line 183, in fields_for_model formfield = f.formfield(\*\*kwargs) File "/home/noah/.virtualenvs/sample-app/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1060, in formfield return super().formfield(\*\*kwargs) File "/home/noah/.virtualenvs/sample-app/lib/python3.8/site-packages/django/db/models/fields/related.py", line 991, in formfield 'queryset': self.remote_field.model.\_default_manager.using(using), AttributeError: … -
How to use Selenium and django test case
I'm a newbie in the use of Selenium. And I got a problem using it. If I understand correctly, when I run my test suite (./manage.py test), django will create a new database for run the test suite. But if I include Selenium test in those test suite, it seems that Selenium connect to my server and access to my real database, which make my test failed. What I'm trying to do is either be able to use the real database with django test or be able to use test database with Selenium. Is there a solution to my problem ? -
Add stylings to a django email template
I need help on how to go about adding CSS stylings to a Django email template. Django version = 4.0+ -
problem with SSL Version when connecting Rails API to Django API
I have inherited an application where there is a legacy API built with Django that serves up most of the resource and a team that was in the process of migrating the API over to a Rails. The front end currently talks to the Rails app and if the resource is not available, the Rails API will query for it from the Django API. I am trying to get this set-up functioning in my local environment however I am getting an SSL version issue. Wondering if anyone can help with this issue? Processing by Api::LegacyApiController#unknown as HTML Parameters: {"path"=>"v1/users"} Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms | Allocations: 1493) OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=error: wrong version number): Here is the controller for the fall back for when the Rails API doesn't have the resource class Api::LegacyApiController < ActionController::Base include ReverseProxy::Controller skip_before_action :verify_authenticity_token def unknown #noinspection RubyResolve host = Rails.application.config.legacy_api_host headers = { 'Host' => host, 'Accept' => request.headers.to_h['HTTP_ACCEPT'] } reverse_proxy "https://#{host}", headers: headers end end Rails API running on localhost:3000 Django API running on localhost:8000 the legacy_api_host is currently set to 'localhost:8000' Thanks for the help everyone. Unfortunately I am a pretty junior developer and I haven't tried … -
Django: Javascript not loading extra rows
I have a page that allows a doctor to create a prescription. This page as a form that allows you to add as many rows as you want to add elements to your prescription. I will share with you the view and html template. I replicated the exam same thing for creating another type of prescription (lab analysis). This time, the button does not want to add more rows, even though I used the exact same code, and I will tell you exactly what breaks it, but I do not know how to fix it. Here is the code for the first one (the one that works): view: @login_required def createPrescription(request): [...] # ommited because unrelated drugs = Drug.objects.all() return render[...] # ommited because unrelated HTML: <!-- PAGE-HEADER END --> <form method="POST" id="presForm"> {% csrf_token %} [...] # ommited because unrelated <div class="card"> <div class="card-header"> <div class="card-title">Eléments de l'ordonnance</div> </div> <div class="card-body"> <table id="myTable" class="table order-list"> <thead> <tr> <td>Médicament</td> <td>Dosage</td> <td>Posologie</td> <td>Durée</td> <td></td> </tr> </thead> <tbody> <tr> <td class="col-5"> <div class="row"> <div class="col-6"> <input class="form-control mb-4" placeholder="Nom du médicament" type="text" name="medicament0"> </div> <div class="col-6"> <div class="form-group"> <select class="form-control select2-show-search form-select" id="medicament-id0" name="listemedicament0"> <option value="0">Ou choisir de la liste</option> {% for … -
Writing a custom user authentication with email using django
This code is to create a custom authentication which accepts email and password to login instead of username and password. Anytime i use the "python manage.py createsuperuser" and input my details, i always get an error message which says: "return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) TypeError: CustomUserManager._create_user() takes 6 positional arguments but 7 were given" How do i go about this models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("Email must be provided") if not password: raise ValueError("Password must be provided") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault("is_active", True) extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault("is_active", True) extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) mobile = models.CharField(max_length=50) address = models.CharField(max_length=250) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = … -
How to create third party login API in Django to save session details?
I am trying to build an external API in django, such that any third party application can log into my Django application with their specific username and password, and further use all the authenticated calls in the Django application. As I understand, in Django, there is a GET call that creates the csrf_token, and an op_browser_state token, which is saved in Cookies. Once the user enters the username and password, and selects login. Internally, the session id is added via the middleware between request and response, after the auth.login is successful, with the username and the password. The session_id, along with the csrf_token and op_browser_state are saved in the cookies, and used for all the further calls made via Django APIs, which may be using SessionAuthentication. So, if I am able to save the cookies for the session__id, csrf_token and op_browser_state for the Django application hostname. I should be able to solve it. I tried creating an external API, which does the login for the given combination of username and password, and returns the values of csrf_token and session_id as generated by the API. However, this didn't work, since looks like it is not storing the cookies for the Django … -
form ModelMultipleChoiceField returns null [IntegrityError]
Using Django 4.0.5, Python 3.10.5. I've created a form which should return a "match" model object. It properly displays "players" to choose from on a form, although after trying to save it I receive an IntegrityError, that I supposedly violate my not-null constraint. The failing row details are below: DETAIL: Failing row contains (2bc3f5f6-3249-4823-ae76-90fe44dc9c89, 2022-09-09, null, null). The values that I'm passing is UUID, date, and two teams that are ManyToManyFields containing Player objects. I can't seem t understand why both teams return empty. Any help is appreciated, posting relevant code below. If anything besides that is required, I'll update it. forms.py [matches app] class PlayerChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj: Player) -> str: return obj.nickname class MatchForm(forms.ModelForm): date = forms.DateField(widget=forms.SelectDateWidget(), initial=datetime.date.today, label="Match Date") blackTeamPlayers = PlayerChoiceField(queryset=Player.objects.all(), widget=forms.CheckboxSelectMultiple) whiteTeamPlayers = PlayerChoiceField(queryset=Player.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Match fields = ['date', 'blackTeamPlayers', 'whiteTeamPlayers'] models.py [matches app] class Match(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) date = models.DateField(null=False) blackTeamPlayers = models.ManyToManyField( Player, related_name='%(class)s_black_team_players' ) whiteTeamPlayers = models.ManyToManyField( Player, related_name='%(class)s_white_team_players' ) views.py [matches app, relevant part] class MatchCreateView(CreateView): template_name: str = 'add_match.html' form_class = MatchForm queryset = Match.objects.all() def form_valid(self, form): return super().form_valid(form) models.py [players app] class Player(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) firstname … -
How to get Percentile in Postgresql same as scipy.stats.percentileofscore
I have a table that contains "id" and "score". id | score 1 | 10 2 | 20 3 | 30 4 | 40 How can I find the percentiles of scores using PostgreSQL to get an expected output of: id | score | percentile 1 | 10 | 25.0 2 | 20 | 50.0 3 | 30 | 75.0 4 | 40 | 100.0 In python one way to solve this would be using scipy.stats.percentileofscore >>>from scipy import stats >>>stats.percentileofscore([1, 2, 3, 4], 3) 75.0 but I'd like a way to do this with PostgreSQL I tried using PERCENT_RANK, "%(function)s() OVER (ORDER BY %(expressions)s DESC) *100" But it has not returned the same value as scipy.stats.percentileofscore -
'ManyRelatedManager' object has no attribute 'models'
In my Django+ DRF app I am having trouble adding a field to serializer when the field is from another model. My Order model has the field 'car_make' and I need to also add the field 'car_model' when serializing the order data ('car_model' comes from the CarModel model), and I add it using SerializerMethodField. Instead of getting the data (the name of the car model), I get an error "'ManyRelatedManager' object has no attribute 'models'". I don't get why this does not work. What is the problem with my code? Thanks in advance! Here is my code: models.py from django.db import models import datetime class CarMake(models.Model): # Toyota, Honda, etc. make_name = models.CharField(max_length=20) class CarModel(models.Model): # Corolla, Civic etc. model_name = models.CharField(max_length=20) make = models.ForeignKey(CarMake, on_delete=models.CASCADE, related_name='models') order = models.ForeignKey('Order', on_delete=models.CASCADE, related_name='models') class Order(models.Model): color = models.ForeignKey(Color, on_delete=models.CASCADE, related_name='orders') car_make = models.ManyToManyField(CarMake, through='CarModel', related_name='orders') quantity = models.PositiveIntegerField() ordered_at = models.DateField(default=datetime.date.today) views.py from rest_framework import viewsets from .models import CarMake, CarModel, Color, Order from .serializers import CarMakeSerializer, CarModelSerializer, ColorSerializer, OrderSerializer class CarMakeViewSet(viewsets.ModelViewSet): queryset = CarMake.objects.all() serializer_class = CarMakeSerializer class CarModelViewSet(viewsets.ModelViewSet): queryset = CarModel.objects.all() serializer_class = CarModelSerializer class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer serializers.py from rest_framework import serializers from .models … -
Show output of a python sciript as website
I am very new to Python. I just need to see the output of import os for k,v in os.environ.items(): print(k,v) as a website, means <server_ip_address>:port. It will be so kind of you if you can help me by doing this. I dont know very much about flask and django etc. -
Recipe creation and modification not working correctly
I'm trying to implement a recipe creation function. The data is created and then you can get it, with a post request, changes are also made. But when creating a site, a redirect does not occur and gives such an error. AttributeError: Got AttributeError when attempting to get a value for field amount on serializer AmountIngredientForRecipePostSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Ingredient instance. Original exception text was: 'Ingredient' object has no attribute 'amount'. view class RecipesViewSet(viewsets.ModelViewSet): queryset = Recipe.objects.all().order_by('id') filter_backends = (DjangoFilterBackend,) filter_class = RecipeFilter pagination_class = PagePagination permission_classes = (OwnerOrAdminOrSafeMethods,) def get_serializer_class(self): if self.request.method == 'GET': return RecipeGetSerializer return RecipePostSerializer @staticmethod def post_or_delete(request, model, serializer, pk): if request.method != 'POST': get_object_or_404( model, user=request.user, recipe=get_object_or_404(Recipe, id=pk) ).delete() return Response(status=status.HTTP_204_NO_CONTENT) serializer = serializer( data={'user': request.user.id, 'recipe': pk}, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) serialaizer class AmountIngredientForRecipePostSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) amount = serializers.IntegerField(min_value=1) class Meta: model = AmountIngredient fields = ('id', 'amount') class RecipePostSerializer(serializers.ModelSerializer): author = CostomUserSerializer(read_only=True) ingredients = AmountIngredientForRecipePostSerializer(many=True) tags = serializers.PrimaryKeyRelatedField( queryset=Tags.objects.all(), many=True) image = Base64ImageField() class Meta: model = Recipe fields = ('id', 'author', 'ingredients', 'tags', 'image', 'name', 'text', 'cooking_time') @staticmethod def create_ingredients_tags(recipe, ingredients, tags): for ingredient … -
Writing custom url model field in Django
I am creating one model called Profile in which i have to add a url field for telegram profile. It takes username as input, but in output it should look like this: https://t.me/{username}. How I can create custom model field for this problem. Thanks by the way My expectation is that, you only enter username, but in output it comes with prefix https://t.me/ and full url path will be https://t.me/{username} -
How to delete corresponding row with ManyToMany relationship in Django?
I am trying to make a basic pizza app with two API's, toppings and pizzas. When I delete a topping, I would like for the corresponding pizzas to also be deleted since the topping is no longer available. As it currently stands, when I delete a topping it just keeps an empty pizza object. Models: class Toppings(models.Model): name = models.CharField(max_length=60, unique=True) def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(max_length=60, unique=True) topping = models.ManyToManyField(Toppings, max_length=60, related_name="toppings") def __str__(self): return (self.name, self.topping) Serializers: class PizzaSerializer(serializers.ModelSerializer): toppings = ToppingsSerializer(read_only=True, many=True) class Meta: model = Pizza fields = "__all__" class ToppingsSerializer(serializers.ModelSerializer): class Meta: model = Toppings fields = "__all__" Pizza.views and Toppings.views are almost the same so I just included Pizza. class PizzaList(generics.ListAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer class PizzaCreate(generics.CreateAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer class PizzaUpdate(generics.UpdateAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer class PizzaDelete(generics.DestroyAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer Please let me know if you need anything else. Thank you. -
Implementing Apple Sign in using django-allauth
I am currently implementing social login using django-allauth. I've had no problems implementing social logins like Google, Facebook and etc. However, when it came to Apple, the package doesn't seem to work properly. I've been testing the logins using https. Also, I've completed settings in Apple Developer and Django Admin. The below is the capture of my login page. when I click on apple icon, it gets redirected to apple page to proceed. When I enter the apple login and complete authentication on apple site, the browser throws Server Error(500). I believe my settings for apple sign-in have been correct. The below is my admin settings for apple sign-in. I tried to search the references on the internet but I couldn't find anyone experienced the same issue. I have no idea on how to resolve this issue nor do I know the way to find where the error is coming from. Could anyone suggest any method on how to implement apple sign-in using django-allauth package? Thanks, -
Query time in django debug toolbar
I see time of query QUERY = 'SELECT COUNT_BIG(*) AS [__count] FROM ... in Django debug toolbar. Is it pure perfomance of database or dirty time that includes handling of query by Django and third-party libraries? -
Unable to change input field text content with javascript
I'm trying to change the text inside an input field to username. The id for the field is is_username. And in my Javascript file I've tried document.getElementById("id_username").innerHTML = "Username"; document.getElementById("id_username").value = "Username"; document.querySelector(".id_username").textContent = "Username"; None are working... This site runs on django. I know with html you can use placeholder to achieve this but these fields are created using django tags. Any ideas? I did try using these methods on a normal html input field and also had no luck. -
how can i send a vuejs array to django rest api
i want to send an array of inputs to my django rest api. I can fill the array with data, but i always got an error message when i tried to send to the rest api. I have already tried to use the ArrayField() option in django but it didnt work. -
ValueError at /category/economy/: Field 'id' expected a number but got 'economy'
I try to add new path and this happen "Field 'id' expected a number but got 'economy'." in traceback the highlighted line is in the views.py file which i mentioned below. category_posts = Post.objects.filter(category=cats) I am sharing my files plz help me to get rid of the issue. urls.py urlpatterns = [ path('',views.allpost,name="allpost"), path('search', views.search, name="search"), path('contact/', views.contact, name="contact"), path('success/', views.successView, name="success"), path('category/<str:cats>/', views.CategoryView, name ="category"), path('<int:blog_id>/',views.detail,name="detail"), ] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'." views.py def CategoryView(request, cats): # here cats is same which mentioned in dynamic url. category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts}) "category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback models.py from django.db import models class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") title = models.CharField(max_length=255, verbose_name="Title") parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank= True, null=True) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) public_date = models.DateField(null=True) public_time = models.TimeField(null=True,default="") category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True) image = models.ImageField(upload_to='images/',null=True, blank=True) body = models.TextField() class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['public_date'] def summary(self): return self.body[:100] def pub_date(self): return … -
After installing fobi from https://pypi.org/project/django-fobi/ and try localhost:8000/admin getting error
I followed the https://pypi.org/project/django-fobi/ instalation instructions, and after pip install django-fobi into my venv I set my settings.py as follows ` INSTALLED_APPS = [ 'dose.apps.DoseConfig', 'django.contrib.admin', 'django.contrib.contenttypes', # Used by fobi 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'aiengine', 'fobi', # `django-fobi` themes 'fobi.contrib.themes.bootstrap3', # Bootstrap 3 theme 'fobi.contrib.themes.foundation5', # Foundation 5 theme 'fobi.contrib.themes.simple', # Simple theme # `django-fobi` form elements - fields 'fobi.contrib.plugins.form_elements.fields.boolean', 'fobi.contrib.plugins.form_elements.fields.checkbox_select_multiple', 'fobi.contrib.plugins.form_elements.fields.date', 'fobi.contrib.plugins.form_elements.fields.date_drop_down', 'fobi.contrib.plugins.form_elements.fields.datetime', 'fobi.contrib.plugins.form_elements.fields.decimal', 'fobi.contrib.plugins.form_elements.fields.email', 'fobi.contrib.plugins.form_elements.fields.file', 'fobi.contrib.plugins.form_elements.fields.float', 'fobi.contrib.plugins.form_elements.fields.hidden', 'fobi.contrib.plugins.form_elements.fields.input', 'fobi.contrib.plugins.form_elements.fields.integer', 'fobi.contrib.plugins.form_elements.fields.ip_address', 'fobi.contrib.plugins.form_elements.fields.null_boolean', 'fobi.contrib.plugins.form_elements.fields.password', 'fobi.contrib.plugins.form_elements.fields.radio', 'fobi.contrib.plugins.form_elements.fields.regex', 'fobi.contrib.plugins.form_elements.fields.select', 'fobi.contrib.plugins.form_elements.fields.select_model_object', 'fobi.contrib.plugins.form_elements.fields.select_multiple', 'fobi.contrib.plugins.form_elements.fields.select_multiple_model_objects', 'fobi.contrib.plugins.form_elements.fields.slug', 'fobi.contrib.plugins.form_elements.fields.text', 'fobi.contrib.plugins.form_elements.fields.textarea', 'fobi.contrib.plugins.form_elements.fields.time', 'fobi.contrib.plugins.form_elements.fields.url', # `django-fobi` form elements - content elements 'fobi.contrib.plugins.form_elements.test.dummy', 'easy_thumbnails', # Required by `content_image` plugin 'fobi.contrib.plugins.form_elements.content.content_image', 'fobi.contrib.plugins.form_elements.content.content_image_url', 'fobi.contrib.plugins.form_elements.content.content_text', 'fobi.contrib.plugins.form_elements.content.content_video', # `django-fobi` form handlers 'fobi.contrib.plugins.form_handlers.db_store', 'fobi.contrib.plugins.form_handlers.http_repost', 'fobi.contrib.plugins.form_handlers.mail', 'fobi.contrib.plugins.form_handlers.mail_sender', ] and I edited mysite.urls.py ` urlpatterns = [ path('instruction/', InstructionListView.as_view()), path('dose/', include('dose.urls')), path('admin/', admin.site.urls), # View URLs re_path(r'^fobi/', include('fobi.urls.view')), # Edit URLs re_path(r'^fobi/', include('fobi.urls.edit')), # DB Store plugin URLs re_path(r'^fobi/plugins/form-handlers/db-store/', include('fobi.contrib.plugins.form_handlers.db_store.urls')), ` I get this error on runserver it was all working before installing fobi ` File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\contrib\sites\models.py", line 39, in _get_site_by_request SITE_CACHE[host] = self.get(domain__iexact=host) File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\viter\base\dosehomev3\dosehome\venv\lib\site-packages\django\db\models\query.py", line 650, in get raise self.model.DoesNotExist( django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. ` I expected to get … -
Getting Token from Django Model to views
I created a user model in Django i want to know what JWT token is generated for my particular user in the views.py section could you please help class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status=models.IntegerField(default=1) phone=models.IntegerField(blank=True,null=True) otp=models.IntegerField(blank=True,null=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) #locations=models.ManyToManyField(Location) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.email def tokensd(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } -
cannot display classes of courses
I am trying to create an educational website using django, so I have two models class and course which have a one-to-many foreignkey relationship between them i.e. one course can have several class but one class can only have one course. But this creates a problem for me. That is, in my course_detail_view I have assigned the model course. So I cannot render classes in my html file. Can anyone help me solve this ? My models.py: class Course(models.Model): title = models.CharField(max_length=100) image = models.ImageField(upload_to='class/instructor_pics', null=True) instructor = models.CharField(max_length=100) instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True) students = models.ManyToManyField(User, related_name='courses_joined', blank=True) slug = models.SlugField(max_length=200, unique=True) description = models.TextField(max_length=300, null=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return self.title class Class(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='class/class_videos',null=True, validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, related_name='classes') def __str__(self): return self.title My views.py: class CourseDetailView(LoginRequiredMixin, DetailView): model = Course template_name = 'class/course.html' Thanks in advance!