Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Directly render html page on specific element without scroll (Django/JavaScript)
My question is about controlling page scrolling/anchor targets while using Django and Bootstrap. I have a Django project styled using Bootstrap. Information is rendered sequentially on a page. New information is added to the bottom of the page each time a user presses a button. This is achieved through loading all the information into a dictionary, but only rendering specific sections of it depending on a variable count which stores how far the user is through the case. When the button is pressed, information is passed to a view which checks its integrity and if acceptable increments a count variable and redirects the user back to the original page. The original page now shows new information because of the incremented count variable. I am trying to use anchors with the URL redirect to ensure the page loads on the new information. These anchors work, but the page is loading from the top each time a user presses the button to advance and then the page scrolls down. Ideally the page would load directly on the new information or reload where the user clicked submit and then scroll to the new information. A section of the view to demonstrate the current … -
django filter user for send activate sms
When the user fills in the registration form, the information entered in the database is saved and an account activation SMS is sent to him, but if the user for any reason can not enter the activation code and wants to fill out the registration form from the beginning, he will encounter an error. I used ---- filter(phone_number=phone_number, verify = False).exists(): ----- to filter the user, but I think there is a problem with how i write the code forms class RegistrationForm(forms.ModelForm): user_name = forms.CharField( min_length=4, max_length=50, help_text='Required' ) phone_number = forms.CharField(max_length=11, error_messages={ 'required': 'با عرض پوزش ، شما به یک شماره تلفن نیاز دارید'}, validators=[RegexValidator(regex=r'09(\d{9})$')], ) password = forms.CharField(widget=forms.PasswordInput) def clean_phone_number(self): phone_number = self.cleaned_data['phone_number'] if User.objects.filter(phone_number=phone_number).exists(): raise forms.ValidationError( 'Please use another Email, that is already taken') return phone_number views def account_register(request): if request.user.is_authenticated: return redirect("store:home") if request.method == "POST": registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.phone_number = registerForm.cleaned_data["phone_number"] user.set_password(registerForm.cleaned_data["password"]) user.is_active = False user.save() code_user = f"{user.code}" print(code_user) #send_sms return render(request, "verificationpage.html", {"form": registerForm}) else: return HttpResponse("Error handler content", status=400) else: registerForm = RegistrationForm() return render(request, "login.html", {"form": registerForm}) -
Counting items in a queryset
This works RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType).count() But this doesn't work queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType), print(queryset2.count()) And I have also tried print(queryset2.objects.count()) print (queryset2.objects.all().count()) print (queryset2.objects.all().len()) print (queryset2.objects().filter().count()) print (queryset2.len()) print (queryset2.all().len()) print (queryset2.objects.len()) -
Django unit testing if a POST request properly updates a model instance
I'm having trouble understanding why my test keeps failing. I have two models (only showing relevant code): class Listings(models.Model): listing_instagram = models.URLField(null=True, blank=True) listing_facebook = models.URLField(null=True, blank=True) ... class ListingsDescription(models.Model): listing = models.OneToOneField(Listings, on_delete=models.CASCADE) space_description = models.TextField(max_length=1000, blank=True) accessibility_description = models.TextField(max_length=1000, blank=True) ... I have a properly functioning view that processes two forms (one form per model): def some_view(request, listing_id): listing = get_object_or_404(Listings, id=listing_id) listing_description = listing.listingsdescription if request.method == "POST": form_a = ListingForm(request.POST or None, instance=listing) form_b = ListingDescriptionForm(request.POST or None, instance=listing_description) if form_a.is_valid() and form_b.is_valid(): form_a.save() form_b.save() messages.success(request, "Changes Made") return HttpResponseRedirect(reverse('destination') Manual testing on my browser works fine, and all fields are properly saved in the database. However, running below test: class ListingJourney(TestCase): @classmethod def setUpTestData(cls): cls.client = Client() # Create Listing cls.listing = ... def listing_post(self): self.assertTrue(Listings.objects.filter(id=self.listing.id).exists()) response = self.client.get(reverse('new_listing', kwargs={'listing_id': self.listing.id}), follow=True) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='foo/listing.html') response = self.client.post(reverse('new_listing', kwargs={'listing_id': self.listing.id}), follow=True, data={ 'space_description': "Lorem ipsum dolor", 'neighborhood_description': "Lorem ipsum dolor", 'listing_instagram': "https://www.instagram.com/listing/", 'listing_facebook': "https://www.facebook.com/listing/", # some more data }) self.assertRedirects(response, reverse('redirect', kwargs={'listing_id': self.listing.id}), status_code=302, target_status_code=200, fetch_redirect_response=True) self.assertEqual(self.listing.listingsdescription.space_description, "Lorem ipsum dolor") self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing/") self.assertEqual(self.listing.listing_instagram, "https://www.instagram.com/listing/") The test fails at: self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing") Traceback (most recent call last): File "...\tests.py", line 153, in listing_post self.assertEqual(self.listing.listing_facebook, "https://www.facebook.com/listing/") AssertionError: … -
How to create factory-boy factories for Django models with foreign key
Im trying to test api post method with factory boy, but im getting errors. I get error: ValueError: Cannot assign "'User 0'": "CustomUser.user" must be a "User" instance. tests.py: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = CustomUser user = factory.Sequence(lambda n: "User %d" % n) class EventFactory(factory.django.DjangoModelFactory): class Meta: model = Event user = factory.SubFactory(UserFactory) john = EventFactory() my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) -
Access content for Anonymous and logedIn User
How best can I access content while the user is not logged in. For example, I have the View which handles both Listing and posting blog posts , though I want someone to access content even without being logged In, though the person shouldn't create a blog post, unless logged In. Below is my current implementation : class PostList(generics.ListCreateAPIView): """Blog post lists""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context=request) if serializer.is_valid(): serializer.save() return response.Response(serializer.data, status=status.HTTP_201_CREATED, ) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how best can I play with these lines : authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] because when I remove this line : authentication_classes = (JWTAuthentication,) I can access the lists of blogs, though I will need an endpoint of creating a blog posts to be protected, how best can this be achieved -
I am having trouble my forms.py file, got an error "KeyError 'request' "
view.py class AssignAgentView(OrganizerLoginRequired, FormView): template_name = "leads/assign_agent.html" form_class = AssignAgentForm def get_from_kwargs(self): return { "request": self.request } def get_success_url(self): return reverse("leads:lead-list") form.py class AssignAgentForm(forms.Form): agent = forms.ModelChoiceField(queryset=Agent.objects.none()) def __init__(self, *args, **kwargs): request = kwargs.pop('request') agents = Agent.objects.filter(organization=request.user.userprofile) super(AssignAgentForm, self).__init__(*args, **kwargs) self.fields["agent"].queryset = agents As you can see I am passing request as a key-value and runserver i got this File "C:\Users\sarfa\Desktop\tutorial\leads\forms.py", line 42, in __init__ request = kwargs.pop('request') KeyError: 'request' -
Extra tables in Django's admin group permission list
I have run a few fake migrations yesterday and also renamed a few tables of my database direcly yesterday due to foreign key constraints and other similar errors Django kept throwing at me after renaming some models. I know this is not standard procedure and it's prone to messing up things. It did solve everything for me though, without the need of wiping out the database, as I was almost resolved to do. Anyway, as I said, all is working great, expect for the list shown in the 'available permissions' in the Group management. The following (and other) tables are not in the database, and indeed are not even prepended with the applications's name: Where are those sourced from? How can I get rid of them? -
How to pass aggregate array to javascript?
I have a list in Django views, and I want to pass it to Javascript for iteration, I've tried serveral way but seems like the data can't be used by the js, could anyone have a look, please? views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) todos = project.todo_set.filter(status='to_do') progresses = project.todo_set.filter(status='in_progress') dones = project.todo_set.filter(status='done') counts_data = Todo.objects.aggregate( to_do_count = Count('pk', filter=Q(status='to_do')), in_progress_count = Count('pk', filter=Q(status='in_progress')), done_count = Count('pk', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', counts_data) ''' html ''' data: { labels: ['todo','inprogress','done'], datasets: [{ label: '# of Votes', data: [{% for todo in data %} {{ todo }}, {% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)' ], borderWidth: 1 }] } ''' -
Using a model as a source for a PK for diffrent model?
So if I have a simple model that I want as a source of my PK like so: class PostCreation(models.Model): pk = models.AutoField(primary_key=True) post = models.OneToOneField(Post, on_delete=models.CASCADE) What I want to do is create a PK of a blog post before the post has been created. My reasoning is I want the images/files I upload to be in a format of /media/blogPK/files So my Post will have a id/PK field set from the PostCreation class above And the Pseudo code is below: id = PostCreation() FileField(upload_to='{}{}{}'.format(id, '/', files)) But how can I create the PK first and then pass it to my Post model and then set the Post is/pk to that of PostCreation? I's going to be using ModelForm to output the fields for the Post content, Description/Date etc so when I goto visit that view I want the pk/id already made even if the user does submit the content of the Post model. How can I do this? Is it possible? Thx -
Django Token objects update error : django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id
I was using django user class and rest_framework Token class to store the user info and the token. For the same I was using serializers.ModelSerializer class. But when I am making update request(check update method) to update the user info as well as the token that I have, its giving me error. Here is serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.authtoken.views import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user def update(self, instance, validated_data): instance.username = validated_data['username'] instance.set_password(validated_data['password']) instance.save() Token.objects.update(user=instance) return instance views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] Error : django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id This is how I am making the request with the authorisation token in the header field: -
AJAX response doesn't print in console
I am using ajax to get form data from Django application and I want to print the response in the console. $.ajax({ type: 'GET' , url: url, data: {'PUITS': PUITSId }, dataType: "json", success: function (response){ console.log(response) var response = JSON.stringify(response); var response = JSON.parse(response); console.log(response.PUITS); console.log(response.DUSE); console.log(response.CS); the first console.log(response) gives me this data: [{"model": "measure.surveillancedespuits", "pk": 15, "fields": {"PUITS": "1", "DATE_TEST": "2021-09-10", "MODE": "GL", "CS": "1", "SITUATION": "O", "DUSE": "27", "PRES_TBG": "27", "PRES_CSG": "27", "PRES_AVD": "27", "RESEAU_GL": "27", "ANNULAIRE_TECH": "27", "OBSERVATION": "Nothing", "Controle_Pression_ENSP": true, "Test_Puits": false, "Controle_Pression_DP": false, "post_date": "2021-09-10T08:56:16.864Z", "author": "smail"}}] and I want to print also some individual data from fields like PUITS, DATE_TEST, post_date in the console but it shows an error!?. -
djagno NotImplementedError: Django doesn't provide a DB representation for AnonymousUser
from django.shortcuts import render, redirect from django.db import transaction from .models import User from .forms import RegisterForm, LoginForm, CheckPasswordForm from .decorators import login_required from django.views.decorators.http import require_POST @require_POST def profile_delete(request): if request.method == 'POST': request.user.delete() return redirect('users:login') return render(request, 'users/delete.html') users view raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") NotImplementedError: Django doesn't provide a DB representation for AnonymousUser. I'm trying to delete user information in django, but I get an error like the title. What should I do? I have also tried the @login_require method and middle_classes in settings, but the error is not resolved. -
dealing with foreign keys in Django
i am creating a doctor appointment system, and i did include prescriptions too class Prescription(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, null = True, on_delete=models.SET_NULL) clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL) i was thinking what if the doctor delete his account for some reasons, can the doctor or the clinic set to null if this happen? -
Add a rest API to an existing Python application
after some research I am stuck on my problematic... I explain myself, for a project I develop an application in microservice composed by : Entities that produce data (geolocation data) and send them to a Queueing system A "server" entity that periodically receives data from the Queueing system, performs processing/calculation on it locally. A front-end, which queries the "server" entity on a producer ID, which retrieves the data from the latter and displays them Currently, the infrastructure of the application is functional, with Kubernetes deployment etc. In relation to development, a simulator is functional to replace the entities "that produce". The latter is a multi-threaded application that continuously sends data to the Queue system. The "server" entity that receives is also functional. This last is developed in python, and consists in its operation to connect to system of Queue, to receive data periodically, to treat them by storing locally (will be migrated towards a DB in the future) an object for each ID of the producers. My problem is the following: I want to add a REST API Gateway, to be able to bind it to my "server" entity and to a front-end in React for example. I tried to … -
'Response' object has no attribute 'user'
I am getting error AttributeError: 'Response' object has no attribute 'user' for the below code I have written I am trying to get the user info from the context and create a notification model. I am getting the above error while returning the statement. I don't understand why I am getting this error Model class CourseNotification(models.Model): uid = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, unique=True) course = models.ForeignKey('Course.Course', on_delete=models.SET_NULL, null=True) user = models.ManyToManyField('Profile.myUser',null=True) def get_user(self): return [i for i in self.user.all()] def __str__(self): return self.course.course_title View class CourseNotificationView(ModelViewSet): queryset = CourseNotification.objects.all() serializer_class = CourseNotificationSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): if self.request.user.email is not None: profile = myUser.objects.get(email=self.request.user.email) if profile is not None: notification = CourseNotification.objects.filter(user=profile) return notification else: return Response(data={"User": "Unauthorized User"}, status=HTTP_401_UNAUTHORIZED) def retrieve(self, request, *args, **kwargs): serializer = self.get_serializer(self.get_queryset(), many=True) return Response(data=serializer.data) Serializer class CourseNotificationSerializer(serializers.ModelSerializer): class Meta: model = CourseNotification fields = '__all__' def create(self, validated_data): users = self.context['request'].user subject = validated_data['course'] if users is None and subject is None or subject == "": raise serializers.ValidationError({"Invalid": "Subject could not be Invalid"}) checkNotification = self.checkNotification(users, subject) if checkNotification is not None and checkNotification.status_code == 200: return checkNotification validate_subject = self.validateSubject(users, subject) if validate_subject.status_code == 200: return validate_subject get_data … -
How to sum ranks in django-orm annotate
model class ChampionKill(Event): start = models.ForeignKey('self', models.CASCADE, null=True, blank=True, related_name='sequence') damage = models.PositiveIntegerField() damage_contribution = models.FloatField() objects = ChampionKillManager() manager class ChampionKillManager(BaseManager): def get_queryset(self): return super().get_queryset().annotate( avg_damage_contribution=Avg('sequence__damage_contribution'), avg_interval=( Cast(Max('sequence__time') - Min('sequence__time'), models.FloatField()) / F('length') ), rank_damage_contribution=Window(Rank(), order_by=F('avg_damage_contribution').desc()), rank_interval=Window(Rank(), order_by=F('avg_interval').asc()), # total_rank_score=(F('rank_damage_contribution') + F('rank_interval')), # rank_total=Window(Rank(), order_by=F('total_rank_score').asc()), ) When I add "total_rank_score" and "rank_total" in annotete, I get the following error.(I am using sqlite) django.db.utils.OperationalError: misuse of window function RANK() I want to create a value of "total_rank_score" by summing the value of "rank_damage_contribution" and the value of "rank_interval". I need advice. -
Please correct the errors below. in Django admin
every time i try to add a new member to my Django admin , this error will pop up and i know its because of the email but i dont know whats wrong with it also i doesnt set my user as ACTIVE. so here is an image of the error i get image of ERROR this is my MODEL : def create_user(self,email, mobileNumber, name, familyName, password, nationalCode, **other_fields): if not email: raise ValueError('you need a valid email') email = self.normalize_email(email) user = self.model(mobileNumber=mobileNumber, name=name, familyName=familyName, password=password, email=email, nationalCode=nationalCode, **other_fields) user.set_password(password) user.save() return user def create_superuser(self,email, mobileNumber, name, familyName, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email,mobileNumber, name, familyName, password, nationalCode, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50, validators=[validate_name]) familyName = models.CharField(max_length=50, validators=[validate_name]) email = models.EmailField(max_length=50, blank=True) nationalCode = models.IntegerField(null=True, validators=[is_valid_iran_code]) mobileNumber = models.CharField(max_length=11, null=True, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = customMemberManager() USERNAME_FIELD = 'mobileNumber' REQUIRED_FIELDS = ['nationalCode', 'familyName', 'name','email'] def __str__(self): return str(self.name) and this is my admin : … -
Django : Django paths not working as expected
I have a project . I have to reference a json file . My code which is the flashcard.html file : {%include 'header.html' %} <style> {%include 'css/flashcard.css' %} {%include 'css/header.css' %} </style> <div id="content" style="width: 100%; position: relative;"></div> <i class="fas fa-caret-right" style="position: absolute; top: 20%; left: 95%; font-size: 50px;" id="next"></i> <i class="fas fa-caret-left" style="position: absolute; top: 20%; left:5%; font-size: 50px;" id="back"></i> {% for key, value in data.items %} <p>{{ key }} +':'+ {{ value }}</p> {% endfor %} <script> let mydata = {%include 'data.json' %} let frontSideFront = true let cardNum = 0 let totalCards = 2 //var mydata = JSON.parse(data); for(var i = 0 ; i < totalCards ; i++ ){ frontSideFront = true $("#content").append(` <div class="card-container" id="${i}"> <div class="front">${mydata['questions'][i]}</div> <div class="back">sd</div> </div> `) } for(var m = 0 ; m < totalCards ; m++ ){ if (m !== cardNum) { $(`#${m}`).css('visibility', 'hidden'); } } $("#next").click(function (e) { $(`#${cardNum}`).css('visibility', 'hidden'); $(`#${cardNum}`).css('position', 'absolute'); cardNum++ $(`#${cardNum}`).css('visibility', 'visible'); $(`#${cardNum}`).css('position', 'relative'); }); $("#back").click(function (e) { $(`#${cardNum}`).css('visibility', 'hidden'); $(`#${cardNum}`).css('position', 'absolute'); cardNum-- $(`#${cardNum}`).css('visibility', 'visible'); $(`#${cardNum}`).css('position', 'relative'); }); $(".card-container").click((e)=>{ if(frontSideFront){ frontSideFront = false $(".front").css({ "transform": "rotateY(-180deg)", }) $(".back").css({ "transform": "rotateY(0deg)", }) }else{ frontSideFront = true $(".front").css({ "transform": "rotateY(0deg)", }) $(".back").css({ "transform": "rotateY(180deg)", }) } }) </script> … -
Building GUI Using CSS that runs Python
I have started building GUI based App on python Using TKinter,But Tkinter is less flexile(atleast for me) to make a good Design ,So i decided to switch to Web App (that runs on local Host) and heard that CSS is good for Designing.So my question Is Is there a way to run the python code that i have previously written, In the web App that is Designed Using CSS. Eg: In my python project with tkinter,a button click would send a notification Using Firebase Cloud Messaging to my Mobile App,I want to implement the same using the Web App. -
Check the Authorization HTTP Header of every incoming request, Django
I should check the Authorization HTTP Header of every incoming request. In case of missing or invalid Authorization header it i should return an error with HTTP Code 401 Unauthorized. How to make simple authorization header validation? my code: models.py class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def clean(self): self.api_token = Token.objects.create(user=self.user) middleware.py class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_id = request.POST.get('created_by', False) try: api_token = CustomUser.objects.get(user=user_id).api_token except CustomUser.DoesNotExist: api_token = '' response = self.get_response(request) response['Authorization'] = "Bearer " + api_token return response I have tried to write validation in auth.py, but when i write request.headers.get("Authorization",'') list is empty. Tried something like this: auth.py class BearerTokenAuthentication: def get_bearer_token(self, request): **#DOEST WORK** auth = get_authorization_header(request).split() **#EMPTY LIST** auth_header_prefix = api_settings.BEARER_AUTH_HEADER_PREFIX.lower() if not auth or smart_text(auth[0].lower()) != auth_header_prefix: return None if len(auth) == 1: return False elif len(auth) > 2: return False return True views.py: @action(methods=['POST'], detail=False) def post(self, request): if BearerTokenAuthentication.get_bearer_token(request): **#DOES NOT WORK** tutorial_serializer = EventSerializer(data=request.data) if tutorial_serializer.is_valid(): tutorial_serializer.save() return Response(tutorial_serializer.data, status=status.HTTP_201_CREATED) return … -
Unable to add token headers to graphene-django using pytest
I am trying to add a token to graphene-django headers using pytest. But It always return that user is anonymous as shown at the end, but it should return user as token is added in fixture. @pytest.fixture def client_query(client): def func(*args, **kwargs): return graphql_query(*args, **kwargs, client=client) return func @pytest.fixture def create_candidate(candidate_factory): candidate = [] for _ in range(5): can = candidate_factory.create() token, __ = Token.objects.get_or_create(user=can.user) candidate.append(can) return candidate # This is the testing @pytest.mark.django_db def test_get_login_candidate(client_query, create_candidate): headers = {"Authorization": f"Token {create_candidate[0].user.auth_token}"} response = client_query( """ query { loginCandidate{ id, } } """, headers=headers, ) result = json.loads(response.content) print(result) output {'errors': [{'message': "'AnonymousUser' object is not iterable", 'locations': [{'line': 3, 'column': 11}], 'path': ['loginCandidate']}], 'data': {'loginCandidate': None}} -
django.core.exceptions.FieldError: Cannot resolve keyword 'field_id' into field. Choices are:...?
django.core.exceptions.FieldError: Cannot resolve keyword 'productcategory_id' into field. Choices are: country, country_id, id, name, vendor I have found one answer. but, that answer can't help me. Can anyone please tell me what is this error and how to solve it? -
creating a checkbox field with a ManyToMany relation
Im trying to add a field called, interested_fields inside my personalInfo model which users can choose from and the choices themselves come from another models' objects with the help of ManyToMany relation between the two models. Here are my models.py codes(I simplified my personal model by removing some other fields like name, age,... in order to make it more readable for you): class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_fields = models.ManyToManyField(Field, blank=True) then, I created a ModelForm like this: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] and created a get and post functions inside my views like this: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) and finally in template, inside the form I added this for loop: {% for field in fields %} <label class="containerq ant-col ant-col-md-6 ant-col-xs-8" > <span> <input type="checkbox" … -
Django: Saving image from URL to ImageField
I have read too many articless but I still haven't found a solution for my problem. I have a Django model with an ImageField on it image = models.ImageField(upload_to='products/%Y/%m/%d') All I need to do is save image from my warehouse the already existing image file path with the ImageField I have code bellow this script do sync with warehouse and I need to download Image and save in my model shop/Book from celery import shared_task from django.core.mail import send_mail import requests from .models import Author, Book, Genre @shared_task def send_mail_task(subject, message, email): send_mail(subject, message, email, ['admin@example.com']) @shared_task def shop_sync(): print('Starting update from warehouse api for database') print('Getting data from api...') url = 'http://warehouse:8001/authors/' print('Clearing data...') response_author = requests.get(url) if response_author.status_code != 200: return response_data_author = response_author.json() while 1: for counter, data in enumerate(response_data_author['results']): Author.objects.get_or_create( id=data['id'], defaults={ 'id': data['id'], 'first_name': data['first_name'], 'last_name': data['last_name'] } ) if response_data_author['next']: response_data_author = requests.get(response_data_author['next']).json() else: break url = 'http://warehouse:8001/genres/' print('Clearing data...') response_genre = requests.get(url) if response_genre.status_code != 200: return response_data_genre = response_genre.json() while 1: for counter, data in enumerate(response_data_genre['results']): Genre.objects.get_or_create( id=data['id'], defaults={ 'slug': data['slug'], 'name': data['name'], } ) if response_data_genre['next']: response_data_genre = requests.get( response_data_genre['next'] ).json() else: break url = 'http://warehouse:8001/books/' print('Clearing data...') response_book = requests.get(url) …