Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: Convert string representative of a string array to a list
I am trying to convert a string representative of a string array containing double quotes, single quotes and commas in its array items in to a python list when that array is passed to an API endpoint over postman. (Im am using Python 3.6) Ex: value passed in postman "data":["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"] element 1 = "bacsr "attd" and, fhhh'''" element 2 = "'gehh', uujf "hjjj"" element 3 = ",,,hhhhh,, " element 4 = "1" What I tried and failed: post_values = request.data['data'] post_values = ast.literal_eval(post_values) Gives this error: During handling of the above exception (invalid syntax (, line 1)), another exception occurred: How can I convert this in to a 4 element list with relevant string escapes? -
How to have PyCharm suggest code completion for Django
I have the following code: from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase) def test_newUserEmailNormalized(self): email = "test@TEST.COM" user = get_user_model().objects.create_user(email, 'test123') I want PyCharm to suggest autocompletion on the last line when I write get_user_model(). but it only suggests main, not, par. And when I write get_user_model().objects. I want it to suggest auto-completion options including create_user but it doesn't suggest anything. How do I enable PyCharm to help me with autocompletion here? These are my AutoCompletion settings: -
DRF - Route to Obtain Token
What is the best way to create route to obtain a token? I want a browsable API. urls.py router = routers.DefaultRouter() router.register(r'tokens', views.TokenViewSet) views.py class TokenViewSet(viewsets.ViewSet): queryset = Token.objects.all() serializer_class = AuthTokenSerializer def create(self, request): serializer = AuthTokenSerializer(data=request.POST) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) This solution works, but don't return actions in OPTIONS. -
Django communication of api from one app to another app
I am working on a Django project Example: I have a model in app 'A', named UserBooks I wrote API in views for sending all the Books owned by an User in the format of JsonResponse Hence I am able to use it as a Simple Json Response and test it in Postman Now my problem is, in app 'B', I have user_books.html template When I access a particular Url which will call the user_books view, I have to access data from API of app 'A' for UserBooks which is JsonResponse, now I have to convert it into dictionary or again convert that data to Model that we have earlier and then pass it to the template to render the data into that view I am looking for a solution that will be easy for this process Here's the details about the project It has two apps -> A, B In app 'A' I wrote models and API's In app 'B' I wrote views that will map data from API of app 'A' I want to use app 'A' for accessing API which gives responses in Json format But in app 'B' all the views are connected to templates and … -
why django signal not working with custom User model?
I am creating a Django signup form through User model and UserCreationForm and customized the User model to accommodate single user defined field contact. 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 SignUp(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Contact = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: SignUp.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import SignUp class SignUpForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) # phone = format() class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class CustomSignUpPage(forms.ModelForm): Contact = forms.CharField(max_length=10) class Meta: model = SignUp fields = ('Contact', ) views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages #from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm, CustomSignUpPage def home(request): return render(request, 'authenticate\home.html', {}) def login_user(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ('login success')) return redirect('home') else: messages.success(request, ('error while login, please try again')) return redirect('login') else: return render(request, … -
How to get datetimefield as string in django queryset's values_list() function?
I have a model which contains a datetime field. I need to write the rows from that model table to excel sheet. As the model field is datetime field, when writing to the excel, it's writing a number like 45976 etc for dates instead of 2020-04-01 as string. I'm getting values of rows using queryset.values_list(*fields_to_fetch) This fields_to_fetch contains the datetimefield I'm looking for. When I print the type, it is saying DateTimeField in the console. Is there any way to get the datetimefield as string type? I was able to convert each item in the values_list() to list and then the datetimefield into string and append it to a new list and write to excel. I'm looking for a way to avoid all this. -
How do I remove to_field from django model?
I have a model like this: class MyModel(models.Model): field_1 = models.ForeignKey(User, related_name='some_name', to_field='unique_id') # more fields In this I want to remove my to_field from field_1, but when I did this, I got error while migrating. django.db.utils.DataError: (1265, "Data truncated for column 'field_1' at row 1") I think the cause of problem is that unique_id is string while my primary key is int, and data already stored in my db is unique_id, which I want to change to id. Is there any good way to achieve this? -
Django Wizard Form problems
I have multiple page form, and i want in to add this feature (course.tutor.add(request.user)(Here course is my model and tutor is field in it) to the view class FormWizardView(SessionWizardView): template_name = 'courses/create_course.html' file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,'courses')) form_list = (CourseForm1,CourseForm2,CourseForm3,CourseForm4) def done(self, form_list, **kwargs): instance = Course() for form in form_list: for field, value in form.cleaned_data.items(): setattr(instance, field, value) instance.save() return redirect('courses:my_courses',username=self.request.user.username) I want to add same feature to my function. I did needed row in capital def create_group(request): group_form = GroupForm() if request.method == 'POST': group_form = GroupForm(request.POST,request.FILES) if group_form.is_valid(): new_group = group_form.save() NEW_GROUP.ADMINS.ADD(REQUEST.USER) new_group.subscribers.add(request.user) return redirect(new_group.get_absolute_url()) else: group_form = GroupForm() return render(request,'groups/create_group.html',{'group_form':group_form}) -
slug 404 not found in django
Here is my views.py from .models import Post,Author def posts_list(request): all_posts = Post.objects.all() context = { 'all_posts': all_posts } return render(request,"post_list.html",context) def posts_detail(request, slug): unique_post = get_object_or_404(Post, slug=slug) context = { 'post': unique_post, } return render(request,"posts_detail.html",context) and my urls.py is: from django.urls import path from posts import views urlpatterns = [ path('admin/', admin.site.urls), path('post/',views.posts_list), path('post/(<slug:slug>/', views.posts_detail,name='post'), ] every time i go to http://127.0.0.1:8000/post/first i get 404 page not found i tired reloading my django server and find others solution too but i cannot figure out what the problem upto https://http://127.0.0.1:8000/post the route is working but after slug not working please help me to solve this issue. -
Django Taggit: how to add tags as listed annotation to queryset.values()
I'm having some conceptual difficulty with understanding how to annotate a queryset for objects which have an attribute of "tags" as defined in the django-taggit library: class MyObject(models.Model): ... tags = TaggableManager(blank=True, verbose_name="Tags") When querying for this object, I want a .values() list, but for some reason...the tags field is not there...I'd ideally like to .annotate() my queryset with a list of the tag names: e.g., instance['tags'] = ['tag1', 'tag2']... Has anyone achieved this before? -
Why do I get the "cannot serialize error" when I try to migrate my model?
Well I'm very new to django, so I got lost easily. I'm trying to build my model, using my sql model as reference (I suppose that's the way people do). I solved most errors, but the last one is killing me and I don't find help on the net. This is my code : from django.core.validators import RegexValidator from django.utils import timezone # Create your models here. class PhoneModel(models.Model): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be: '+999999999'. Max 15 digits.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list class Room(models.Model): number = models.IntegerField(primary_key=True, unique=True) duration = models.IntegerField(default="3") max_score = models.IntegerField(default="100") name = models.CharField(max_length=30) status = models.CharField(max_length=15, default="inactive") class Credit(models.Model): value = models.CharField(max_length=3) class Language(models.Model): name = models.CharField(max_length=20, default="chinese") class Token(models.Model): token_id = models.IntegerField(primary_key=True, unique=True) class Level(models.Model): value = models.IntegerField(default="1") class Event(models.Model): name = models.CharField(max_length=80) phone_number = models.ForeignKey(PhoneModel, blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField('date of event') members = models.IntegerField() credit = models.ForeignKey(Credit, on_delete=models.DO_NOTHING) language = models.ForeignKey(Language, on_delete=models.SET_DEFAULT, default="chinese") level = models.ForeignKey(Level, on_delete=models.SET_DEFAULT, default="1") class Team(models.Model): name = models.CharField(max_length=80) token_id = models.ForeignKey(Token, blank=True, null=True,on_delete=models.SET_NULL) event_id = models.ForeignKey(Event, on_delete=models.CASCADE) language = models.ForeignKey(Language, on_delete=models.SET_DEFAULT, default=Event.language) level = models.ForeignKey(Level, on_delete=models.SET_DEFAULT, default=Event.level) players_number = models.IntegerField(default="3") end_time = models.DateTimeField() activation_status = models.BooleanField(default=True) active_room = models.ForeignKey(Room, … -
eCommerce website- Updating Cart Items in Django
UnboundLocalError at /cart/ - error message from website carts/views.py", line 24, in update_cart if not product in cart.products.all(): UnboundLocalError: local variable 'product' referenced before assignment this is the error message I receive when I click the 'add to cart' button on my website. - error message in terminal views.py - here is my views for the cart. From my understanding the issue seems to be in this file. from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here . from fuisce.models import Product from .models import Cart def view(request): cart = Cart.objects.all()[0] context = {"cart": cart} template = "cart/view.html" return render(request, template, context) def update_cart(request, product_id): cart = Cart.objects.all()[0] try: product = Product.objects.get(product_id=product_id) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) return HttpResponseRedirect(reverse('cart')) ***urls.py*** from django.urls import path from . import views from carts import views as cart_views urlpatterns = [ path('cart/', cart_views.view, name='cart'), path('cart/<product_id>', cart_views.update_cart, name='update_cart'), ] ***models.py - cart *** from django.db import models # Create your models here. from fuisce.models import Product class Cart(models.Model): products = models.ManyToManyField(Product) total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def __string__(self): return "Cart id: … -
Uploaded file in Django Rest Framework and processing the request for zip
I'm having difficulty knowing how to process the HTTP request from an uploaded file within the Django Rest Framework. The create endpoint in my views.py: def create(self, request): file_iobytes = request.FILES["file"].file self.zipping(file_iobytes) serializer = FileSerializer(data=request.data) # converts to JSON if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) def zipping(self, file): # Create a buffer to write the zipfile into zip_buffer = io.BytesIO() # Create the zipfile, giving the buffer as the target with zipfile.ZipFile(zip_buffer, 'w') as zip_file: #file.seek(0) zip_file.write(file) file.close() My intention is: upload file via DRF create hash from file eg sha1 (which I don't know how to directly because the hashing requires a path, and I don't know how to retrieve this from the http request). zip the file and store it How can I use the request to create a zip file (is this the right approach)? -
How to remove Important dates section from Django User view?
I want to remove Important dates section from django Admin User view. Tried this: class UserAdmin(admin.ModelAdmin): exclude = ('last_login', 'date_joined',) admin.site.unregister(User) admin.site.register(User, UserAdmin) But it's saying: "Key 'last_login' not found in 'UserForm'. Choices are: email, first_name, groups, is_active, is_staff, is_superuser, last_name, password, user_permissions, username." How to remove this section from default User view django admin. Thanks -
Is it possible to write a mobile app using python as back-end and react as a front-end
I'm pretty much new to the developer business and I'll say I'm at a beginner level in javascript (I can do DOM manipulation) and intermediate level in python. I was wondering could I write an app for code I wrote in python as it's back-end and use react as a front-end, the question might be silly seeing as I'm new to developing and there might be some technicalities I'm overlooking, but any how I'd appreciate your help and advice. -
Django QuertySet.annotate() received non-expression
First time with Django. Trying to add an annotation to queryset: class EnrollmentManager(models.Manager.from_queryset(EnrollmentCustomQuerySet)): COURSE_DURATION = datetime.timedelta(days=183) def get_queryset(self): """Overrides the models.Manager method""" lookback = make_aware(datetime.datetime.today() - self.COURSE_DURATION) qs = super(EnrollmentManager, self).get_queryset().annotate(is_expired=(Value(True)), output_field=models.BooleanField()) return qs At the moment I am just trying to add an extra 'calculated' field on the returned queryset, which is hard-coded to True and the attribute/field should be called is_expired. If I can get that to work, then Value(True) needs to be a derived value based on this expression: F('enrolled') < lookback I guess the problem is not understanding how annotate works... -
Custom Logo Django JET2
I can't add my logo, what am I doing wrong? CODE {# Template: your_app/templates/admin/base_site.html #} {% extends "admin/base_site.html" %} {% load static i18n %} {# Setup favicon #} {% block extrahead %}<link rel="shortcut icon" type="image/png" href="{% static 'projetoOuvidoria/imagens/unisc.png'%}"/>{% endblock %} {# Setup browser tab label #} {% block title %}{{ title }} | {% trans "Your title" %}{% endblock %} {# Setup branding #} {% block branding %} <h1 id="site-name"> <a href="{% url 'admin:index' %}"> {# Your logo here #} <img style="background-color: white" src="{% static 'projetoOuvidoria/imagens/unisc.png'%}" alt="Your Company Name" height="50%" width="50%"> <br><br> </span> {% trans "Your Branding" %} </a> </h1> {% endblock %} Image of my project, its architecture enter image description here -
How can I use 'json_script' template tag within Django 1.1.2 so that I can utilise SPA VueJs/ReactJs
I am wanting to bring VueJs/ReactJs into a current project that mainly uses Python templates. We are using Django 1.1.2 that does not have the wonderful template tag that converts a Python object to JSON. Once I have the JSON object, I can then use the data within the VueJS framework. Is there an alternative tag within Django 1.1.2 that would allow me to convert a Python object to JSON? I am unable to update Django at this point in time. -
How to order_by a many to many field in template?
When I try to render a manytomany object in the template. My models.py is: class Class(models.Model): id = models.CharField(max_length=8, primary_key=True) name = models.CharField(max_length=255) members = models.ManyToManyField(User, related_name='member') texts = models.ManyToManyField(Messages) class Messages(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) id = models.CharField(max_length=8, primary_key=True) messages = models.TextField(blank=False, null=False) time = models.DateTimeField(auto_now_add=True) I've rendered this in my template: {% for text in class.texts.all %} <div class="card col-md-4 w-75 l-balloon mb-2"> {{text.messages|linebreaks}} <span class="font-small d-block ml-auto mr-3">{{text.time}}</span> </div> {% endfor %} And this is what I used in my views.py: context = { "class": Class.objects.get(id=pk) } Here I am just passing a single object of the class where I want to render the texts of the related class. While rendering {{text.messages|linebreaks}} it is ordered by the values of messages attribute of Message class. I want this to be ordered by time attribute. How can I acheive? -
Assign foreign key in DRF POST request
How I can directly add user which already login, when I create company? Models: class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True View: class CompanySetupView(ModelViewSet): queryset = Company.objects.all() permission_classes = [IsAuthenticated] serializer_class = CompanySetupSerializer Serializer: class CompanySetupSerializer(serializers.ModelSerializer): class Meta: model = Company fields = '__all__' -
User authentication failing while user login in django
I am trying to create a simple login page using python and django. My registration/signup is working fine and I am able to register the user. once the user is registered, while logging in the user using username and password the user is not authenticated. I am not able to find out the exact error, can anyone please guide me through this. This is my views.py file from django.shortcuts import render from django.views.generic import TemplateView, DetailView, ListView from django.contrib.auth import login,logout,authenticate from django.contrib.auth.decorators import login_required from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect from custom_login_app.forms import CustomUserInfoForm from custom_login_app import models # Create your views here. # about template view class AboutView(TemplateView): template_name = 'about.html' # user profile detail page class ProfileDetailView(DetailView): context_object_name = 'user_detail' model = models.CustomUserInfo template_name = 'userinfo_detail.html' # home page view def index(request): return render(request,'index.html') # logout view @login_required def customlogout(request): logout(request) return HttpResponseRedirect(reverse('index')) # registration view def registration(request): # bool variable to chcek the user is registered registered = False # check the user has poste the data through the form if request.method == 'POST': # create a form object user_form = CustomUserInfoForm(data=request.POST) # check if the form is valid if user_form.is_valid(): # save the … -
Unable to login after PUT operation Django REST Framework
I'm having the following problem: the login request returns "Unable to login with provided credentials" after I do a PUT request (changing fields like first_name, last_name, address) even though the username and password are correct in the DB. The following view I use to make my Login Request. class RetrieveAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) resp = Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email, 'role': user.role, }) return resp And these are for my users and registration of a user: from users.models import User from users.serializers import UserSerializer, RegistrationSerializer from rest_framework import viewsets, generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response # Create your views here. class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() class RegistrationView(generics.CreateAPIView): model = User serializer_class = RegistrationSerializer My serializers look like this: from rest_framework import serializers, status from users.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(style={'input_type': 'password'}) class Meta: model = User fields = '__all__' extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): instance = super(UserSerializer, self).update(instance, validated_data) instance.set_password(validated_data['password']) instance.save() return instance class RegistrationSerializer(serializers.ModelSerializer): password … -
Django - Profile doesn't change
I want my users to be able to change their information, when I click "Enregistrer" (Save), I'm redirected but there's no success message and my informations don't change. I think I've setup everything correctly and I looked at similar questions but it still doesn't work. models.py : from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaut.png', upload_to='image_profil') def __str__(self): return f'{self.user.username} Profil' forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profil class FormulaireModifUtilisateur(forms.ModelForm): username = forms.CharField( label = 'Nom de compte', min_length = 4, max_length = 150, initial=User.username, ) email = forms.EmailField( label = 'Email', min_length = 4, max_length = 150, ) class Meta: model = User fields = ['username', 'email'] class FormulaireModifProfil(forms.ModelForm): class Meta: model = Profil fields = ['image'] profils.html : {% extends 'home/index.html' %} {% block title %} Profil {% endblock %} {% block content %} <div id='profil'> <img src='{{ user.profil.image.url }}'> <form> {% csrf_token %} {% for field in u_form %} <p> {{ field.label_tag }}<br> {{ field }<br> </p> {% endfor %} {% for field in p_form %} <p> {{ field.label_tag }}<br> {{ field }}<br> </p> {% endfor %} … -
DjangoChannels consumers
I am very interested in the idea to write a chat application. I've recently come across great tutorial at https://channels.readthedocs.io/en/latest/index.html using DjangoChannels All understood, wrote my own one (suppose the same as there), everything is working. However, I ran into a problem: when updating the chat page, the server throws this exception (and after that I can't send messages, so that's quite harmful): Exception in callback AsyncioSelectorReactor.callLater..run() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287 handle: .run() at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 81, in _run self._context.run(self._callback, *self._args) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py", line 290, in run f(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/daphne/server.py", line 229, in application_checker exception = application_instance.exception() asyncio.exceptions.CancelledError (I am using WebsocketConsumer, python 3.8.2) Actually, I suppose there is a problem with the disconnection with the server when updating the page. I tried to solve it myself but unfortunately didn't succeed :( Could anybody please help me? -
Django Transaction Error: 'You can't execute queries until the end of the 'atomic' block.'
I'm trying to upload a list to my Database. I get this error when I try to migrate. Django Transaction Error: 'You can't execute queries until the end of the 'atomic' block.' From what I have read I have to do something with transaction.atomic(). But it's not clear to me where/what I need to do with that function. Can someone explain where the problem is occurring? restaurants = [ ["Cecilware HWD3 Black 3 Gallon Hot Water Dispenser - 120V", 581.62, 737.78], ["Avamix BXSSJAR 1 Gallon Stainless Steel Blender Jar", 149.99, 206.40], ["Brother HL-L8360CDW Business Color Laser Printer", 328.94, 405.25], ] def change(apps, schema_editor): New_Products= apps.get_model("Home_Page", "New_Products") for restaurant in restaurants: name = restaurant[0] old_price = restaurant[1] new_price = restaurant[2] New_Products.objects.create( Product_Name=name, Old_Price=old_price, New_Price=new_price, ) class Migration(migrations.Migration): dependencies = [ ('Home_Page', '0001_initial'), ] operations = [ migrations.RunPython( change ), ] ```