Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I run a model python from a button click from site web?
I have a Model python and I want to run it from a site web I already created from Django. -
Python Pickle object in Django model
I would like to know what would be the simplest way to store pickle objects in postgresql db using Django orm. Thanks in advance. -
Form not found or not recognized
I have ModelMultipleChoiceField form in my form.py like this : class UserResponseSearchForm(forms.Form): def __init__(self, *args, **kwargs): qry = kwargs.pop('qry') super(UserResponseSearchForm,self).__init__(*args, **kwargs) self.fields['gejala_id0'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains=qry).values_list('gejala', flat=True).distinct().order_by('gejala'),widget=forms.CheckboxSelectMultiple, required=False) gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False) And my views.py like this : def responsePenyakit(request): if request.user.is_authenticated: if request.method == 'POST': form = UserResponseForm(request.POST) gejala0 = form["gejala_id0"].data gejala1 = form["gejala_id1"].data gejala2 = form["gejala_id2"].data gejala3 = form["gejala_id3"].data if (len(gejala0) > 0): for i in range(0, len(gejala0)): userAnswer = UserAnswer() userAnswer.gejala_answer = gejala1[i] userAnswer.user_id = request.user.id userAnswer.number_diagnosis = user.number_diagnosis + 1 userAnswer.save() print(gejala0) if (len(gejala1) > 0): for i in range(0, len(gejala1)): userAnswer = UserAnswer() userAnswer.gejala_answer = gejala1[i] userAnswer.user_id = request.user.id userAnswer.number_diagnosis = user.number_diagnosis + 1 userAnswer.save() if (len(gejala2) > 0): for i in range(0, len(gejala2)): userAnswer = UserAnswer() userAnswer.gejala_answer = gejala2[i] userAnswer.user_id = request.user.id userAnswer.number_diagnosis = user.number_diagnosis + 1 userAnswer.save() if (len(gejala3) > 0): for i in range(0, len(gejala3)): userAnswer = UserAnswer() userAnswer.gejala_answer = gejala3[i] userAnswer.user_id = request.user.id userAnswer.number_diagnosis = user.number_diagnosis + 1 userAnswer.save() return redirect('diagnosis_penyakit:response_matching') else: raise Http404 I want to get the data what i choose from gejala_id0 form. I try to get the data like what i do in my views.py. … -
Django rest framework "Var must be a User Instance" vs "Object of type 'type' is not JSON serializable"
I'm trying to serialize a model having a foreign key "User". The concerned view snippet is: data = JSONParser().parse(request) serializer = SiteSerializer(data=data) if serializer.is_valid(): userid = data['supervisor'] user = User.objects.get(id=userid).__dict__ ## tried case I user = User.objects.get(id=userid) ## tried case II serializer.save(supervisor=user) return JsonResponse(serializer.data, status=201) The serializer is as : class SiteSerializer(serializers.ModelSerializer): supervisor = serializers.RelatedField(source='User', read_only=True) class Meta: model = Site fields = ('sitename', 'start_date', 'supervisor') The model is : class Site(models.Model): sitename=models.CharField(max_length=255) start_date=models.DateTimeField supervisor=models.ForeignKey(User,on_delete=models.PROTECT) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.sitename) When I pass supervisor object it says that object of type "Type" is not serializable and when I pass supervisor as dictionary it says that the dict variable supervisor must be a User instance. How do I sort this out and proceed?? -
Django 2 Adding Custom Template / View
i ve been looking around for couple of hours yet only old posts or kind of not simple explanations , here is my problem i customized the admin templates and now i have a left panel ( side navigation ) and a right panel for content , the thing is i want to make the django admin recognize my Additional templates so that the navigation finally works where each button refers to an HTML file . i'd be happy if someone out there guides me through this Error i'm getting : Using the URLconf defined in AdminDashWithNPMandBS.urls, Django tried these URL patterns, in this order: admin/ [name='index'] admin/ login/ [name='login'] admin/ logout/ [name='logout'] admin/ password_change/ [name='password_change'] admin/ password_change/done/ [name='password_change_done'] admin/ jsi18n/ [name='jsi18n'] admin/ r/<int:content_type_id>/<path:object_id>/ [name='view_on_site'] admin/ auth/group/ admin/ auth/user/ admin/ ^(?P<app_label>auth)/$ [name='app_list'] The current path, admin/index.html, didn't match any of these. -
Why I can't update my one-to-one model's FileField in Django?
In order to add more features to the default model, I employed one-to-one filed in Django. Then I want to customize my update/edit Userprofile page. I rewrite the update form like this : {% load static %} ... <div id="block-center" class="col-md-6 col-md-offset-3"> <form method="post"> {% csrf_token %} ... <div class="form-group"> <p> <label for="id_location">Location:</label> <input class="form-control" placeholder="Location"type="text" name="location" value="{{user.profile.location}}"maxlength="30" id="id_location" /> </p> </div> <div class="form-group"> {% if user.profile.upload.url%} <p class="file-upload">Currently: <img src="{{user.profile.upload.url}}" alt="Avatar" class="avatar"><br></p> <label for="id_upload">Change:</label> <input type="file" name="upload" value="{{user.profile.upload}}" id="id_upload" /> {% else%} <label for="id_upload">Avator:</label> <input type="file" name="upload" value="{{user.profile.upload}}" id="id_upload" /> {% endif %} </div> <button class="btn btn-primary" type="submit">Save changes</button> </form> </div> My models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) upload = models.FileField() @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() My views.py: from django.db import models from django.contrib.auth.models import User from users.forms import UserForm,ProfileForm from django.contrib import messages from django.shortcuts import render,redirect from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth import login,logout,authenticate from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required … -
boto3 ec2 & django
I'M new using django and python, i try to use aws ec2 API to create, start and stop instances in aws ec2: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#instance I found boto3 and i think that's the solution, but i don't know how to install in django framework i try using this in a view: import boto3 #import directly ec2 = boto3.resource('ec2') I think it's works but i receive the message: botocore.exceptions.NoRegionError: You must specify a region. According to boto docs i need to set my api keys and the region: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html, but where i put this data in django? For me this is not the best solution because I don't use INSTALLED_APPS in settings, is there a django package or a better solution to do? -
Fetch data from form at view
I am trying to fetch data in view when user click on submit at form in template. models.py class Posudba(models.Model): nazivKnjige = models.ForeignKey(Knjiga, on_delete=models.CASCADE, null=False) nazivProdavaca = models.ForeignKey(User, on_delete=models.CASCADE, null=False) nazivKupca= models.ForeignKey(Kupac, on_delete=models.CASCADE, null=False) datum = models.DateField(null=False, blank=False) kolicina = models.IntegerField(null=False, blank=False) def __str__(self): return str(self.nazivKnjige) + ', ' + str(self.nazivProdavaca) + ', ' + str(self.nazivKupca) + ', ' + str(self.Datum) class Knjiga(models.Model): naziv = models.CharField(null=False, blank=True, max_length=120) autor = models.ForeignKey(Autor, on_delete=models.CASCADE, null=True) datumObjave = models.DateField(null=True, blank=False) izdanje = models.CharField(null=True, blank=True, max_length=120) slika= models.FileField(upload_to='images/', null=True, verbose_name="") #videofile kolicina = models.IntegerField(null=False, blank=False) forms.py class PosudbaForma(forms.ModelForm): class Meta: model = Posudba fields = '__all__' views.py @login_required def UnosPosudbe(request): if request.method == 'GET': forma = PosudbaForma() elif request.method == 'POST': forma = PosudbaForma(request.POST,request.FILES) if forma.is_valid(): #Fetch data form_data = request.GET.copy() NazivKnjige = forma.get("Knjiga.kolicina") kolicina = forma.get("kolicina") #Dohvacanje Kolicine print(data) print(NazivKnjige) forma.save() return redirect('pregledPosudbe') return render(request, 'unosPosudbe.html', {'forma':forma}) So what I am trying to do is that I need to link Posudba.nazivKnjige to Knjiga and fetch kolicina, as fetch kolicina from posudba. But I am all time getting "None" value with: Fetch data form_data = request.GET.copy() NazivKnjige = forma.get("Knjiga.kolicina") kolicina = forma.get("kolicina") #Dohvacanje Kolicine print(data) print(NazivKnjige) -
Can not integrate my app with a text editor in django / python
Although I have tried several richtext editors like tinymce, but I am not being able to make it work, no error appears, the page loads normally, a field appears to be filled, but without any editing option. Try to use several ways I could find in google, but none was able to help me ----base.html <head> ... <!-- Tinymce Text-Editor (Must be in Head Tag) --> <script src="{% static '/tinymce/js/tinymce/tinymce.min.js' %}"></script> <script type="text/javascript" src="{% static 'js/custom.js' %}" ></script> ... </head> ---post_form.html {% extends "blog/base.html" %} <!-- {% load crispy_forms_tags %} --> {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> <!-- {{ form|crispy }} --> {{ form.as_p }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} ---- models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from simple_history.models import HistoricalRecords from tinymce.models import HTMLField class Post(models.Model): title = models.CharField(max_length = 100) versao = models.CharField(max_length=10, default=1) # content = models.TextField() content = HTMLField() resumo_das_mudancas = models.TextField(default='Não houve mudanças') date_posted = models.DateTimeField(default = timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs ={'pk':self.pk}) ..... ------settings.py … -
Django ajax update model
I'm having a problem with a simple task I want to accomplish. I want to load a list of models and when a user clicks on a button, I want to edit two fields of the selected instance of a model. I leave my model: class Enfermos(models.Model): TIPO_ANIMAL = [ ('terneros', 'Terneros'), ('terneras', 'Terneras'), ('vaquillas', 'Vaquillas'), ('toros', 'Toros'), ('vacas_viejas', 'Vacas Viejas'), ] tipo = models.CharField(choices=TIPO_ANIMAL, max_length=20) potrero = models.ForeignKey('campo.Potrero', on_delete=models.DO_NOTHING) enfermedad = models.ForeignKey('Enfermedad', on_delete=models.DO_NOTHING) fecha = models.DateTimeField(default=timezone.now) descripcion = models.CharField(null=True, blank=True, max_length=80, help_text='Si considera necesario agregar alguna descripción del animal enfermo aquí lo puede hacer. De lo contrario dejar vacio.') ESTADO = [ ('curado', 'curado'), ('muerto', 'muerto'), ('enfermo', 'enfermo'), ] estado = models.CharField(choices=ESTADO, max_length=10, default='enfermo') def __str__(self): return 'Un ' + self.tipo + ' con: ' + self.enfermedad.nombre_enfermedad The significant part of my template: <div class="container" style="min-height: 100%;height: 100%;"> <div class="row justify-content-center"> <div class="col-10"> <div class="py-3"> <h2>Panel de gestion de animales enfermos</h2></div> {% for e in enfermos %} <div class="row" style="border: double; margin-bottom: 20px; padding: 10px;"> <div class="col-8"> <h3>{{ e }}</h3> <span id="enfermo_{{ e.id }}" style="display: none;">{{ e.id }}</span> </div> <div class="col-2"> <button data-enfermo-id="{{ e.id }}" type="button" class="btn btn-primary c_curo">Curado</button> </div> <div class="col-2"> <button data-enfermo-id="{{ e.id }}" type="button" class="btn btn-danger … -
Django date fields never evaluate equal when compared
I have two instances of a model object, and I want to do something if they differ in one field, that happens to be a DateField but, when I evaluate wether they are different, they always are, even when they have the same date. This is the code that performs the comparison: for field in fields: if 'name' in field.__dict__: field_name = field.__dict__['name'] if field_name in instance.__dict__: new_value = instance.__dict__[field_name] old_value = old_instance.__dict__[field_name] if new_value != old_value: # This line always avaluates true when fields are DateField print("{} - {}".format(old_value, new_value)) if first: first = None else: detail = detail + '\n' detail = detail + field_name + ' = ' + str(old_value) + ' --> ' + str(new_value) I am printing new_value and old_value for debugging, and I find that date fields always evaluate different, even when they have the same date: I don't know if there is an specific way for comparing date values. -
Django (PostgreSQL) query filter to exclude given letters
The user sends one of the letters from the following alphabet and I want to sent appropriate response. As you can notice there is some mixture of Cyrillic and Latin. I have the following get_queryset method: def get_queryset(self): SPECIAL_CHARACTERS = [ 'Аь', 'Гl', 'Кх', 'Къ', 'Кl', 'Оь', 'Хь', 'Хl', 'Цl', 'Чl', 'Юь', 'Яь' ] queryset = WordChechenModel.objects.all().order_by('word_chechen') first_letter = self.request.query_params.get('letter', None) if first_letter is not None: if len(first_letter) == 2: queryset = queryset.filter( word_chechen__iregex=r"^w+%s" % first_letter) else: queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q( word_chechen__startswith=first_letter.upper())).exclude( word_chechen__startswith__in=SPECIAL_CHARACTERS) return queryset In case that user sends a request for double(mixture) letter I can filter that using regex, but if a user sends request lets to say with Аь or some of the SPECIAL_CHARACTERS characters than I have problems. Currently, I tried to exclude all words that start with one of the letters defined in SPECIAL_CHARACTERS using the following query: queryset = queryset.filter(Q(word_chechen__startswith=first_letter) | Q( word_chechen__startswith=first_letter.upper())).exclude( word_chechen__startswith__in=SPECIAL_CHARACTERS) return queryset But this gives me the following error: django.core.exceptions.FieldError: Unsupported lookup 'startswith' for CharField or join on the field not permitted, perhaps you meant s tartswith or istartswith? I would be very grateful for the ideas. The speed of processing the request is important. Therefore, it would nice … -
What's the fastest way to filter a django queryset based on a custom method?
I have a model that's recursive. Let's call it Organization. I have another model that is a child of Organization called Store. When Store's are listed in the application it is in a hierarchical format so we actually get the Organization's and include the recursive hierarchy below them. In the serializer we pass in parameters to filter the Store and we return None if the store does not match the filters. However, the catch is that the Organization will be still be returned even if it has no Stores which causes the table to have a bunch of empty pages if the Store does not match the filters. To counter this, in the viewset I want to filter the organizations based on whether or not they will have a store. queryset = [x for x in queryset if x.will_have_store()] def will_have_store(self): willHaveStore = False for organization in self.organizations.all(): willHaveStore = organization.will_have_store() if (willHaveStore): return True if (hasattr(organization, 'store') and organization.store.id ): willHaveStore = True return willHaveStore This is really close to working but it's painfully slow because it does a recursive check on every row in the database for every query. Is there anyway to make this faster? -
is it possible to extend SetPasswordForm to add custom css class form fields
forms.py from django.contrib.auth.forms import SetPasswordForm class PasswordChange(SetPasswordForm): < > urls.py path('password_change/',auth_views.PasswordChangeView.as_view( form_class=PasswordChange),name='password_change' ), i just want to add custom css class to the form fields. -
Creating Model instance with a randomly generated, human sized, unique id
I need a Model that has a field with a Random, Human-Sized, Unique key. We intend to use this for a human to brain-net the id to another computer and recall the data. What I have: def make_code(): numbers = "".join(random.choice(string.digits) for x in range(4)) letters = "".join(random.choice(string.ascii_lowercase) for x in range(2)) return numbers + letters class PinRecord(models.Model): pin = models.CharField(max_length=16, primary_key=True) data = models.TextField(blank=False, null=False) created = models.DateTimeField(auto_now_add=True) @classmethod def create_uniq(cls, action, data): created = False while not created: pin, created = cls.objects.get_or_create(pin=make_code(), defaults={'data':data}) return pin.pin Is there a better way to do create_uniq? Right now, there is a small chance that it loops for a long time, especially if the PinRecords don't get cleaned up properly or traffic is higher then expected. An alternate version that limits attempts to a finite number leaves us with nothing to give the user except a middle finger error. The recommended solution to the Random, Unique key problem seems to be uuid, but the users will object to writing down and retyping a uuid. -
Problem with foreign key field - Cannot assign "1": must be a "EstadoPessoa" instance
I'm creating a django app which contains user registration, but i'm stuck while I try to set the foreign key which indicates the user status (not defined, wanted or missing). Basically, 'EstadoPessoa' has 2 fields: one for the id and the other one for the status name. I created a choice element - which populates itself dynamically during migrations - and applied it in the foreign key field (as seen in PessoasProcuradas class). Models.py class GerenciadorEstados(models.Manager): def estados_possiveis(self): from django.db import connection cursor = connection.cursor() cursor.execute(""" SELECT ep.id_estado_pessoa, ep.nome_estado FROM estado_pessoa ep ORDER BY ep.id_estado_pessoa ASC""") lista_estados = cursor.fetchall() return lista_estados class EstadoPessoa(models.Model): id_estado_pessoa = models.AutoField(primary_key=True) nome_estado = models.CharField(max_length=25) objects = GerenciadorEstados() class Meta: db_table = 'estado_pessoa' class PessoasProcuradas(models.Model): ESTADO_PESSOA = EstadoPessoa.objects.estados_possiveis() cpf = models.CharField(verbose_name='CPF', primary_key=True, max_length=11, null=False, blank=False) nome_completo = models.CharField(verbose_name='Nome completo do indivíduo', max_length=50, blank=False, null=False) estado_pessoa_id_estado_pessoa = models.ForeignKey(EstadoPessoa, models.PROTECT, db_column='estado_pessoa_id_estado_pessoa', verbose_name='Estado do indivíduo', blank=False, null=False, choices=ESTADO_PESSOA, default=1) imagem_individuo = models.ImageField(verbose_name='Imagem do indivíduo', blank=True, null=True) class Meta: db_table = 'pessoas_procuradas' Forms.py class CadastroPessoas(ModelForm): class Meta: model = PessoasProcuradas fields = ['nome_completo', 'cpf', 'estado_pessoa_id_estado_pessoa', 'imagem_individuo'] Views.py def adicionar_individuo(request): from django.http import HttpResponseRedirect from .forms import CadastroPessoas form = CadastroPessoas(request.POST, request.FILES or None) if form.is_valid(): form.save() return HttpResponseRedirect('../results/usuario-adicionado') return render(request, … -
TypeError: unhashable type: 'collections.OrderedDict'
See image for reference See error for reference I'm facing this error whenever i try to send user object to members field which is many to many field as it is handing friends. I have tried by saving data through terminal but when i post it from django rest, it gives me error. class ProfileSerializer(serializers.ModelSerializer): """Profile Serializer""" class Meta: model = Profile fields = ('user','profile_name','image','profile_title') extra_kwargs = { 'image': {'read_only': True}, 'profile_name': {'read_only': True}, 'profile_title': {'read_only': True}, } class FriendsSerializer(serializers.ModelSerializer): """Serializer For Team Mambers""" members = ProfileSerializer(many=True) class Meta: model = Friend fields = '__all__' def create(self, validated_data): print(validated_data) user = validated_data['user'] members = validated_data['members'] instance = Friend.objects.create(user=user) instance.members.add(*members) return instance class FriendsViewSet(ModelViewSet): """ViewSet For TeamMembers Model""" serializer_class = FriendsSerializer lookup_field = 'user' queryset = Friend.objects.all() class Friend(models.Model): user = models.OneToOneField(User, related_name='creator', on_delete=models.CASCADE) members = models.ManyToManyField(Profile, blank=True) def __str__(self): return str(self.user.username) -
Use "like" and "more\less\equal" with filter
@login_required def pregledKnjiga(request): form = ChoiceForm(request.GET or None) data = Knjiga.objects.all() #data = list(Knjiga.objects.all()) form_data = request.GET.copy() mojNaziv = form_data.get("naziv") mojaKolicina = form_data.get("kolicina") if form.is_valid(): if mojNaziv != '': data = data.filter(naziv=mojNaziv) if mojaKolicina != '': data = data.filter(kolicina=mojaKolicina) return render(request, 'pregledKnjiga.html', {'data':data, 'form': form}) I have lines that filter my database and return some values. First I have line: data = data.filter(naziv=mojNaziv) It is searching if there is anything equal and returning it back, is it possible to make something like "Like" function in SQL that doesn't only look if it is exactly same, rather it should look if it has entered characters in searched name. For example if I have names: Josip Ante Mate And if I search for "Jo" it will return nothing but it should return all that has "Jo" in it. Other line is: data = data.filter(kolicina=mojaKolicina) That is integer field. My problem is if I put >= or => it give me error. Is it possible to search for greater\equal or less\equal that entered number? -
Django: can't update the user profile
Just wondering what could be the problem with a code. Got user profile, that should be edited not via django-admin. But getting '404 Page not found' error instead. Or if I put it in a main page id does not show anything at all, just a blank screen. I suppose its something either with urls. Could you advice me, please. my views: def edit_profile(request): if request.method == 'POST': edit_form = EditProfileForm(request.POST, instance=request.user.profile) if edit_form.is_valid(): edit_form.save() messages.success(request, 'Your account has been updated!') return redirect('user_profile') else: edit_form = EditProfileForm(instance=request.user.profile) context = {'edit_form': edit_form} return render(request, 'edit_profile.html', context) my models. Its a simple model, basically allows to edit the website. It is been created once User registers on site. class Profile(models.Model): website = models.URLField(default='') <...> def create_profile(sender, **kwargs): if kwargs['created']: profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) my forms. Nothing special again, just a standart form class EditProfileForm(UserChangeForm): class Meta: model = Profile fields = ('website',) urls: urlpatterns = [ url(r'^profile/$', profile, name="profile"), url(r'^profile/edit_profile/$', edit_profile, name="edit_profile"), ] profile.html just a link to edit_profile form, but shows empty if I just type in the address. Otherwise its 404 error. <form method="GET" action="edit_profile/{{ user.profile }}"> {% csrf_token %} <button type="submit" value="Edit">Edit</button> </form> edit_profile.html it does not display … -
Monaco-editor in django framework
How can I integrate the monaco-editor application in django? This is the monoco editor link https://microsoft.github.io/monaco-editor/ -
Django rest api problem: should either include a `querylist` attribute, or override the `get_querylist()` method
This is my serializer class: class JlistSerializers(serializers.ModelSerializer): class Meta: model = Jlist fields = ('id', 'name', 'news_channel', 'wiki', 'image', 'total_star', 'total_user') This is my views class JlistView(ObjectMultipleModelAPIView): queryset = Jlist.objects.all() def get_queryset(self, *args, **kwargs): userId = self.kwargs.get('pk') queryset = [ {'queryset': Jlist.objects.all(), 'serializer_class': JlistSerializers}, {'queryset': JStarList.objects.filter(userId=userId), 'serializer_class': JStarList} ] return queryset I am getting followiing error AssertionError at /api/jlist JlistView should either include a `querylist` attribute, or override the `get_querylist()` method. I have used the same code to create api for other serializer class but getting error in creating this api.Please help me figure out what is problem here? -
NOT NULL constraint failed - custom date in django simple history
I'm trying to create a custom model for the history_date field in django simple-history, but when trying to save to DB i'm getting the error NOT NULL constraint failed I already have some data in the current fields from the default history_date model - example 2019-05-29 19:19:03.922533 but I want to change that to Day/Month/Year I have imported datetime with from datetime import datetime Docs: https://django-simple-history.readthedocs.io/en/2.7.0/historical_model.html#custom-history-date Model: class NodesData(models.Model): Node = models.CharField(max_length=20, default="Anonymous Node") NodeIP = models.CharField(max_length=15) NodeCountry = models.CharField(max_length=30, default="Not Found") NodeCity = models.CharField(max_length=30, default="Not Found") NodeISP = models.CharField(max_length=30, default="Not Found") NodeLat = models.CharField(max_length=15, default="Not Found") NodeLon = models.CharField(max_length=15, default="Not Found") Node_id = models.CharField(max_length=128, default="Not Found") Node_Cores = models.CharField(max_length=15, default="Not Found") Node_Subtask_Success = models.CharField(max_length=15, default="Not Found") Node_Subtask_Error = models.CharField(max_length=15, default="Not Found") Node_Subtask_Timeout = models.CharField(max_length=15, default="Not Found") Node_Task_Requested = models.CharField(max_length=15, default="Not Found") Node_Blender_Performance = models.CharField(max_length=15, default="Not Found") Node_OS = models.CharField(max_length=10, default="Not Found") Node_OS_system = models.CharField(max_length=10, default="Not Found") Node_OS_release = models.CharField(max_length=25, default="Not Found") Node_OS_version = models.CharField(max_length=300, default="Not Found") Node_OS_windows_edition = models.CharField(max_length=25, default="Not Found", blank=True) Node_OS_linux_distribution = models.CharField(max_length=50, default="Not Found", blank=True) Node_Version = models.CharField(max_length=8, default="Not Found") Node_Memory = models.CharField(max_length=15, default="Not Found") Node_Disk = models.CharField(max_length=15, default="Not Found") history = HistoricalRecords() __history_date = None @property def _history_date(self): return self.__history_date @_history_date.setter def _history_date(self, value): value … -
Django's html email's inline css not working
I am trying to send a mail through HTML email. Everything is working perfectly, but the inline css of html file is not getting rendered in actual email. Here my html file : <html> <head> </head> <body> <div style="backgound-color:red;position:relative;width:100%;text-align:center;">Email Verification</div> Hi {{ user.username }}, </body> Please help! -
How to upload and display image django 2?
I tried to hardcode path and nothing worked. What's wrong with my code? I'm getting 404 error and image isn't showing up. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'blog/media') models.py image = models.ImageField(upload_to = 'media/', blank = True) urls.py urlpatterns = [...] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('author','title', 'text','image') widgets = { 'title': forms.TextInput(attrs={'class': 'textinputclass'}), 'text': forms.Textarea(attrs={'class': 'editable medium-editor-textarea postcontent'}), } html <img src="{{post.image.url}}"> -
DJANGO - Possible app_name issue ('password_reset_done' is not a valid view function or pattern name.)
I've been scouring the internet and here for a solution to my problem of Django not being able to find password_reset_done as a view and I am completely stuck. The error is shown below. I had previous issues with the password_reset_email.html saying it could not find it either untill I put 'LifeOfReillyApp:' before the password_reset_email in the {% url .... %}. {% load i18n %}{% autoescape off %} {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'LifeOfReillyJohnApp:password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The {{ site_name }} team{% endblocktrans %} {% endautoescape %} This is where I believe my issue stems from, using an app_name in my urls.py in my app, which is meant to be the correct thing to do. Using the fix in the password_reset_email.html only pushes the issue further down to password_reset_done.html. Below is my urls.py, if …