Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Null in response which should't exist Django
When I send request in Postman like this: it returns me all fields fine expect the profile_photo. profile_photo in response is null and I don't know what is the problem. It should be the new uuid photo name. Here is my model: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=150, blank=True) description = models.CharField(max_length=1000, blank=True) profile_photo = models.CharField(max_length=500, blank=True) date_joined = models.DateTimeField(default=timezone.now) about = models.TextField(_( 'about'), max_length=500, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccountManager() object = models.Manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'city'] def __str__(self): return self.email This is my view: class CustomUserUpdate(generics.UpdateAPIView): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserUpdateSerializer def get_object(self): return self.request.user This is my serializer. Here i am setting the new photo name. When I print the new name here like this: print(instance.profile_photo) it shows me the new file name fine. But in the response i get null. class UserUpdateSerializer(serializers.ModelSerializer): profile_photo = serializers.FileField(required=False) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'city', 'description', 'profile_photo') def __init__(self, *args, **kwargs): super(UserUpdateSerializer, self).__init__(*args, **kwargs) self.fields['email'].required = False self.fields['description'].required = False def update(self, instance, validated_data): if … -
InconsistentMigrationHistory with devstack make dev.provision command
I followed this guide All of the services can be run by following the steps below. For analyticstack, follow Getting Started on Analytics_. NOTE: Since a Docker-based devstack runs many containers, you should configure Docker with a sufficient amount of resources. We find that configuring Docker for Mac_ with a minimum of 2 CPUs and 6GB of memory works well. Install the requirements inside of a Python virtualenv_. .. code:: sh make requirements The Docker Compose file mounts a host volume for each service's executing code. The host directory defaults to be a sibling of this directory. For example, if this repo is cloned to ~/workspace/devstack, host volumes will be expected in ~/workspace/course-discovery, ~/workspace/ecommerce, etc. These repos can be cloned with the command below. .. code:: sh make dev.clone You may customize where the local repositories are found by setting the DEVSTACK_WORKSPACE environment variable. Be sure to share the cloned directories in the Docker -> Preferences... -> File Sharing box. Run the provision command, if you haven't already, to configure the various services with superusers (for development without the auth service) and tenants (for multi-tenancy). NOTE: When running the provision command, databases for ecommerce and edxapp will be dropped and … -
How to put data from DRF form in function
thank you for reading, i have problem in Django Rest Framework project, i wrote only backend, and i must return url with user info from fields: models.py class Payment(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT) # we cannot delete user with money # em email = models.CharField(max_length=255, blank=False, null=True) # m shop_id = models.CharField(max_length=30, blank=False, null=True) # oa amount = models.DecimalField(default=0, max_digits=12, decimal_places=2) class Curency(models.TextChoices): UAH = 'UAH' USD = 'USD' EUR = 'EUR' KZT = 'KZT' RUB = 'RUB' # currency currency = models.CharField( max_length=10, choices=Curency.choices, default=Curency.USD ) # o order_id = models.CharField( max_length=255, null=True, blank=False, unique=False) # s sign = models.CharField(max_length=255, blank=False, null=True) url = models.CharField(max_length=1000, null=True) def __str__(self): return f'Payment {self.user} of game {self.order_id}' serializers.py class PaymentSerializer(serializers.ModelSerializer): # in order to work you should add related_name in Action model class Meta: model = Payment fields = '__all__' # balance is read only, because i don't want someone create account # with money read_only_fields = ('id', 'shop_id', 'sign', 'user', 'email') views.py class PaymentViewSet(viewsets.ModelViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, ): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, ) serializer_class = PaymentSerializer queryset = Payment.objects.all() def get_queryset(self): """Return object for current authenticated user only""" return self.queryset.all() def perform_create(self, serializer): serializer.save(user=self.request.user) serializer.save(email=self.request.user.email) shop_id = … -
Saving a PDF Document generated in js.PDF to a Django Project Directory
I currently create a PDF in Django using js.PDF that gets download to wherever the web browser directs it to on my local computer. I would like to instead have it saved in a directory in my Django project that is hosted in Pythonanywhere.(i.e. /home/abraner/ABS/absdatabase/pdfs) Below is my current JavaScript code. Any suggestions would be appreciated. async function generatePDF(){ document.getElementById("downloadButton").innerHTML = "Currently downloading, please wait"; var downloading = document.getElementById("whatToPrint"); var doc = new jsPDF('1', 'pt'); await html2canvas(downloading, { allowTaint: true, useCORS: true, width: 798 }).then((canvas) => { doc.addImage(canvas.toDataURL("image/png"), 'PNG', 5, 5, 585, 800); }) doc.save("Document.pdf"); window.location.replace('../emailproposal'); } -
React.js and Django switching foreign key into name problem
I got Game model with 2 foreign keys away_team and home_team, both come from Club model. I got data from them rendered from the API to React.js like this: const AllGames = () => { //Simplified Game object const [games, setGames] = useState([{ away_score:"", away_team:"", home_score:"", home_team:"", id:'' }]); //Simplified Club object const [clubs, setClubs] = useState([{ name:'', id:"" }]) useEffect(() => { loadAllGames(); },[]) useEffect(() => { loadAllClubs(); }, [games]) const loadAllClubs = () => { getAllClubs() .then((data) => { setClubs(data) }) .catch((error) => console.log(error)) } const loadAllGames = () => { getAllGames() .then((data) => { setGames(data) }) .catch((error) => console.log(error)) }; With this piece of code everything is loaded smoothly, the problem is when I try to render the data: return ( <Base> {games.map((game) => { return ( <p> Home) {game.home_team}: {game.home_score} Away){game.away_team}: {game.away_score} </p> ) })} </Base> ) } export default AllGames; The output looks like Home) 1: 34 Away) 2: 51 It displays id of the club instead of a name. I know there was a function to switch game.home_team and game.away_team from being id's to being proper names (aka: text variables like "Team Name Example") TLDR; I need to swap home_team or away_team in games … -
How to create a graphql mutation with a relation in Django
I have a problem with creating mutations in graphql that contain a relation. I don't know where to start. For example - three classes of models: class HotelGuests(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=46, default='noname') lastname = models.CharField(max_length=46, default='noname') email = models.EmailField(max_length=254) tel_number = models.CharField(max_length=12, blank=True, null=True) class Rooms(models.Model): room_number = models.PositiveSmallIntegerField() min_vacancy = models.PositiveSmallIntegerField(default=1) max_vacancy = models.PositiveSmallIntegerField(default=7) class Reservations(models.Model): BOOKING_STATUS = { (0, 'Do zatwierdzenia'), (1, 'Zatwierdzona'), (2, 'Zrealizowana'), (3, 'Anulowana'), } price = models.FloatField(default=0) prepayment_price = models.FloatField(default=0, blank=True, null=True) number_of_guests = models.PositiveSmallIntegerField() date_from = models.DateField(default=now) date_to = models.DateField(default=now) description = models.TextField(blank=True, null=True) booking_status = models.PositiveSmallIntegerField(default=0, choices=BOOKING_STATUS) hotel_guest = models.ForeignKey(HotelGuests, on_delete=models.CASCADE) room = models.ForeignKey(Rooms, on_delete=models.SET_NULL, blank=True, null=True) Three classes of graphql types: class HotelGuestType(DjangoObjectType): class Meta: model = HotelGuests fields = ('id', 'name', 'lastname', 'email', 'tel_number') class RoomType(DjangoObjectType): class Meta: model = Rooms fields = ('id', 'room_number', 'min_vacancy', 'max_vacancy') class ReservationType(DjangoObjectType): class Meta: model = Reservations fields = ('id', 'price', 'prepayment_price', 'number_of_guests', 'date_from', 'date_to', 'description', 'booking_status', 'hotel_guest', 'room',) And three classes of node: class HotelGuestNode(DjangoObjectType): class Meta: model = HotelGuests filter_fields = ['id', 'name', 'lastname', 'email', 'tel_number'] interfaces = (relay.Node, ) class RoomNode(DjangoObjectType): class Meta: model = Rooms filter_fields = ['id', 'room_number', 'min_vacancy', 'max_vacancy'] interfaces = (relay.Node, … -
This Field can not be changed Django Validation Error
All I am trying to create valiadtion check that will check after saving the "Name" and "Address that field can not be changed, How I can do that? class Institution(CustomModel): name = models.CharField(max_length=256, null=False, blank=False, verbose_name=_('Name')) address = models.ForeignKey('Address', on_delete=models.PROTECT, null=False, blank=False, verbose_name=_('Address')) -
How do I access data from a dictionary in a HTML template?
When I try to use data from a dictionary, I get the error: 'tuple' object has no attribute 'get' This happens when I click on a link that should take me to the page of the entry. The entry is a Markdown file that I get from util.get_entry(title). How do I access data from a dictionary in my HTML template (entry.html)? Do I need to convert the Markdown into HTML? entry.html: {% extends "encyclopedia/layout.html" %} <!-- {% load static %} --> {% block title %} {{ name }} {% endblock %} {% block style %}{% endblock %} {% block body %} <div class="left">{{ entry }}</div> <div class="right"> <a href="{% url 'edit' %}"> <button class="edit">Edit</button> </a> </div> {% endblock %} views.py: from . import util def entry(request, name): if util.get_entry(name) is not None: return render(request, 'encyclopedia/entry.html'), { 'entry': util.get_entry(name), 'name': name } else: return render(request, "encyclopedia/404.html") urls.py: path('<str:name>', views.entry, name='entry'), -
Getting 0 all the time when dividing in annotation
I get next query qs = Supplier.objects.annotate( goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)), ).annotate( goods_sales_percent=(F('goods_with_sales') / Value(500)) * Value(100), ) SQL query SELECT Count("wb_good"."id") filter (WHERE "wb_stockshistory"."sales" > 0) AS "goods_with_sales", ((count("wb_good"."id") filter (WHERE "wb_stockshistory"."sales" > 0) / 500) * 100) AS "goods_sales_percent" FROM "wb_supplier" left outer join "wb_good" ON ( "wb_supplier"."id" = "wb_good"."supplier_id") left outer join "wb_stockshistory" ON ( "wb_good"."id" = "wb_stockshistory"."good_id") GROUP BY "wb_supplier"."id" Why I get always 0.0? I'm use Django 4.0 and PostgreSQL. -
Simple password login/logout using django and session storage. Stay logged in not working
I am trying to make a password protected page in a website using django. There is no need for any username, just a user to enter a password to gain access. That's fine, but I've got a checkbox so that they can choose to stay logged in for the session, but then on the actual protected page itself, a logout button should they wish to. My idea is to set a session variable when submitting the log in form if the box is checked, check for that variable at the start of the function to go straight to the page if it exists on revisiting and to delete the variable and return to login page if logout is pressed. However I can't make it work, I am trying all sorts of syntaxes.. does it want the session variable to be a dictionary? I'm quite a novice and not very good at knowing syntax. If someone could look at my functions and help I'd be very grateful. def investors(request): """ A view show the investor login page (or investors page if a correct password is in session) and load the investors page if a correct password is entered. Also set a … -
Trying to create simple API with Django Rest Framework
I think something is wrong with imports. the error is ImproperlyConfigured but don't know what it is. Followed along with tutorial https://medium.com/swlh/build-your-first-rest-api-with-django-rest-framework-e394e39a482c doing the same coding Here is some of my code. I added my installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'my_api.apps.MyApiConfig', ] created serializer.py: from rest_framework import serializers from .model import Hero class HeroSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hero fields = ('name', 'alias') views.py: from django.shortcuts import render from rest_framework import viewsets from django.views import View from django.http import HttpResponse from .serializers import HeroSerializer from .models import Hero # Create your views here. class HeroViewSet(viewsets.ModelViewSet): queryset = Hero.objects.all().order_by('name') serializer_class = HeroSerializer class IndexView(View): def get(self, request): return HttpResponse('This is Home Page!') my_api/urls.py (urls of my app): from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'heroes', views.HeroViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path("home/", views.IndexView.as_view, name="home")] my_API/urls.py (urls of my project): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_api.urls'))] models.py: from django.db import models # Create your models here. class Hero(models.Model): name = models.CharField(max_length=50) alias = models.CharField(max_length=50) def __str__(self): return self.name -
How to remove "this field is not required" in django?
I found posts with similar problem, but the solutions dont seem to work with me. Or maybe I am missing something. I created a form in Django, but as a default it seems that every mandatory fields have this "this field is required" text above. Ideally, I would like to have this only when someone tries to submit a form and a field is missing. form.py class ElderFlowerChampFormAdmin(ModelForm): fieldsets=[ ("Look",{'fields':[ ('look_colour','look_clarity','look_effervescence')]}), } widgets = { 'user': forms.Select(attrs={'class':'form-control','required':'True'}), 'look_colour':forms.Select(attrs={'class':'form-control','required':'True'}), } view.py def elderflowerchamp(request, product_id): global ChampageRating product = Product.objects.get(pk=product_id) url = request.META.get('HTTP_REFERER') submitted = False try: if request.method == "POST": reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST, instance=reviews) if form.is_valid(): form.save() return redirect('home') else: form = ElderFlowerChampForm(request.POST, instance=reviews) if form.is_valid(): ChampageRating = form.save(commit=False) ChampageRating.user = request.user ChampageRating.save() return redirect('home') else: #This part goes to the page, but doesnt submit reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin else: form = ElderFlowerChampForm if 'submitted' in request.GET: submitted = True except: reviews = None if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST) if form.is_valid(): data = ChampageRating() data.rating = form.cleaned_data['rating'] data.look_colour = form.cleaned_data['look_colour'] data.ip = request.META.get('REMOTE_ADDR') data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted.') return redirect('home') else: form … -
call view function in celery beat task (Django)
i want call del_cart() function in views.py, with celery beat tasks, but i cant found any way to call del_cart in del_cart_task views.py def del_cart(request): cart_obj = Cart(request) cart_obj.remove_all() return HttpResponse('your cart expire') tasks.py @app.task(name='remove_cart_session') def del_cart_task(): pass url.py urlpatterns = [ path('add_cart/', views.AddCart.as_view(), name='add_cart'), path('show/', views.ShowCart.as_view(), name='show'), path('remove/', views.del_cart, name='remove'), ] -
can not access webpage django
i am working on user's page on django. i want to enter http://127.0.0.1:8000/user/2 and get my template but django says The current path, user/2, didn’t match any of these. my view: from django.shortcuts import render from django.views import generic from .models import * def UserPage(request,user_num): #get user info username = "none" posts = []#post("test", "none") status = 'aboba' return render( request, 'userpage.html', context={'username': username, 'posts': posts, 'status': status}, ) my urls: from django.urls import path from . import views urlpatterns = [ path(r'^user/(?P<user_num>\d+)$', views.UserPage, name='userpage'), ] -
how customize django graphql-jwt
how customize backend authenticate for graphql-jwt? If i user BaseBackend and return user i get exception " graphql.error.located_error.GraphQLLocatedError: 'NoneType' object has no attribute 'is_anonymous' " class MyBackend(BaseBackend): def authenticate(self, request, *profile): user = User() user.social_id = int(profile.get('user_id')) user.expires_at = profile.get('expires_at') user.last_verification_code = "{:04}".format(random.randrange(1, 10**4)) user.set_unusable_password() user.save() token = get_token(user) authenticate(username=user.full_name, password=user.password) login(request, user, backend='graphql_jwt.backends.JSONWebTokenBackend') return user -
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (set_session cannot be used inside a transaction)
raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (set_session cannot be used inside a transaction) -
Django Files Upload from Form get CSRF Forbidden on production
I have a simple Django FileForm for multiple files upload (basically txts with polygon coordinates). I don't want to save the uploaded files anywhere but only treat them on the fly (memory?) and return a leaflet map with the polygons and a new file of mine (which transforms and exports all the txts in a .dxf format file (CAD combatible)). I have done all the logic and my programm seems to work fine on development but on production (Heroku) when i hit the submit button on my form I keep getting CSRF Forbidden 403 message. I am really frustrated. I have used csfr decorators (csrf_exempt, requires_csrf_token, ensure_csrf_cookie) on my views but none seems to work. I have included enctype="multipart/form-data"> and {% csrf_token %} on my form template. What's the problem? It's hard for me to test and try because on development everything is ok and I have to deploy everytime only to see if another approach works. Is it because I am not saving the files on a model and on a disk (What's the logic here?), or is it because I'm missing something on the CSRF part on my settings? settings.py (when deploying) """ Django settings for myKAEK project. … -
Diffrence between user and user_id in get() functions [Django]
UserProfile.objects.get(user=request.user) UserProfile.objects.get(user_id=request.user.id) these two line of codes are returning the same object. so what is the diffrence between them ? -
I want to CRUD the comments of a django user
What you want to achieve When a user posts a comment for a movie, I can only comment on that comment and I want to update and delete it without changing the URL. What you want to ask How do I get my post to appear at the top of new posts when users post comments? How should I change delete and update when I change the url of the posted comment? Current code def view_movie_detail (request, movie_id): if not (Movie.objects.filter (id = movie_id)): Movie (id = movie_id) .save () movie = Movie.objects.get (id = movie_id). if request.method == "POST" and not (Comment_movie.objects.filter (user = request.user, movie = movie_id)): form = Comment_movie_CreateForm (request.POST) if form.is_valid (): Comment_movie ( comment = form.cleaned_data ['comment'], user = request.user, stars = form.cleaned_data ['stars'], user = request.user, star = form.cleaned_data ['stars'], Movie = movie ). Save () return redirect ('view_movie_detail', movie_id = movie_id) Otherwise form = Comment_movie_CreateForm () data = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=ja-US") Recommendation = requests.get (f "https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed (Comment_movie.objects.filter (movie_id = movie_id)) Mean = movie.average_stars () Context = { "data": data.json (), "Recommendations": recommendations.json (). "Type": "Movie", "Comment": Comment "average": average value, "form": form. } return render (request, "Movie / movie_detail.html", context) … -
This error is displayed when running Django-> TemplateDoesNotExist
Error: TemplateDoesNotExist at /finance/charge/ view: class ChargeWalletView(View): form_class = ChargeWalletForm template_name = 'charge_wallet.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': self.form_class}) urls: urlpatterns = [ path("charge/", ChargeWalletView.as_view(), name="") ] -
Use dj-rest-auth login token to access @login_required view
I would like to do a Django all auth login process via the drf. I use dj-rest-auth for this. After I get the authToken, I use it in the header to authorize the individual requests. However, as soon as I try to call a view that contains the @login_required decorator I am still redirected to the login page. I get the authtoken as follows: payload = {'username': '***', 'email': '***', 'password': '***'} r = requests.post("http://127.0.0.1:8000/dj-rest-auth/login/", data=payload, timeout=5) print(r.content) If I execute this request with this token, for example, everything works as intended: headers = {'Authorization': 'Token ***', 'content-type': 'application/json', 'Accept': 'application/json'} r = requests.post("http://127.0.0.1:8000/dj-rest-auth/user/", headers=headers, timeout=5) print(r.content) ...I get the related user details. However, when trying to access a view that has the decorator @login_required using the same auth header, I get redirected to the signin page. Why am I not being logged in? @login_required def home(request): return HttpResponse('It works!') -
how can I pass value from django forms to Excel?
I have a model with static values that I want to use in my model methods and 1 column with values that the user needs to insert called number_of_units. What I want to do is export the CostCalculator but the value in the number_of_units column should be taken from Django form, not from the model. How can export the value from number_of_units to the excel column? The form is saved successfully and I can see value from the form in the admin panel but in Excel, I see the value 0 in all rows. It seems that it takes only fixed values that are in the model but doesn't the value from the form. How can I fix that and pass the value from the form to Excel? forms.py class CalculatorForm(forms.ModelForm): number_of_units = forms.IntegerField(min_value=0) class Meta: model = CostCalculator fields = ('number_of_units',) resources.py class CostCalculatorResource(resources.ModelResource): related_product__title = Field(attribute='related_product__title', column_name='Product') number_of_units = Field(attribute='number_of_units') class Meta: model = CostCalculator models.py class CostCalculator(models.Model): related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product') title_component = models.ForeignKey(CalculatorServiceComponent, on_delete=models.CASCADE, default=1) number_of_units = models.IntegerField(default=0) views.py class ModelDetailView(FormMixin, DetailView): model = Product form_class = CalculatorForm template_name = 'ModelDetailView.html' def form_valid(self, form): number_of_units = form.cleaned_data['number_of_units'] filter_qs = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) dataset = CostCalculatorResource().export(filter_qs, … -
Is mandatory to refer foreign key even it has only one parent?
lets assume that there is an institution and this institution has many announcement so I intend to store these announcements in a table. Here is how it looks, class institution: - name - address, - .....etc class announcements: - owner = models.ForeignKey(Institution, on_delete=models.CASCADE) - messages, - ...etc From this, there wont be any new Institution, so do i really need to add FK in announcements table ?or can i simply create a table without FK as i can directly call the announcements without need to FK -
how can i solve this strenge error in python making django
this is my code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), ] and this is the error: in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings -
Django todoApp coming problem in adding task
I am getting problems with added tasks. It shows MultiValueDictKeyError in my code. Here is my source code -- https://github.com/Aliwahid17/todoApp Please help me in solving the problem.