Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Charfield with select2 input not populated in update view
I'm working on a form that gets the "Education" information from the user. The institute name is one of the fields in the model. The initial configuration for the model: class Education(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) institute = models.CharField(max_length=50, null=True, blank=True) program = models.CharField(max_length=50, null=True, blank=True) level = models.CharField(max_length=1, choices=StudyLevel.choices, default=StudyLevel.UNSPECIFIED) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I don't want to grant the users ability to give meaningless input. That's why I decided to let users "select" their university from an external API. Sample search: http://universities.hipolabs.com/search?name=johannes I used jQuery Select2 with Ajax to fetch data from the API whenever user types a character in the field. Ajax code: $(document).ready(function () { $('#id_institute').select2({ ajax: { url: 'http://universities.hipolabs.com/search?', data: function (params) { return { name: params.term }; }, dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.name, text: item.name}; }) }; } }, width: '50%', minimumInputLength: 1 }); And I had to overwrite the widget for the 'institute' field at the ModelForm as following: class EducationForm(ModelForm): class Meta: model = Education fields = '__all__' exclude = ['owner'] widgets = { 'institute': forms.Select(), } It works as expected: create view However, when I go … -
Celery django with supervisor dont give use the Django database scheduler
I got apache server with django, all work. And celery with redis. Worker work,all right, but when on celery beat through supervisor, i get an error. My think was about database(postgress), but 'django' all granted. Here error. Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/polski-urody-back/venv/bin/celery", line 8, in <module> sys.exit(main()) File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/__main__.py", line 16, in main _main() _gdbm.error: [Errno 13] Permission denied: 'django' Traceback (most recent call last): File "/home/polski-urody-back/venv/lib/python3.8/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/polski-urody-back/venv/bin/celery", line 8, in <module> sys.exit(main()) value = obj.__dict__[self.__name__] = self.__get(obj) File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/worker/state.py", line 266, in db return self.open() File "/home/polski-urody-back/venv/lib/python3.8/site-packages/celery/worker/state.py", line 192, in open return self.storage.open( File "/usr/lib/python3.8/shelve.py", line 243, in open … -
Override django-filters Django models PointField
I am trying to filter data using django-filters. I am using a PointField for location and I want to override this field from filters.py. How can I override the models PointField from filters.py? import django_filters from .models import Apartment class ApartmentFilter(django_filters.FilterSet): ADKT = 'Addis Ketema' AKLT = 'Akaki-Kality' ARDA = 'Arada' BOLE = 'Bole' GLLE = 'Gulele' KLFE = 'Kolfe-Keranio' KIRK = 'Kirkos' LDTA = 'Lideta' YEKA = 'Yeka' NFSL = 'Nefas Silk-Lafto' SUBCITY_CHOICES = [ (ADKT, 'Addis Ketema'), (AKLT, 'Akaki-Kality'), (ARDA, 'Arada'), (BOLE, 'Bole'), (GLLE, 'Gulele'), (KLFE, 'Kolfe-Keranio'), (KIRK, 'Kirkos'), (LDTA, 'Lideta'), (NFSL, 'Nefas Silk-Lafto'), (YEKA, 'Yeka')] class Meta: model = Apartment fields = ['apt_subcity', 'apt_cost'] filter_overrides = { models.PointField: { 'filter_class': django_filters.CharField, } } -
How to integrate Blastplus in a Django environment
Django newbie here! I have downloaded via git clone this package: https://github.com/michal-stuglik/django-blastplus I have installed all the dependencies required in the requirement.txt I already have my really basic site working and now what I want to achieve is to add the BLAST tool in it. What I miss is basically what I have to do to integrate this app with my website. Actually, I am able to call the .html templates, but I am not able to call the forms.py that contains all the instructions to make the BLAST alignments. I know that what I am asking will require a pretty long answer, but any hint will help. If I have to share some of my file in order to let the community makes a better idea of my situation, do not refrain to ask. Thank you so much. -
Input boxes styling weirdly when using Django & Tailwind.css
I am creating a simple login page using Django & Tailwind.css. My form was styling fine until I inherited a <nav> from base.html. When I did so, gray borders started appearing around my input boxes and the input boxes got slightly bigger. The original layout: https://ibb.co/vXxgrH0 The new layout (with base.html being inherited): https://ibb.co/QCsvKmz I'm not sure why this is occurring, because all of the code remains the same, I am just {% extends "base.html" %} at the top of my login.html Here is my base.html code (contains the navar & responsive navbar): <!DOCTYPE html> <html class="screen-top"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>{% block title %}{% endblock %}</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://shuffle.dev/vendor/icons/css/fontello.css?v=h7b" id="bs-base-css"> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="https://shuffle.dev/vendor/tailwind-flex/css/tailwind.min.css?v=bd4"></style> <style type="text/css" href="css2?family=Poppins:wght@400;500;600;700&display=swap"></style> <link rel="stylesheet" href="https://shuffle.dev/static/build/css/shuffle-preview.3a553ecf.css"> <link rel="stylesheet" href="https://unpkg.com/flowbite@latest/dist/flowbite.min.css" /> <script src="https://shuffle.dev/vendor/tailwind-flex/js/main.js"></script> <script src="https://cdn.tailwindcss.com"></script> {% block css %} {% endblock %} </head> <body id="page" class="antialiased font-body bg-body text-body bg-[rgb(248,250,251)]"> <!-- NAVBAR --> <div class="" id="content"> <section class="relative overflow-hidden"> <nav class="flex justify-between p-6 px-4" data-config-id="toggle-mobile" data-config-target=".navbar-menu" data-config-class="hidden" style="background-color: #2a3342;"> <div class="flex justify-between items-center w-full"> <div class="w-1/2 xl:w-1/3"> <a class="block max-w-max" href="{% url 'home' %}"> <img class="h-8" src="https://i.ibb.co/LRCrLTF/Screenshot-2022-04-03-140946-removebg-preview.png" alt="LOGO" data-config-id="auto-img-1-2" style="transform: scale(2); padding-left: 30px"> </a> … -
Get a queryset of objects where a field is distinct
I have a model like the following: class Reports(models.Model): reportid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=100) description = models.CharField(max_length=300, default='', blank=True) value = models.FloatField(default=0) I need to search the model by matching a search term in the name field. Then I need to return a queryset containing objects each of which have unique names which match the search term. See the example: testsearchterm = 'bs' initreports = Reports.objects.filter(name__lower__contains=testsearchterm) print("initreports:", initreports) Result: initreports: <QuerySet [<Reports: FBS>, <Reports: PPBS>, <Reports: FBS>, <Reports: FBS>, <Reports: PPBS>, <Reports: FBS>, <Reports: FBS>, <Reports: PPBS>, <Reports: Random Blood Sugar (RBS)>, Now I get distinct names reports = Reports.objects.filter(name__lower__contains=testsearchterm).values_list('name', flat=True).distinct() print("Unique values:", reports) Result: Unique values: <QuerySet ['FBS', 'PPBS', 'Random Blood Sugar (RBS)', 'Sleep study to r/o Obstructive sleep apnea', 'Serum HBsAg']> Now I need the full queryset not just the names, so that I can serialize the results and return the other fields too. for name in tests: res = Reports.objects.filter(name=name).first() print(res, type(res)) Results: FBS <class 'appointments.models.Reports'> PPBS <class 'appointments.models.Reports'> Random Blood Sugar (RBS) <class 'appointments.models.Reports'> Sleep study to r/o Obstructive sleep apnea <class 'appointments.models.Reports'> Serum HBsAg <class 'appointments.models.Reports'> I need a queryset of the above, like the following: <QuerySet [<Reports: FBS>, <Reports: PPBS>, <Reports: RBS>, … -
Django Server Error whenever i run my server how to resolve this error
this error occurs again and again anyone have solution please tell me -
Django for loop in html<script>
I've created a menu where there was originally a hardcoded choice .Im trying to pass some models names into it but it doesnt work . Any ideas what I am doing wrong? view def map(request): field_list = models.Field.objects.all() context = { "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) map.html {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name")); //friendly name {% endfor %} -
Compare Day of the Week with ManyToMany Relationship
I'm new to Django and learning, and i'm trying to do the following: The user registers the days of the week and the time period he is available. class DiasDaSemana(models.Model): diasdasemana = models.CharField(max_length=20) def __str__(self): return self.diasdasemana class RelacaoHorarioSemana(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE) relacao_dia_semana = models.ManyToManyField(DiasDaSemana) start_horario = models.TimeField(auto_now=False, verbose_name='Horário Inicial',blank=False, null=False) end_horario = models.TimeField(auto_now=False, verbose_name='Horário Final',blank=False, null=False) obs = models.TextField(max_length=200, null=True) class Meta: verbose_name = "Usuário e Horário" verbose_name_plural = "Usuários e Horários" def dias_da_semana(self): return ", ".join([str(p) for p in self.relacao_dia_semana.all()]) def __str__(self): return str('Cadastre o Horário de Trabalho do Usuário:') I want to add a logic that checks if the user is available on the present time and day, so i can filter the results to display in a template. I'm trying to compare the timezone.isoweekday IDs with the user inputted IDs (Which are the same, Monday = 1 and Segunda-feira(Monday in Portuguese) is = 1) but i'm clueless as how to do it... I've thought about querying the ManyToMany field but i'm clueless as how to do it. So far, i've got to this: @property def checar_disponibilidade_horario_dia(self): data_comeco = timezone.localtime(self.start_horario) data_fim = timezone.localtime(self.end_horario) data_agora = timezone.localtime(timezone.now()) # Segunda é 1 e Domingo é 7 diasemana_hoje = … -
AttributeError: 'NoneType' object has no attribute '_meta' while updating data using nested serializers via PATCH call in Django Rest Framework
I want to update the Model data using nested serializers via PATCH call in DRF. I have custom User Model, Country, City, Detail Model. I have MainUserSerializer, CountrySerializer, CitySerializer and UserSerializer, and I have UserAPI view. Below is my models.py: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, null=True, blank=True) email = models.EmailField(max_length=254, unique=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class Country(models.Model): name = models.CharField(max_length=100, default='c') def __str__(self): return ("{}".format(self.name)) class City(models.Model): name = models.CharField(max_length=100 ,default='c') country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return ("{} ({})".format(self.name, self.country.name)) class Detail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=20, default='g') age = models.IntegerField(default=0) country = models.IntegerField(default=1) city = models.IntegerField(default=1) def __str__(self): return ("{} ({} {})".format(self.user.email, self.user.first_name, self.user.last_name)) my serializers.py: class MainUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email') class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('name',) class CountrySerializer(serializers.ModelSerializer): city = CitySerializer() class Meta: model = Country fields = ('name', 'city') class UserSerializer(serializers.ModelSerializer): usr = MainUserSerializer() country = CountrySerializer() city = CitySerializer() … -
Create link to specific blog article by primary key in Django and slugify url
I am following some basic tutorials to learn the basics of building websites in Django. I have a "news template" working, but I am struggling to (understand) create the links to a specific database article and use the slug in the url. I have only managed to find examples where a list of all posts are shown with links but this is not what I am looking for. I have this: models.py class Post(models.Model): title = models.CharField(max_length=200) slug=models.SlugField(max_length=250, null=True, blank=True) category=models.CharField(max_length=40) text=RichTextField(blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug=slugify(self.title) super().save(*args, **kwargs) # def get_absolute_url(self): # return reverse('post_detail', kwargs={'slug': self.slug}) def get_absolute_url(self): return reverse('post_detail', kwargs={"id":self.id, "slug":self.slug}) views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) urls.py urlpatterns = [ path('',views.index,name='index'), path('articles/<int:pk>/', views.post_detail, name='post_detail'), # path('articles/<slug>/', views.post_detail, name='post_detail') ] html: <a href="{% url 'post_detail' pk=1 %}">'*article headline from post.title (somehow)*'</a> This works when I hardcode the primary key of the article but of course the url shows with the pk and fails if I try using slug (NoReverseMatch). What can I do in the html line to be able to point to a specific article but get the slugfield to be shown … -
Django Import-Export
Im using Django import-export to add a large spreadsheet into a model. The import itself works just fine, but I am looking to add two additional columns to the dataset that identify the name of the excel file, and the date it was uploaded. Here is my Model from django.db import models class DataImport(models.Model): Column1 = models.CharField(max_length=15, null=True) Column2 = models.CharField(max_length=50, null=True) Column3 = models.CharField(max_length=25, null=True) Column4 = models.CharField(max_length=150, null=True) FileName = models.CharField(max_length=150, null=True) UploadDate = models.CharField(max_length=150, null=True) def __str__(self): return str(self.Column1) My Resource Class from dashboard.models import DataImport from import_export import resources, fields from import_export.fields import Field class DataImportResource(resources.ModelResource): Column1 = Field(attribute='Column1', column_name="Column_1") Column2 = Field(attribute="Column2", column_name="Column_2") Column3 = Field(attribute='Column3', column_name="Column_3") Column4 = Field(attribute='Column4', column_name="Column_4") def skip_row(self, instance, original): if instance.Column1.strip() != 'value': return True if instance.Column2.strip() not in {'value1, 'value2', 'value3', 'value4'}: return True else: return False class Meta: model = DataImport and my admin class class DataImportAdmin(ImportExportModelAdmin): resource_class = DataImportResource admin.site.register(DataImport, DataImportAdmin) ideally, I would like to have the user select the excel, and then select the month from a select list that will then go into the "UploadDate" field in the database. due to the duplicative (but needed) nature of the data, I need to do … -
Slice a list with for loop range function in Django templates
I am developing a Django application about statistics calculations. But now I have faced a problem that I can't solve. I have two lists in my views.py list1 = [5, 6, 7, 8] list2 = [5, 6, 7, 8]. I sent this to Django templates and I also sent 'n' : range(7) as context. In my html code, there have a code <table> <thead> <tr> <th>list1</th> <th>list2</th> </tr> <tr> <td></td> <td></td> </tr> </thead> </table> Now I want to print first value of each list in first row, then second value of each list in second row and so on. So I have made a code something like this <table> <thead> <tr> <th>list1</th> <th>list2</th> </tr> {% for i in n %} <tr> <td> {{ list1.i }} </td> <td>{{ list2.i }}</td> </tr> {% endfor %} </thead> </table> After writting this code, I am not getting any error but the values are not showing. Instead a blank row and columns are being made. Please help me to print the values that I want to print. -
Django rest framework user earn points
How do I make dot scheme in django? Like, every time I send a post and the answer is true, the user gets a point, and whenever he sends a post with the id of the answer and the answer is True, the user gets more point -
Django: error trying to access detail view with re_path
To elaborate, I went down a bit of a rabbit hole just trying to make a trailing "/" optional in the URL. got it to sorta work with the project directory, but when on the blog app, I tried to use re_path in order to use regex to allow for an optional trailing "/" in the url, but I seem to get an error in the template website urls.py (directory with settings.py) from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('blog/', include('blog.urls')), path('blog', include('blog.urls')) ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) blog urls.py from django.urls import path, include, re_path from .views import BlogView, ArticleView urlpatterns = [ path('', BlogView.as_view(), name="blog"), re_path(r'titles/(?P<slug_url>\d+)/metadata/localized/$', ArticleView, name="article"), ] blog.html template error appears at the href {% extends 'base.html' %} {% block content %} <h1>Articles</h1> {% for post in object_list %} <h2><a href="{% url 'article' post.url_slug %}">{{ post.title }}</a></h2> {% endfor %} {% endblock %} blog views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Post from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy, reverse from django.http import HttpResponseRedirect # Create your views here. class BlogView(ListView): model … -
MultiValueDictKeyError at / 'name'
enter image description here i just want to fetch the data from my website and record it to my django databae this my views.py code : def index(request): feature1 = Feature.objects.all() Appnt = Appointment.objects.all() if request.method == 'GET': Appnt.name = request.GET['name'] Appnt.email = request.GET['email'] Appnt.phone = request.GET['phone'] Appnt.Adate = request.GET['date'] Appnt.Dept = request.GET['department'] Appnt.Doc = request.GET['doctor'] Appnt.message = request.GET['message'] contaxt = { 'feature1' : feature1, 'Appointment' : Appnt } return render(request, 'index.html', contaxt) -
Django - BaseSerializer.is_valid() missing 1 required positional argument: 'self'
I am creating a base viewset class and trying to use it in two classes. The viewset has a create method which uses the get_serializer_class() to get the serialzer and creates the object. But the is_valid() throws error TypeError: BaseSerializer.is_valid() missing 1 required positional argument: 'self' Here is the base class: class BaseViewSet(BaseFilterViewSet): permission_classes = [IsAuthenticated] def create(self, request: Request, *args: Any, **kwargs: Any) -> Response: context = super(BaseViewSet, self).get_serializer_context() context.update({"request": request}) # serializer = super(BaseViewSet, self).get_serializer_class() serializer = self.get_serializer_class() serializer(data=request.data, context=context) serializer.is_valid(raise_exception=True) serializer.save(created_by=request.user) return Response(serializer.data, status=HTTP_201_CREATED) Here is the child class which uses this viewset and defines a get_serializer_class method. class ChildViewSet(BaseViewSet): queryset = Child.objects.all().select_related("model2") permission_classes = [IsAuthenticated] def get_serializer_class(self) -> Type[BaseSerializer[_MT_co]]: if self.action == "stock": return StockSerializer else: return ChildSerializer Many thanks for inputs and help. -
django:how to upload image file with ckeditor?
i write a function to upload the image file import os import uuid from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.conf import settings @csrf_exempt def upload_file(request): """ ckeditor5图片上传 """ upload = request.FILES.get('upload') # 生成uuid uid = ''.join(str(uuid.uuid4()).split('-')) # 修改图片名称 names = str(upload.name).split('.') names[0] = uid # 拼接图片名 upload.name = '.'.join(names) # 构造上传路径 print(upload.name, '='*100) new_path = os.path.join(settings.MEDIA_ROOT, 'upload/', upload.name) # 上传图片 with open(new_path, 'wb+') as destination: for chunk in upload.chunks(): destination.write(chunk) # 构造要求的数据格式并返回 filename = upload.name url = '/media/upload/' + filename retdata = { 'url': url, 'uploaded': '1', 'fileName': filename } return JsonResponse(retdata) this is the url setting from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static from utils.upload import upload_file urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('blog.urls')), path('uploads/', upload_file, name='uploads') # 上传图片url ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is ckeditor.js, i add ckfinder: { uploadUrl: '/uploads/' }, into it import ...... class Editor extends ClassicEditor {} // Plugins to include in the build. Editor.builtinPlugins = [ ...... ]; // Editor configuration. Editor.defaultConfig = { toolbar: { ...... }, language: 'zh', image: { ...... }, ckfinder: { uploadUrl: '/uploads/' }, table: {......} }; export default … -
how to create user if email address is not exist same time with log in
if the user with the email address already exists it logs the user in and shows a dashboard for the user. If the email address does not exist, a user is created with the email address and the user logs in -
Can't create superuser/ TypeError: NewUser() got an unexpected keyword argument 'username'
I try to create a custom superuser model, but when I try to create the actual superuser account with "python manage.py createsuperuser" I fill in the email, user name, first name, password, and password 2. But when I press enter after I input the second password I got an error. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from datetime import datetime from .country import COUNTRY_CHOICE from django.utils.translation import gettext_lazy as _ from django.db import models # Create your models here. country_choice = COUNTRY_CHOICE class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30, blank=False) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=False) birthday = models.DateTimeField() # gender model GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) gender = models.CharField(max_length=1, … -
How to create an a model instance
Ok, I have two models here (Room & Message) and the message model is the child of room. so i wanted to add a comment section where a user can comment to other rooms topic.Unfortunately i tried this code below here, and django says; (Cannot assign "(<Room: MYSQL Triggers>,)": "Message.room" must be a "Room" instance.) I mean i don't understand this. please help me figure this out if you can. #room model class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name #message model class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) room = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body #VIEWS TEMPLATE def room(request , pk): room = Room.objects.get(id=pk), comments = Message.objects.filter(room=pk).order_by('-created') #get comments comments_no = comments.count() #count number of comments #create comments if request.method == 'POST': #The problem seems to be here, but i don't understand how to fix it. messaging = Message.objects.create( host = request.user, room = room, body = request.POST.get('body') ) return redirect('room', id=room.id) context = {'room': room, 'comments':comments, 'noofcomm':comments_no} return render(request, 'base/rooms.html', context) -
Can not get links to work in Django project
Library/urls.py| urlpatterns = [ path('admin/', admin.site.urls), path('catalog/',include('catalog.urls')), path('',RedirectView.as_view(url='catalog/')), path('accounts/', include('django.contrib.auth.urls')), |Catalog/URL.PY| urlpatterns = [ path('',views.index,name='index'), path('',views.memb,name='memb'), path('create_book/',views.BookCreate.as_view(),name='create_book'), path('book/<int:pk>/',views.BookDetail.as_view(), name='book_detail'), path('my_view/',views.my_view, name='my_view'), |Catalog/View| def memb(request): return render(request, 'memb.html',context=context) |Catalog/index.html| <a href="memb.html">MEMBERS</a> |Catalog/memb.html| <li><a href="#news">News</a></li> Next menu option. |ERROR| Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/memb.html Using the URLconf defined in library.urls, Django tried these URL patterns, in this order: admin/ catalog/ [name='index'] catalog/ [name='memb'] catalog/ create_book/ [name='create_book'] catalog/ book/int:pk/ [name='book_detail'] catalog/ my_view/ [name='my_view'] accounts/ The current path, catalog/memb.html, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page Says Request URL: http://127.0.0.1:8000/catalog/memb.html NOT FOUND! Why does it not match path: catalog/ [name='memb'] in URLS? I have tried with and without .html different name selections,whatever. Please help....Stuck!!!!! Could it be some conflict with Admin? Have tried straight html links...same effect??? -
In Django is urlsafe_base64_encode encrypted?
I want to encrypt pk of the user in the signup form, e.g.: e.g. http://localhost:8000/user/pk/complete_signup/ -
Get Django to return related objects
I'm trying to filter one table and obtain the related rows from another table as a nested object. Models are as follow: class KpiArea(models.Model): harvest = models.CharField(max_length=45) area_id = models.IntegerField() percentage = models.FloatField(max_length=10) class Meta: managed = False db_table = 'kpi_area' unique_together = ['harvest', 'area_id'] class KpiAreaProducts(models.Model): product = models.CharField(max_length=45) percentage = models.FloatField(max_length=10) area_id = models.IntegerField() harvest = models.ForeignKey(KpiArea, on_delete=models.PROTECT, db_column = "harvest") class Meta: managed = False db_table = "kpi_area_products" unique_together = ['harvest', 'area_id'] My goal would be to be able to get the related objects whenever I'm filtering on KpiArea, ideally as a property containing a related object's array. Something like this: [ { area_id : 1, harvest: '2020/2021', percentage: 25, products: [ { product: 'soy', percentage: 15, area_id : 1 }, { product: 'wheat', percentage: 35, area_id : 1 }, ] } ] I've tried linking with 2 foreing keys on KpiAreaProducts model, and unique_together (as per other SO questions) to achieve this. Could somebody point me in the right direction? -
Django TestCase fails to load fixture data with MySQL
I am trying to create tests to check a newly implemented login process, however I got stuck at the very beginning. When I try to make a query in my tests, Django throws a MySQLdb._exceptions.OperationalError and fails to continue. I noticed, that this issue happens only when I use django.test.TestCase, but not when I use django.test.TransactionTestCase. Now I read that there is a difference between how these two handle transactions, but I still cannot understand why one fails when the other one works. Can someone please point me in the right direction? This code fails: class AuthenticateUserTest(TestCase): fixtures = ["test_users.json"] serialized_rollback = True def test_login_success(self): print(User.objects.all()) but this code doesn't: class AuthenticateUserTest(TransactionTestCase): fixtures = ["test_users.json"] serialized_rollback = True def test_login_success(self): print(User.objects.all()) with this fixture: [ { "model": "app.user", "pk": 1, "fields": { "created_at": "2022-04-07T13:34:53+01:00", "email": "test@test.com", "password": "topsecret", "is_active": true, "roles": "[\"SUPER_ADMIN\"]", "first_name": "Test", "last_name": "User" } } ] and with the following error: ERROR: test_login_success (tests.auth.test_auth_api.AuthenticateUserTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/tests/auth/test_auth_api.py", line 36, in test_login_success print(User.objects.all()) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 252, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 258, in __len__ self._fetch_all() File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line …