Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'objects' django
My views.py file is def studentFeedBack(request): studentid = '' courseid = '' teacherid = '' if request.method == 'POST': studentid_id = request.POST.get("studentid") studentid = studentid.objects.get(id=studentid_id) courseid_id = request.POST.get("courseid") courseid = courseid.objects.get(id=courseid_id) teacherid_id = request.POST.get("teacherid") teacherid = teacherid.objects.get(id=teacherid_id) description = request.POST.get("description") rating = request.POST.get("rating") studentFeedBack.objects.create( courseid=courseid, description=description, studentid=studentid, teacherid=teacherid, rating=rating ) return render( request, 'forms/studentFeedBack.html', { 'studentids':studentid.objects.all(), 'courseids':courseid.objects.all(), 'teacherids':teacherid.objects.all(), } ) and my models.py file is class StudentFeedBack(models.Model): feedbackid = models.AutoField(primary_key=True) courseid = models.ForeignKey('Course', on_delete=models.CASCADE) description = models.CharField(max_length=500) submitdate = models.DateTimeField(auto_now_add=True) teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE) studentid = models.ForeignKey('Student', on_delete=models.CASCADE) option = [('Good','Good'),('Average','Average'),('Bad','Bad')] rating = models.CharField(max_length=100, choices=option, default='none') class Course(models.Model): courseid = models.IntegerField(primary_key=True) coursedescription = models.CharField(max_length=500) coursename = models.CharField(max_length=50) userid = models.IntegerField() code = models.CharField(max_length=50) videolink = models.FileField(default='default_link') createddate = models.DateTimeField() imagelink = models.URLField(default='default_link') duration = models.DateTimeField() longdes = models.TextField() coursetype = models.CharField(max_length=50) assignto = models.CharField(max_length=200) status = models.BinaryField() def _str_(self): return self.coursename class Meta: db_table = "courseids" class schoolTeacher(models.Model): teacherid = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) address = models.CharField(max_length=200) email = models.EmailField() contact = models.IntegerField() passowrd = models.CharField(max_length=13) image = models.ImageField(default='default.jpg') regno = models.CharField(max_length=20) joiningdate = models.DateTimeField() def _str_(self): return self.name class Meta: db_table = "teacherids" class Student(models.Model): studentid = models.IntegerField(primary_key=True) regno = models.CharField(max_length=20) name = models.CharField(max_length=50) email = models.EmailField(max_length=50) contactno = … -
Django tag in tag
Hello i think i've a simple question but i can't solve it by myself or searching models.py class Sektorler(models.Model): Link_tr = models.SlugField(max_length=1000,verbose_name="Link - Tr",null=True,blank=True,unique=True) Link_en = models.SlugField(max_length=1000,verbose_name="Link - En",null=True,blank=True,unique=True) Isim_tr = models.CharField(max_length=200,verbose_name="İsim - Tr",null=True,blank=True) Isim_en = models.CharField(max_length=200,verbose_name="İsim - En",null=True,blank=True) def save(self, *args, **kwargs): self.Link_tr = slugify(self.Isim_tr) self.Link_en = slugify(self.Isim_en) super(BuyukUrunCesitleri, self).save(*args, **kwargs) At the template page for example index page: {% for pk1 in productcategory1 %} <div class="col" style="max-width: 200px"> <div class="card"> <img class="card-img-top" src="/static/Img1/ProductCategorys/{{pk1.Resim}}" alt="{{pk1.Isim_tr}}" /> {% union "pk1.Isim_" "tr" as aaaa%} <div class="card-body py-4 px-0 text-center"> <a class="stretched-link text-body" href="{% url 'products' productcategory='tasima-ekipmanlari' products=aaaa %}"> <h6>{{aaaa}}<small>(11)</small></h6> </a> </div> </div> </div> {% endfor %} First I made a simple tag who union strings but it didn't work for example return of {{aaaa}} = pk1.Isim1_tr(or en) but i want to value of pk1.Isim1_tr(or en). If you understand me, can you write direct code solution or someone said learn getattr but because every doc or lessons of language is english and i don't understand fully (For 2 full day i'm working on it and now i'm starting to become crazy). -
Lost connection to MySQL server at 'handshake: reading initial communication packet', system error: 104
Hi I'm trying to run my Django applications with docker but when I run docker-compose up it gives me the error. Lost connection to MySQL server at 'handshake: reading initial communication packet', system error: 104 Here is my docker-compose.yml version: '3' services: db: image: mysql:5.7 ports: - '3306:3306' environment: MYSQL_DATABASE: 'my_app' MYSQL_USER: 'root' MYSQL_PASSWORD: '12345' MYSQL_ROOT_PASSWORD: '12345' volumes: - /tmp/app/mysqld:/var/run/mysqld - ./db:/var/lib/mysql web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/vvouch - /tmp/app/mysqld:/var/run/mysqld ports: - "8000:8000" depends_on: - db I tried to even with different port and also I removed ports from docker-compose.yml file but it gives the same error. Anyone can please help me thanks in advance. -
Disable password suggestions in Django
So, basically I'm learning Django from some courses and I was trying to test my registration template. It works fine, but the problem is that I want to disable the password suggestions below the password field. They look like this: [password hints I want to turn off][1] I'm using a form which inherits from UserCreationForm called CreateUserForm, which looks like this: [enter image description here][2] So my question is - Is there any function command available in Django to make these hints dissapear? [1]: https://i.stack.imgur.com/kjJi3.png [2]: https://i.stack.imgur.com/yJ9zS.png -
Impossible to make a migration with mysql and django
I'm developing a web application with django on docker, on Windows 10. I'm getting an error when trying to do the data model migrations, and I've tried everything I've seen in other threads of this same topic. I'm using mysql. The error is shown below: I've installed python3-dev, default-libmysqlclient-dev, mysqlclient, python3-mysqldb but it still shows the same error. I also tried to install the wheel file from this site: enter link description here, but it indicates to me that it is not compatible, even having tried several files. You can see how my dockerfile is made: FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /proyectoCDN COPY requirements.txt . ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.7.3/wait /wait RUN chmod +x /wait RUN apt-get update RUN apt-get install -y python3-dev RUN apt-get install -y default-libmysqlclient-dev RUN apt-get install -y build-essential RUN apt-get install python3-mysqldb RUN pip install mysqlclient # COPY mysqlclient-1.4.6-cp39-cp39-win_amd64 . # RUN pip install mysqlclient-1.4.6-cp39-cp39-win_amd64.whl RUN pip install -r requirements.txt COPY . . EXPOSE 8000 EXPOSE 3306 the settings for my django project are shown below DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mariadb', 'USER': 'javier', 'PASSWORD': 'javier', 'HOST': 'db', # Or an IP Address that your database is hosted … -
Filter list in Raw Django
I have this query but It didn't filter the specific index. I just want to filter the paid_by column based on the emp_list, that's why I've come up with this indexes paid_by = emp[1].it would be great if anybody could figure out where I am doing thing wrong. thank you so much in advance. TypeError: 'Person' object does not support indexing emp_list = Person.objects.raw('SELECT id,paid_by, IF(paid = "Yes" || paid = "YES", "paid", "unpaid") as id,paid, category, category_status, count(paid) FROM app_person WHERE paid_by != "" GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid ') for emp in emp_list: paid_by = emp[1] #I want to filter paid_by in emp_list print(paid_by) -
How filter with less than or greater than value using (filter_fields) in Django REST API
I am able to filter with exact value but not sure how to filter with less that or greater than value. API used with postman to filter with exact value (failed for > or <) Filter code: class FilterView(ListAPIView): queryset = Products.objects.all() serializer_class = ProductSerializer filter_backends = (DjangoFilterBackend, SearchFilter,) filter_fields = ('stock','product_id') search_fields = ('product_id', 'product_name') P.S I tried something like filter_fields = ('stock**__gte**','product_id') but no luck. -
Reverse for 'service_fee' with arguments '('',)' not found. 1 pattern(s) tried: ['fees/(?P<service_id>[0-9]+)$']
I'm getting this error and I couldn't find why? Please help me with this error. Below is the code from my project urls.py path("fees/<int:service_id>", views.service_rates_view, name='service_fee') index.html {% for service in main_services %} <a href="{% url 'emitr:service_fee' service.id %}">{{ service.name }}</a> {% endfor %} view.py def service_fee_view(request, service_id): service = Service.objects.get(pk=service_id) subservices = service.subservice_set.all() return render(request, 'emitr/service.html', { 'service': service, 'subservices': subservices }) -
Specific Django Formset structure can't be saved
I have based my formset on the CRUD methodology. Taken code from here and there. The problem now is I can't save the model, the form_valid method is not called. The template looks like this: <form action="create" method=”POST”> {% csrf_token %} <div id="formset" data-formset-prefix="{{ formset.prefix }}"> {{ formset.management_form }} <div data-formset-body> {% for form in formset %} <div data-formset-form> {{ form }} </div> {% endfor %} <hr> </div> </form> The Formset class on which it is based is as follows: class Formset(LayoutObject): template = "doc_aide/formset2.html" def __init__(self, formset_name_in_context, template=None): self.formset_name_in_context = formset_name_in_context self.fields = [] if template: self.template = template def render(self, form, form_style, context, template_pack=TEMPLATE_PACK): formset = context[self.formset_name_in_context] # for form in formset: return render_to_string(self.template, {'formset': formset}) The form and view are as below: class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription exclude = ['handed_out', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3 create-label' self.helper.field_class = 'col-md-9' self.helper.layout = Layout( Div( Field('patient'), Field('note'), HTML('<hr class="style2">'), Fieldset('Add Drug', Formset('line_prescription')), HTML('<hr class="style1">'), ButtonHolder(Submit('submit', 'save')), ) ) class PrescriptionCreate(generic.CreateView): model = Prescription template_name = 'doc_aide/write_prescription4.html' form_class = PrescriptionForm def get_context_data(self, **kwargs): print('here') context = super().get_context_data(**kwargs) if self.request.POST: context['line_prescription'] = SinglePrescriptionFormset(self.request.POST) else: context['line_prescription'] … -
update tag (manytomany) fields in form post model django
model.py class Post(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True, blank = True) title = models.CharField(max_length = 100, null = False, blank= False) tag = models.ManyToManyField(Tag) class Tag(models.Model): title = models.CharField(max_length = 200) def __str__(self): return self.title form.py class UpdatePostForm(forms.Form): title = forms.CharField() def clean_title(self): data = self.cleaned_data['title'] return data tag = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Separate the tags with , or space','size':50})) def clean_tag(self): data = self.cleaned_data['tag'] return data views.py class UpdatePostView(LoginRequiredMixin, generic.UpdateView): model = Post #form_class = UpdatePostForm template_name = 'blog/update_post.html' success_url = reverse_lazy('blog:mypost_list') fields = ['title', 'tag'] def form_valid(self, form): tags = re.split("\s|(?<!\d)[,.](?!\d)", form.cleaned_data['tag']) for tag in tags: temp= Tag.objects.create( title = tag) form.instance.tag(temp) form.save() return super(UpdatePostView, self).form_valid(form) in template {{ form.tag.label }}: {{ form.tag }} now first porblem : in html page in user side i see select multiple tag so i can not type the new tag in this field just can select tags or unselected tags I want show tags in textbox and type new tag or delete old tags please help THANK YOU. -
unable to migrate to Heroku PostgreSQL- what kind of an error is this? Django project to heroku
This is a Django project of a simple blog. Github link: https://github.com/papansarkar101/easyBlog When I was trying to upload it on Heroku, everything is working fine but when I tried to connect it with Heroku PostgreSQL and migrate, it's showing this error. I have no idea what this error is. Environment: Request Method: GET Request URL: http://easyblogg.herokuapp.com/ Django Version: 3.1.4 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'members', 'ckeditor'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (relation "home_category" does not exist LINE 1: ...ome_category"."name", "home_category"."name" FROM "home_cate... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 545, in resolve for pattern in self.url_patterns: File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return … -
Django Form Ajax no refresh
I have been trying to develop a form within detailview, which I did. Now I would like it to send data to the database and to display the new data on the same page without refreshing. So I found a way to send the data to the database without refreshing, however, when it comes to display the new data without refreshing it does not work. I followed this tutorial : tutorial from red eye coder club Here is my code. models.py class ImportantFacts(models.Model): collection_important_facts = models.ForeignKey(Collection, related_name="has_important_facts", on_delete=models.CASCADE, null=True) note = models.TextField(max_length=400, verbose_name='Note') forms.py class ImportantFactsForm(forms.ModelForm): class Meta: model = ImportantFacts fields = ['note'] views.py class CollectionDetail(LoginRequiredMixin, FormMixin, DetailView): model = Collection form_class = ImportantFactsForm template_name = 'taskflow/collection_detail.html' success_url = None def get_context_data(self, **kwargs): context = super(CollectionDetail, self).get_context_data(**kwargs) context['important_facts'] = ImportantFactsForm() return context def post(self, request, *args, **kwargs): form = ImportantFactsForm(request.POST) tgt = self.get_object() if form.is_valid(): new_fact = form.save(commit=False) new_fact.collection_important_facts = tgt new_fact.save() return JsonResponse({'fact': model_to_dict(new_fact)}, status=200) else: return redirect('taskflow:collection_all') facts.js $(document).ready(function(){ $(".btn").click(function() { var serializedData = $("#createFactForm").serialize(); $.ajax({ url: $("createFactForm").data('url'), data: serializedData, type: 'post', success: function(response) { $("#canal1").append('<div class="card mb-1"><div class="card-body">' + response.fact.note + '<button type="button" class="close float-right"><span aria-hidden="true">&times;</span></button></div></div>') } }) $("#createFactForm")[0].reset(); }); }); collection_detail.html <div class="tab-pane active" id="Canal1"> … -
Replace image on mouse click using jQuery and Django doesn't work
so I want to replace an image when it is clicked using jQuery. Here is how my code looks like. HTML {% load static %} <div class="col-md-6 image"> <img class="map" src="{% static 'home/map.png' %}" class="doctors"> </div> jQuery $(document).ready(function() { $('.map').click(function() { $(this).attr("src", "{% static 'home/map2.png' %}"); }); }) I tried the code above and it didn't work. The location of the image and its image format is already correct but when I click the image it only shows a blank picture (the same display as when we write the wrong image format). I already tried to change the jQuery into this one too $('.map').click(function() { $(this).attr("src", "home/map2.png"); }); but it still didn't work. Anyone knows how to fix it? -
Input Type for ManyToMany Field with Graphene in Django
I am getting error when try Mutation on graphiql: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. How can i set it, what should i write for category = in types.py in InputObjectType based QuestionInput class? My files are below: models.py from django.contrib.postgres.fields import ArrayField from django.db import models from ..common.models import CommonFields from ..kategoriler.models import Kategori class Question(CommonFields): question = models.TextField() answer = ArrayField(models.TextField()) rightAnswer = models.TextField() category = models.ManyToManyField("Kategori") DIFFICULTY_CHOICES = ( ('Easy', 'easy'), ('Medium', 'medium'), ('Hard', 'hard'), ('Very Hard', 'very hard'), ) difficulty = models.CharField(max_length=10, choices=DIFFICULTY_CHOICES, default="medium") def __str__(self): created_at = self.created_at.strftime("%b %d %Y %H:%M:%S") return f"Q : {self.question[:7]} , Created at : {created_at}" types.py import graphene from graphene import relay, ObjectType, InputObjectType from graphene_django import DjangoObjectType from ..models import Question class QuestionNode(DjangoObjectType): class Meta: model = Question filter_fields = [] interfaces = (relay.Node, ) class QuestionInput(InputObjectType): question = graphene.String(required=True) answer = graphene.String(required=True) rightAnswer = graphene.String(required=True) category = graphene.????????? difficulty = graphene.String(required=True) create_question.py import graphene from graphene import relay from ...models import Question from ..types import QuestionNode, QuestionInput class CreateQuestion(relay.ClientIDMutation): class Input: question_inputs = graphene.Field(QuestionInput) question = graphene.Field(QuestionNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): question = Question.objects.create(**input.get("question_inputs")) question.save() return CreateQuestion(question=question) -
Why django geo map not working correctly?
I have already installed django ,postgresql, postgis, Qgis and GDAL Map show like this. Nothing to show on the map at models.py: from django.contrib.gis.db import models class Shop(models.Model): name = models.CharField(max_length=200) location = models.PointField() address = models.CharField(max_length=200) city = models.CharField(max_length=50) at setting.py: try: import gdal gdal_path = Path(gdal.__file__) OSGEO4W = os.path.join(gdal_path.parent, 'osgeo') os.environ["OSGEO4W_ROOT"] = OSGEO4W os.environ["GDAL_DATA"] = os.path.join(OSGEO4W, "data", "gdal") os.environ["PROJ_LIB"] = os.path.join(OSGEO4W, "data", "proj") os.environ["PATH"] = OSGEO4W + ";" + os.environ["PATH"] GEOS_LIBRARY_PATH = str(os.path.join(OSGEO4W, "geos_c.dll")) GDAL_LIBRARY_PATH = str(os.path.join(OSGEO4W, "gdal301.dll")) except ImportError: GEOS_LIBRARY_PATH = None GDAL_LIBRARY_PATH = None if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] -
SimpleLazyObject instead of User in re-usable Django app?
I used user model User in my Django app in filter or create queries like that: # FILTER queries self_posts = ( Post.objects .prefetch_related('stage') .filter(Q(stage__assignee__isnull=False, stage__assignee=request.user)) .exclude(stage__slug__in=['vault', 'published']) ) ... # CREATE one if form.is_valid(): post = form.save(commit=False) post.editor = request.user post.save() Then I packaged my app into re-useable Django module. As my User has several additional fields and methods compared to standard Django one, I created a proxy model. In my package it points to my local proxy model, but has access to actual "global" user, provided by main app auth system: class User(UserModel): # Proxy user model in packaged app class Meta: proxy = True class Meta: permissions = ( ("manage_authors", "Can manage authors"), ) ... Since that, inside my packaged app views I can't assign request.user directly to User-like fields, but still can use in filter queries. (Pdb) request.user <SimpleLazyObject: <User: koowpjcs>> (Pdb) request.user.user <User: John Doe> So, Post.objects.filter(foo=request.user) will still work, but post.editor = request.user wiil fail: Cannot assign "<SimpleLazyObject: <User: koowpjcs>>": "Post.editor" must be a "User" instance. Why it happend? Is it realated to re-usable app or with defining custom proxy model? Is it correct to replace all calls of request.user to request.user.user in re-usable … -
Django Documentation Tutorial NoReverseMatch at /polls/1/results/
Please help me, I'm new to django and I have error like this: """Reverse for 'vote' with no arguments not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']""" In polls.views def vote(request, question_id): question = get_object_or_404( Questions, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{'question':question, 'error_message':"You didn't select a choice."} ) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Questions, pk = question_id) return render(request,'polls/result.html',{'question':question}) polls url_patterns urlpatterns = [ path('',views.index,name='index'), path('<int:question_id>/',views.details, name='details'), path('<int:question_id>/results/',views.results, name='results'), path('<int:question_id>/vote/',views.vote, name='vote') ] And polls/result.html <h1>{{question.question_text}}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{choice.choice_text}} -- {{choice.votes}} votes {{choice.votes|pluralize}}</li> {% endfor %} </ul> <a href="{% url 'polls:vote' %}">Vote Again?</a> -
Required attribute is not working Djnago Template
Here, I am trying to build a quiz website. I want, all answers must be submitted. But the required attribute is not working. <section class="allquiz"> <div class="sectionarea"> <form action= '' method = "POST" > {% for question in questions %} <div class = 'question'>Q{{ question.question_name }} </div><br> <div id= "choices" class='select' required> <input type = "radio" name="{{forloop.counter}}" value="A{{question.pk}}">{{question.option_a}}<br> <input type = "radio" name="{{forloop.counter}}" value="B{{question.pk}}">{{question.option_b}}<br> <input type = "radio" name="{{forloop.counter}}" value="C{{question.pk}}">{{question.option_c}}<br> <input type = "radio" name="{{forloop.counter}}" value="D{{question.pk}}">{{question.option_d}}<br> </div> <br> {% endfor %} <div style="text-align:center"> <input style="padding: 10px 35px;font-size:120%;cursor: pointer;" type="submit" class="submit" id="submit" value="Submit"/></div> {% csrf_token %} </form> </div> -
IF clause in Django filter
I'm having a trouble on how can I translate my query to Django format, The problem is I'm wondering if it is possible to have a if clause inside Django queries, So I have this format , Is there any expert can help me with this format. query SELECT paid_by, IF(paid = 'Yes' || paid = 'YES', 'paid', 'unpaid') as paided, category, category_status, count(paid) FROM `app_person` What I tried app_person.objects.filter((paid = 'Yes' ||paid = 'YES', 'paid', 'unpaid')as 'paided', 'category', 'category_status', 'count(paid)') -
Unable to authenticate custom user in Django 3
I am unable to authenticate custom user in django==3.1.3 Here is Custom User Manager: from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if username is None: raise TypeError(_('Users should have a username.')) if email is None: raise TypeError(_('Users should have a Email.')) user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError(_('Password should not be empty.')) user = self.create_user(username, email, password) user.is_superuser = True user.is_staff = True user.save() return user Here's the CustomUser model: from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import CustomUserManager class CustomUser(AbstractBaseUser): 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) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email I have added AUTH_USER_MODEL = 'authentication.CustomUser' in settings.py (authentication is the app name) In the shell, if I run these, I get authenticated_user as None: user = CustomUser.objects.create(email='tejas@gmail.com', username='tejas12', password='tejas12') authenticated_user = authenticate(email='tejas@gmail.com', username='tejas12', password='tejas12') However, the User gets created successfully with given details. Also, check_password returns False: from django.contrib.auth.hashers import check_password user.check_password('tejas12') # returns False … -
Parsing returned json from Django async rest call
I am in process of learning Django to build a smaller application that consumes a swagger REST API. When I am testing the API, I get a lot of JSON output, that I need to take, filter(change values) and send back via PUT, POST (typical stuff.) I have tried the async client sessions with return of json_response like this: async def get_some_jsonrest_value_back(response): async with ClientSession() as session: async with session.get('http://example.com', headers={'X-API-KEY':' fdfsdfdfff', 'Content-Type':'application/json'}, json={}) as resp: response = await resp.json() return json_response(response, text=None, body=None, status=200, reason=None, headers=None, content_type='application/json') I do get the values like these: { "key1": "values1", "key2": { "@subkey1": "54534543", "@subkey2": "fdsfdsfdsf", "subkey3": [ "fdsfsdfdsf" ], "subkey4": "fdfsdfds", "subkey5": "8594593489" }, "key3": "8594859438594385943", "key4": "kfdlskfldsk" } And the values grow, with many sections of that JSON output. There can be like hundreds of those JSONs. My question would be , if someone could point me to some examples of django code, which consumes API, returnes the JSON values and for an example takes out only the subkeys from 1 to 5 (like in json example in output). After that it changes the values and returns back to the external REST API via POST/PUT. Thanks in advance. -
Reading .sql with python and using data
I am completely new to SQL, but I know Python a little. I just programmed Version 2 of another 10 years old project of mine. The old project has a .sql file. For the new project, I made same alterations in the database. Now to test it, I want to read the old .sql file, make some calculations with it's data and populate the new database with the old data and the newly made calculations. How is it best done? (I don't know wheter it makes a difference, but it's a django project and there I use an .sqlite3 at the moment.) -
Django Query Works on python shell but it didnt work in template and forms
i tried the same code on forms in shell. the code working like i want. but when it deploy from Forms.py to html template instead become [models_name].objects.all() in forms.py main_page_choices = MainPage.objects.filter(parent_check=2).values_list('id', 'page_link') main_page_choices_list = [] for main_page in main_page_choices: main_page_choices_list.append(main_page) class AdminCreateSubPageForm(forms.ModelForm): class Meta: model = SubPage fields = ( 'sub_title', 'sub_title_tag', 'sub_page_link', 'body', 'parent_page', 'meta_keyword', 'meta_description') widgets = { 'sub_title': forms.TextInput( attrs={'class': 'form-control', 'id': 'sub_title', 'onchange': 'autotypelink()'}), 'sub_title_tag': forms.TextInput(attrs={'class': 'form-control', 'id': 'sub_title_tag'}), 'sub_page_link': forms.TextInput(attrs={'class': 'form-control', 'id': 'sub_page_link'}), 'body': forms.Textarea(attrs={'class': 'form-control', 'id': 'body'}), 'parent_page': forms.Select(choices=main_page_choices_list, attrs={'class': 'form-control', 'id': 'parent_page'}), 'meta_keyword': forms.Textarea(attrs={'class': 'form-control', 'id': 'meta_keyword', 'rows': '4'}), 'meta_description': forms.Textarea(attrs={'class': 'form-control', 'id': 'meta_description', 'rows': '4'}), } my models.py class MainPage(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255) page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) category = models.ForeignKey(Category, default="", on_delete=models.CASCADE) parent_check = models.ForeignKey(ParentCheck, default="", on_delete=models.CASCADE) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) USERNAME_FIELD = 'user' REQUIRED_FIELDS = [] def __str__(self): return self.page_link def get_absolute_url(self): return reverse("main-list-admin") class SubPage(models.Model): sub_title = models.CharField(max_length=255) sub_title_tag = models.CharField(max_length=255) sub_page_link = models.SlugField(max_length=255, unique=True) body = RichTextField(blank=True, null=True, config_name='special', external_plugin_resources=[ ('youtube', '/static/ckeditor_plugins/youtube/youtube/', 'plugin.js'), ] ) parent_page = models.ForeignKey(MainPage, default="", on_delete=models.CASCADE) meta_description = models.TextField(null=False, blank=False) meta_keyword = models.TextField(blank=False, null=False) USERNAME_FIELD = … -
I am new to python and django when I try to migrate my file i am receiving error
from django.db import models class employees(models.Model): GENDER_CHOICES= [ ('M,''Male'), ('F',"Female"), ] first_name= models.CharField(max_length=100) last_name=models.CharField(max_length=1000,blank=True) email_id =models.EmailField(max_length=255) phone_nuber = models.CharField(max_length=10) employees_gender = models.CharField(choices=GENDER_CHOICES,max_length=1) employees_address= models.TextField() employees_job=models.ManyToManyField('availableJobs',blank=True) date_of_birth= models.DateField() class availableJobs(models.Model): name = models.CharField(max_length=100) Received the following error: ERRORS: employees.employees.employees_gender: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. -
Change download location to "Downloads" in Pytube in Python
I want to change the download location to "Downloads" in pytube in Python. Can anyone tell me how to do this? Thanks in advance:)