Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
str' object has no attribute 'get Django Python
Now I have one more problem. Could you please help? Thank You in advance :) An error: AttributeError: 'str' object has no attribute 'get'. . And the code password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): password = password_form.save() try: for i in password.text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request,'kod.html', {'key': key}) return render(request, 'start.html', {'password_form': password_form}) ``` I would be grateful for answer ! Natalia -
ImportError: attempted relative import with no known parent package DJANGO
I am following a tutorial on how to work with django and i cant figure out what this error happens. This is Admin.py from django.contrib import admin from .models import Genre, Movie class GenreAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(Movie) admin.site.register(Genre, GenreAdmin) and this is models.py: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) There are in the same parent folder. -
How to override existing '/api/products/' to return more fields in Django-osacr-api?
Django-oscar-api-override setup I am new to Oscar Api, And I need to added extra fields to the default '/api/products' response. Additional fields to add: description, meta_title, meta_description, rating, attributes from oscar.core.loading import get_class from rest_framework import serializers from oscarapi.serializers import checkout, product from oscarapi.serializers.product import ( ProductImageSerializer, ProductLinkSerializer) class MyProductLinkSerializer(ProductLinkSerializer): images = ProductImageSerializer(many=True, required=False) class Meta(ProductLinkSerializer.Meta): fields = ('url', 'id', 'title', 'images', 'rating', 'meta_title', 'meta_description') I tried the above code from documentation to see if it overrides. But no luck. Can you please help to add additional fields to the default response ? or point me any sample project repo where you they overrided default response. Thank you in advance. -
'undefined likes' twitter like project
Recently I started working on a twitter like clone to learn some python and django. I have successfully added "tweets" and got them to display some basic text on my homepage. My issue is with the like button. I am attempting to have a like button that will display the total amount of likes on that "tweet". For now I am using a random int just to display the likes. However the button just displays "undefined Likes". I thought it was going to be pretty straight forward however i am still new to all this so any help pointing me in the right direction would be appreciated. Thanks all. views.py: import random from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render from .models import Prediction # Create your views here. def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def prediction_list_view(request, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data """ qs = Prediction.objects.all() predictions_list = [{"id": x.id, "content": x.content, "likes": random.randint(0, 122)} for x in qs] data = { "isUser": False, "response": predictions_list } return JsonResponse(data) def prediction_detail_view(request, prediction_id, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data … -
TypeError: object of type 'Listeningfilter' has no len()
this error appear when using django-filter with pagination. this my filter.py, view.py code. I need to add pagination to django-filter I display data in html table. the error appear in this Listening_filter = paginator.get_page(page_number) line. class Listeningfilter(django_filters.FilterSet): listentime = django_filters.DateFromToRangeFilter( label='By Date Range', method='filter_by_range', widget=RangeWidget(attrs={'class': 'datepicker', 'type': 'date'}) ) class Meta: model = Listening fields = [ 'listentime', 'serviceshortcode', ] def filter_by_range(self, queryset, name, value): listenTime_from = value.listenTime_from listenTime_to = value.listenTime_to return queryset.filter(transaction_time__gte=listenTime_from, transaction_time__lte=listenTime_to) def listeningReportView(request): Listening_filter = '' form = ListeningSearchForm(request.POST or None) if request.method == 'POST': listenTime_from = request.POST.get('listenTime_from') listenTime_to = request.POST.get('listenTime_to') serviceCode = request.POST.get('serviceCode') Listening_filter = Listeningfilter( request.GET, queryset = Listening.objects.filter(listentime__lte=listenTime_to, listentime__gte=listenTime_from, serviceshortcode=serviceCode).order_by('listeningid'), ) # pagination paginator = Paginator(Listening_filter , 2) page_number = request.GET.get('page') try: Listening_filter = paginator.get_page(page_number) except EmptyPage: Listening_filter = paginator.page(paginator.num_pages) if not Listening_filter: messages.error(request, "no data availabe") context = { 'form': form, 'Listening_filter': Listening_filter, } return render(request, 'charge/listening.html', context) -
Unable to see the lines in chart.js
I am trying to make a django website which will display a chart that is updated every 1sec. I dont know why but except for the lines everything else is getting update a snapshot of the graph with the console log. the code below is my jquery in the html page {% block jquery %} <script> var updateInterval = 20 //in ms var numberElements = 5 var values = [] //Globals var updateCount = 0 var endpoint = '/api/chart/data' var ctx = document.getElementById('myChart'); var gchart = new Chart(ctx, { type: 'line', data: { label: [], datasets: [{ label: 'Wholesale 24 K', data: [], fill: true, borderColor: 'rgb(245, 0, 0)', tension: 0.1, parsing: { yAxisKey: 'b1' } }, { label: 'Retail 24 K', data: [], fill: true, borderColor: 'rgb(245, 225, 0)', tension: 0.1, parsing: { yAxisKey: 's24K' } }] }, options: { interaction: { mode: 'index', } }, }) function addData(chart, label, data) { console.log(data) chart.data.labels.push(label); chart.data.datasets.forEach((dataset) => { dataset.data.push(data); }); if (updateCount > numberElements) { gchart.data.labels.shift(); gchart.data.datasets[0].data.shift(); gchart.data.datasets[1].data.shift(); } else updateCount++; chart.update(); } setInterval(ajaxcal, 1000) function ajaxcal() { $.ajax({ method: "GET", url: endpoint, success: function (data) { var lal = data.time addData(gchart, lal, data) }, error: function (error_data) { console.log(error_data) … -
Django generate template doesn't correct
Django generate wrong template, why? code: <a class="one_menu_part" href="{% url 'projects_list' %}"> <img src="{% static 'icons/projects.svg' %}" alt=""> Projects <ul class="projects_list"> {% for project in projects %} <li class="project_part"><a href="{{ project.url }}">{{ project.title }}</a></li> {% endfor %} </ul> </a> <hr> <a class="one_menu_part" href="{% url 'admin_panel:admin_panel' %}"> <img src="{% static 'icons/admin_settings.svg' %}" alt=""> Admin Setting </a> in browser: Why ul generate after tag A, but in code tag ul must generate in tag A -
Unexpected result : "detail": "Method \"GET\" not allowed."
I am learning django restframework for the first time , and I am not able to debug this error since a while , please help in debugging this issue. Thanks! HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } Here is my code of views.py from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() -
Django: QuerySet.update() returns FieldError when using Count() with filter
Given that: class User(models.Model): organization = models.ForeingKey( "Organization", related_name="users", ... ) is_active = models.BooleanField(default=True) class Organization(models.Model): user_count = models.IntegerField(default=0) When I run this, if we run line 2 or 3 exclusively, both fail: # Line: 1 active_count = Count("users", filter=Q(users__is_active=True)) # Line: 2 Organization.objects.update(user_count=active_count) # Line: 3 Organization.objects.annotate(num_users=active_count).update(user_count=F("num_users") I get the following error: FieldError: Joined field references are not permitted in this query Annotating (annotate()) instead of updating, works just fine. I couldn't find examples of this solution using Subquery() What's an alternative to this requirement? Am doing making a design mistake perhaps? -
Models Django not iterable
I have some problems with Django models, I would like to iterate data got from the textfield from the form based on model. But I can't it still an error: TypeError at /kod/start/ 'Passwords' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/kod/start/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'Passwords' object is not iterable Exception Location: /home/natalia/PycharmProjects/django_project/kodszyfru/views.py, line 52, in start Python Executable: /home/natalia/PycharmProjects/django_project/venv/bin/python3 Python Version: 3.8.10 Python Path: ['/home/natalia/PycharmProjects/django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/natalia/PycharmProjects/django_project/venv/lib/python3.8/site-packages'] Server time: Fri, 22 Oct 2021 16:03:53 +0000 Code models.py from django.db import models # Create your models here. class Passwords(models.Model): text = models.TextField(max_length=2000,null=True) cipher = models.CharField(max_length=64) def __str__(self): return self.text views.py def start(request): password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): text = password_form.save() try: for i in text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request, 'kod.html', {'kod': kod}) return render(request, 'start.html', {'password_form': password_form}) I would be grateful for help!! Natalia -
Apply filter to field with lookup
I have seen a couple of similar questions on StackOverflow (Troubleshooting "Related Field has invalid lookup: icontains", Django error Related Field got invalid lookup: icontains, Related Field got invalid lookup: icontains, Django: Unsupported lookup 'case_exact' for CharField or join on the field not permitted, Filtering on Foreign Keys in Django) but unfortunately the answers on those questions have not helped me. If a hotel only has four double rooms and there are already four bookings for the first week of October, I want to prevent the next user being able to make a fifth booking for the first week of October. This was working - RoomBookings.objects.filter(HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType, ArrivalDate__lt=RoomBookingsForm['DepartureDate'], DepartureDate__gt=RoomBookingsForm['ArrivalDate']) But then I changed the HotelName field in the RoomBookings model from CharField to ForiegnKey. And now I cannot figure out how to do a reverse lookup. These are my failed attempts - # queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName_exact=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__HotelName_exact=hotel.HotelName) class Hotel(models.Model): HotelName = models.CharField(max_length=60, null=False) HotelOwner = models.CharField(max_length=60, null=True) FirstLineAddress = models.CharField(max_length=60, null=False) SecondLineAddress = models.CharField(max_length=60, null=True) PostCode = models.CharField(max_length=60, null=False) Country = CountryField(max_length=120, null=True) PhoneNumber = PhoneNumberField(null=True, blank=False, unique=True) Email = models.EmailField(max_length=254) def __str__(self): return self.HotelName class RoomType(models.Model): HotelName … -
How to add new field in model after custom migration which access model before new field?
I have custom migration file which creates entry in table user. Initial working project has these migrations: 1. 001_initial.py # creates model with some fields 2. 002_custom_user_data.py # adds data in "user" due some middle requirement after some time. Now I want to add one more column to this table as "config_data". For this I have followed below steps: 1. python manage.py makemigrations <app-name> # creates one more migration file` 003_add_config_data_field.py 2. python manage.py migrate # raise an error migrate command raises below error. Applying my_user.001_initial.py... OK Applying my_user.002_custom_user_data.py ...Traceback (most recent call last): File "/home/myhome/.local/share/virtualenvs/myproject/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column my_user.config_data does not exist LINE 1: ..., "my_user"."address", This is because migration 002 tries to access my_user table before the add field migration(003) is migrated in the table, which is raising UndefinedColumn config_data error. Any idea how can be this resolved as these migrations should work for fresh DB as well as production dB in which till 002 is migrated earlier. Below is the migration for 002_custom_user_data.py # Generated by Django 3.2.2 from django.db import migrations from myapp.models import MyUser def create_user(apps, schema_editor): user = MyUser.objects.get_or_create(id=123) user.address = 'demo' user.save() def delete_user(apps, schema_editor): MyUser.objects.filter(id=123).delete() class … -
When I loop through from the database and render it to the page with VUE-Js v-for , it becomes disorganized
So when I loop through my data from the API, I am trying to fit the data into bootstrap rows and columns, but it keeps getting rendered wrongly. I am using the VUE-Js v-for directive to loop through the data I am getting from my Django rest API.[enter image description here][1] This is when I pass the data to the component [[1]: https://i.stack.imgur.com/UGtRp.png][1] This is when I am trying to loop through the data[ [1]: https://i.stack.imgur.com/OjsZF.png][2] This is how it renders to the page [[1]: https://i.stack.imgur.com/bRZRy.png ] -
¿Como filtrar las opciones de un campo select en base al valor de otro campo del mismo tipo en un formulario Django? [closed]
El problema que tengo es el siguiente, quiero acceder al valor seleccionado en tiempo real de un campo select en mi formulario y en base a este, filtrar las opciones para el cliente. El campo en específico es el que corresponde en el model Request al atributo product_type, el cual según la opción que seleccione a partir de un choice, se filtre el segundo campo, el de product (Product tiene una fk que apunta al product_type) mis models.py class ProductType(models.Model): name = models.CharField("Nombre", max_length=100) def __str__(self): return f'{self.name}' class Product(models.Model): name = models.CharField("Producto", max_length=250) price = models.IntegerField("Price") type = models.ForeignKey(ProductType, on_delete = models.CASCADE) def __str__(self): return f'{self.name}' class Request(models.Model): CUSTOMER_TYPE = [ ('IND', 'Individuos'), ('NEG', 'NEGOCIOS'), ] COMPANIES = [ ('CLA', 'Claro'), ('PER', 'Personal'), ('TUE', 'Tuenti'), ('MOV', 'Movistar'), ('OTR', 'Otro'), ] types = ProductType.objects.all() PRODUCT_TYPE = [] for o in types: key = o.name[:3] value = o.name t = (key,value) PRODUCT_TYPE.append(t) customer_type = models.CharField(max_length=150, choices=CUSTOMER_TYPE) product_type = models.CharField(max_length = 150, choices = PRODUCT_TYPE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_of_sale = models.DateTimeField(auto_now_add=True) request_source = models.ForeignKey(RequestSource, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #Portability current_company = models.CharField(max_length=150, choices=CUSTOMER_TYPE) mobile_to_carry = models.CharField("Número a portar", max_length=13) pin = models.IntegerField("Pin") #Internet services address_coordinates = … -
Please help: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$']
I am new to django and I am having trouble implementing the edit template to my project. I am encountering the following error: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$'] I have looked on the site for similar occurrences such as Reverse for 'plan_edit' with keyword arguments but I haven't been able to pin point the issue. I believe the issue arises when I add a hyperlink to my all_clients.html template. Also, the template pages for /clients/edit_client/?/ will load, however after submission using the save changes button the NoReserse Match error resurfaces as it attempts to load the clients/all_clients page. Any help on this matter would be greatly appreciated. See code below: models.py from django.db import models # Create your models here. class Client(models.Model): #A client is composed of the company general info text = models.CharField('Company Name',default = 'Company Name', max_length = 200) phone_num = models.CharField('Phone Number', default = '000-000-000', max_length = 12) ceo_name = models.CharField ('CEO', max_length = 50) num_employees = models.IntegerField('Number of Employees', default = 0) maintenance_schedule = models.CharField('maintenance schedule', max_length = 100) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Location(models.Model): #Location holds … -
Can I delete the third-party Python library `future` after moving exclusively to Python 3?
The future module (https://pypi.org/project/future/) is "the missing compatibility layer between Python 2 and Python 3." I have a Django project that was ported from Python 2 to 3 long ago, but future is still a requirement. My question is: now that the project only needs to run on Python 3, is there much danger in deleting the requirement for future? My own investigations: After deleting future from requirements.txt, the unit tests still pass. Grepping my project source, I don't see any imports of builtins, which future shadows in Python 2. The future docs say The imports have no effect on Python 3. On Python 2, they shadow the corresponding builtins, which normally have different semantics on Python 3 versus 2, to provide their Python 3 semantics. So deleting future seems pretty safe, but is there anything I'm missing? Thanks. -
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable
here is my django project's urls.py from django.urls import path from .import views from django.conf import settings from django.conf.urls import static urlpatterns = [ path('',views.index,name='home'), path('abouts/about/',views.about,name='about'), path('abouts/contact/',views.contact,name='contact'), path('orders/cart/',views.cart,name='cart'), path('shops/dashboard/',views.dashboard,name='dashboard'), path('shops/orders/',views.orders,name='orders'), path('shops/checkout/',views.checkout,name='checkout'), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) and the part of settings.py where I defined media url and media root import os # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [ BASE_DIR/ 'static', ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') but the server says ile "C:\Users\ITS\Desktop\e-com\commerce\shop\urls.py", line 15, in <module> ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable I do this always but now it showing me this. thanks in advance for helping. -
show the particular table row based on checkbox
I want to display the table row based on the multi choice selection where I'm retrieving the data from the database there would be 1000+ rows among that I need to display only the particular row. I'm noob in JavaScript and took this snippet from How to show table rows based on checkbox selected I tried to modify the code as per the requirement but I couldn't able to figure out. I have cut the td part to reduce the code length there would be 16 columns around. pls help me out if any other JS script would be provided also it would be much helpful. <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> </tr> </tbody> <script> // checkbox selection function filter_type(box) { //alert("checked"); var cbs = document.getElementsByTagName('input'); var all_checked_types = []; for(var i=0; i < cbs.length; i++) { if(cbs[i].type == … -
Automatic reply/confirmation emails for Django CMS form
does anyone have experience with configuring/overriding the Django CMS FormPlugin to send out automatic confirmation emails? -
Multiple images for a project in django
Am creating a web app in django where I have a model called projects which carries data of a project with an image. I have another model called ProjectImages which allows one to add multiple images to a project. I am trying to query the images related to a specific project but they are mot being rendered on the webpage. I will appreciate any help. Here are my models models.py class Projects(models.Model): title = models.CharField(max_length=100, null=True, blank=True) image = models.FileField(upload_to='media/images', null=True, blank=True) video = models.FileField(upload_to='media/videos', null=True, blank=True) description = models.TextField(null=True, blank=True) client = models.CharField(max_length=300, null=True, blank=True) completed = models.BooleanField(default=True) def __str__ (self): return self.title class Meta: verbose_name_plural = 'Projects' ordering = ('-id',) class ProjectImages(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images', blank=True, null=True) def __str__ (self): return self.project.title forms.py more_project_images = forms.FileField(required=False, widget=forms.FileInput(attrs={ 'class':'form-control', 'multiple':True })) class Meta: model = Projects fields = '__all__' views.py form = ProjectsForm() if request.method == "POST": form = ProjectsForm(request.POST, request.FILES) files = request.FILES.getlist('more_project_images') if form.is_valid(): project = form.save() for f in files: project_image = ProjectImages(project=project, image=f) project_image.save() projectdetails.html {% for project in project.projectimages_set.all %} <div class="col-md-3 p-2"> <img src="{{project.image.url}}" class="img-fluid" style="object-fit: contain;" alt=""> </div> -
Django REST framework unrecognized
I already have django rest framework installed in my project, as you see when I run pip freeze: However, when I try to import any module it does not recognize it, so it is not possible for me to go check the function or class or whatsoever I am importing. Who knows what the problem is? -
Send Event after Celery Signal call
I have a Django project and call a task named my_task and listen to different signals which are sent by the task. I am using django_eventstream inside my project to send to my eventstream. from django_eventstream import send_event when I listen for celery builtin signal after_task_publish the following way @after_task_publish.connect(sender='my_task') def task_sent_handler(sender=None, headers=None, body=None, **kwargs): print("task_sent") message = "task_sent" send_event("eventchannel", "my_event", message) the message is sent to my existing eventstream and is working as expected. print statement is printed into webserver console but when I listen to celery builtin signal task_success the following way @task_success.connect(sender=my_task) def task_success_handler(sender=None, result=None, **kwargs): print("task_success") message = "task_success" send_event("eventchannel", "my_event", message) send_event will not be sent to my eventstream print statement will print into celery worker console I am struggling to find the reason for that behavior. What is the difference between both signals or what is the difference between both functions which are triggered by the signals? Following Versions are used: Django=3.2.6 celery=5.1.2 redis=3.5.3 django-eventstream=4.2.0 -
UNIQUE constraint failed: post_author.href in django
I will create a different author table using the user table available in django and I want to combine this custom table I created with the column in the post model. Thus, I will have both the author table and the post table with the posts shared by these authors separately. And also, I will make the user models that I will create in the future with the ready user table. but I am getting the error I mentioned. How can I solve this, what are the alternative ways? from django.db import models from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse from .utils import get_read_time from django.conf import settings from django.utils import timezone from markdown_deux import markdown from django.utils.text import slugify from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.safestring import mark_safe class GENDER(models.TextChoices): Erkek = "Erkek" Kadın = "Kadın" Diğer = "Diğer" NONE = "Belirtmek İstemiyorum" class Category_Choices(models.TextChoices): BİLİNMEYENLER = '13İlinmeyenler' KİŞİSEL_GELİŞİM = 'Kişisel Gelişim' İLHAM_AL = 'İlham Al' YATIRIM_HABERLERİ = 'Yatırım Haberleri' GİRİŞİMCİLİK = 'Girişimcilik' ENGLİSH_NEWS = 'English News' BAŞARI_HİKAYELERİ = "Başarı Hikayeleri" class Color_Choices(models.TextChoices): INDIGO = 'indigo' green = 'green' yellow = 'yellow' RED = 'red' blue = 'blue' gray = 'gray' … -
Import "rest_framework" could not be resolved "django-rest-framework"
I have installed the Django framework but it always shows a yellow line under it as if the project is not defined Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'rest_framework.routers', 'hauptapp', ] views.py Zb Import "rest_framework" could not be resolved When i write pip freeze find Django==3.2.7 django-environ==0.7.0 django-filter==21.1 django-import-export==2.5.0 django-mssql-backend==2.8.1 django-mssql-backend-aad==0.2.1 django-pyodbc==1.1.3 django-rest-framework==0.1.0 djangorestframework==3.12.4 djangorestframework-csv==2.1.1 -
Django REST Framework - How to compare two given values?
at my Django API application, I have a serializer that should validate a given pin but I'm always running into: TypeError: string indices must be integers def validate_old_pin(self, value): user = self.context['request'].user if value['old_pin'] != user.pin: # <- Breakpoint raise serializers.ValidationError( ({'old_pin': _("Your old PIN was entered incorrectly. Please try again.")}) ) return value Why do I get this? What is the most effective way to simply check if the two pin field match? Thanks in advance.