Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-formtools, saving data between form steps
I am trying to create a multi-step form wizard using django-formtools. I have a main model called Report and several ModelForms as follows: class ReportFormP1(forms.ModelForm): class Meta: model = Report fields = [ 'company', 'address_line_1', 'address_line_2', 'responsible_person', 'person_consulted', 'assessor_name', 'previous_assessment_date', 'review_date', ] # section 1 class ReportFormP2(forms.ModelForm): class Meta: model = Report fields = [ "premise_num_floors", "premise_floor_area", "premise_occupancy", "premise_occupancy_comments", ] in my views, I have created the following view: class ReportWizardView(SessionWizardView): template_name = 'reporting/report_create2.html' form_list = [ReportFormP1, ReportFormP2] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) And my relevant template looks as follows: {% extends '_base.html' %} {% load static %} {% load i18n %} {% load crispy_forms_tags %} <!-- templates/home.html --> {% load socialaccount %} {% block title %}Create a report{% endblock title %} {% block extra_css %} {{ wizard.form.media }} {% endblock extra_css %} {% block content %} <div class="container"> <h1>Create a report</h1> <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post"> {% csrf_token %} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form|crispy }} {% endfor %} {% else %} {{ wizard.form|crispy }} {% endif %} <div class="text-center"> {% … -
FileUploadHandler writing on Uploaded File when calling .read()
Does TemporaryUploadedFile (class from UploadedFile) write on the uploaded data? I have an XML file here when reading the whole file it starts off with text like: "b'----------------------------507481440966899800347275\r\nContent-Disposition: form-data; name=""; filename="sampleXML.xml"\r\nContent-Type: application/xml\r\n\r\n". The original XML file does not contain this. I am trying to use ElementTree to read through the Uploaded XML File. But am stuck at this part which keeps causing a syntax error. Not sure if it is the class file who edits the data or Postman (used this to upload the file to my REST API). If I read the XML file directly from my PC by getting the path, ElementTree reads it with no issue. Its only getting syntax error when reading from the Uploaded File. I have tried ElementTree.fromString() and parse(). Issue isn't on the actual ElementTree. Tried opening the Temporary file and reading from there (same issue, where there is a the text specified above is shown). I basically want to know if the Django inbuilt FileUploadHandler write on the data when running .read() or somewhere along the process? class FileUploadView(APIView): parser_classes = (FileUploadParser, XMLParser,) def post(self, request, filename, format=None): print(request.FILES) file_obj = request.FILES['file'] fileHandler(file_obj) return Response(status=204) def fileHandler(file): filepath = file.temporary_file_path() print(file.read()) tree … -
How to use Django ORM for multiple inner joins on nested foreign keys
I would like to do multiple joins on some django models with a filter on one of the joined tables. Here is what the raw SQL would look like: SELECT DISTINCT c.id, c.description FROM public.customer_customerhiernode AS c INNER JOIN public.territory_management_territorycustomer AS tc ON tc.customer_id = c.id INNER JOIN public.territory_management_territorynode AS tn ON tn.id = tc.territory_node_id INNER JOIN public.territory_management_territoryuser AS tu ON tu.territory_node_id = tn.id INNER JOIN public.authentication_user AS u ON u.id = tu.user_id WHERE u.username = %s This is what I've tried so far, it is filtering correctly at territorycustomers, but when I fetch the CustomerHierNode, it gets all of them. users = TerritoryUser.objects.select_related('user').filter(user__username=username) territorycustomers = TerritoryCustomer.objects.prefetch_related(Prefetch('territory_node__territoryuser_set', queryset=users)) customers = CustomerHierNode.objects.prefetch_related(Prefetch('territorycustomer_set', queryset=territorycustomers)) I want to join these tables and get all their fields as a flat dictionary. Is this possible with the ORM? I also want this to be as efficient as possible. -
Can't set virtualenv - problem with source activation.ps1
Fallowing the freecodecamp's django tutorial I'm stack on the very beginning - I can't set up virtualenv. Everything goes great until it's time to make final step - activate virtualenv and download Django. I'm working on Windows 10, and tried a lot of ways to solve it. Everything ends up with to results, but first things first. Here is what i did: Ran powershell as administrator and set up ExecutionsPolicy as unrestricted Create new folder called 'Dev' Inside Dev created another folder for project with virtualenv - everything by command 'virtualenv name of the folder Tried to activate it by "name_of_project's_folder\Scripts\activate" After this I'm getting error which says that I must "source this script". I tried to make path to the Scripts folder and type only activate but it doesn't work. When I tried to type "name_of_project's_folder\Scripts\activate" but with ".bat" added on the end, nothing happens. Like, literally nothing. I really hope for making this work because I'm slowly getting frustrated coz of tons of research I made today nad a lot of blind tries to solve this. Python was downloaded via powershell and pip if it's important. -
Django: How can I access and display details about the single "child" in the one-to-many relationship?
I have two models - the Company and Department. The Company can have many Departments - this is all connected with Foreign Key and works as expected. I have URLs and templates/views nicely setup and I can add the Company and then I can add Depratments to it. I am also able to access and create new Departments and assign them to the Company. To see, say 5 last companies I have in the system I use this: class IndexView(generic.ListView): model = Company template_name = 'company/index.html' context_object_name = 'latest_company_list' def get_queryset(self): """Return the last five created companies.""" return Company.objects.order_by('company_name')[:5] And here are the models from models.py class Company(models.Model): company_name = models.CharField(max_length=200) company_dba = models.CharField(max_length=200) class Meta: verbose_name_plural = "companies" def __str__(self): return self.company_name # on submit click on the company entry page, it redirects to the url below. def get_absolute_url(self): return reverse('company:index') class Department(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) dept_name = models.CharField(max_length=200) dept_code = models.IntegerField(default=0) def __str__(self): return self.dept_name # on submit click on the department entry page, it redirects to the url below. def get_absolute_url(self): return reverse('company:index') My urls.py file looks like this app_name = 'company' urlpatterns = [ # Company management views path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('add/', … -
Factory-boy / Django - Factory instance not reflecting changes to model instance
I am writing tests for a website I'm working on and I'm representing the models with factoryboy Factory objects. However, I've run into some behavior I found somewhat confusing and I was wondering if anyone here would be so kind to explain it to me I'm running a test that contains the following model: STATUS = ( ('CALCULATING'), ('PENDING'), ('BUSY'), ('SUCCESS'), ('FAILED') ) class SchoolImport(models.Model): date = models.DateTimeField(auto_now_add=True) status = models.CharField( verbose_name=_('status'), choices=STATUS, max_length=50, default='CALCULATING' ) For which I've created the following factory. As you can see the status is set to its default value, which I found more realistic than having a randomly selected value class SchoolImportFactory(factory.DjangoModelFactory): class Meta: model = models.SchoolImport status = 'CALCULATING' school = factory.SubFactory(SchoolFactory) @factory.lazy_attribute def date(self): return timezone.now() - datetime.timedelta(days=10) Below you'll see both a (simplified) version of the function that is being tested, as well as the test itself. (I've currently commented out all other code on my laptop, so the function that you see below is an accurate representation) The gist of it is that the function receives an id value that it will use to fetch an SchoolImport object from the database and change its status. The function will be run … -
If possible, how can I automatically create a Many to Many class with a custom create function?
I came across a problem while creating an application. It essentially involves three different classes. The purpose is to create an object containing basic social media information for an artist, as the main model shows: class ArtistSocial(models.Model): artist = models.ForeignKey('core.Artist', on_delete=models.PROTECT) social_network = models.ForeignKey('core.SocialNetwork', on_delete=models.PROTECT) url = models.CharField(max_length=50) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) The premise of the challenge I'm faced with is that upon the creation of a new artist, I'll be sent a JSON with all the information I need. However, being quite new to programming applications like this, This makes me confused as to how exactly I need to prepare to properly receive that information and create the class. To me, making a custom create action is the clear solution, but I've tried this in many different ways both in ArtistSerializer and ArtistSocialSerializer. I'll post those two pieces of code here: class ArtistSerializer(ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) class Meta: model = Artist fields = ['id', 'user', 'name_alternative', 'labels', 'tags', 'country', 'bio', 'profile_image', 'created_at', 'updated_at'] read_only_fields = ['id', 'created_at', 'updated_at', 'user'] And here's the main one: class ArtistSocialSerializer(serializers.ModelSerializer): class Meta: model = ArtistSocial fields = ['id', 'created_at', 'updated_at', 'artist', 'social_network', 'url'] read_only_fields = ['id', 'created_at', 'updated_at'] Though … -
Django mixin and FormView template confusion with CBV
I'm still a noob at mixins in general so I'm just trying to understand what happens in this code that uses Ajax to submit forms. I've been scouring the docs for a whole day to try to figure out what happens. The code seems to work but I just don't entirely understand why. I still have a lot of question marks on the whole process so if anyone can correct my thinking that would be amazing The AjaxableResponseMixin extends the form_invalid() and form_valid() methods of the FormView to support Ajax requests Why is the Ajax class referring to itself with super()? How does the class know to extend FormView's methods? If the request is not Ajax it returns response What does the response object do/have? Does it show a template? Does it have context for the template? CreatePostView is a child class of the two parent classes that are passed in (AjaxableResponseMixin, FormView) Do the order of the classes in the params have an impact in general and more specifically when calling super()? When CreatePostView calls form_valid() and form_invalid() is it overwriting the Ajax class? If it isn't, what class methods is it changing? If the form is valid then … -
How to call a a field of one model A into another model B so that b can work as a view
I have created a model called Department, Course. Models are as follow This is the model for departments and course class Departments(models.Model): Department_Id = models.IntegerField(primary_key=True) Department_Name = models.CharField(max_length=200) Department_Code = models.CharField(max_length=200) class Course(models.Model): Course_Id = models.IntegerField(primary_key=True) Department_Id = models.ForeignKey(Departments, on_delete=models.CASCADE) Course_Name = models.CharField(max_length=200) Course_Code = models.CharField(max_length=200) I want to create a model called view which can be later on called for search. I want a view model in a such a way that it consit of the data in concat form i.e. name= Department_name+ Course_Name class View (models.model): view_id= models.IntegerField(primary_key=True) Name= Department_name(I want this from Departments table) + Course_Name(I want this from Course table) I try using one to one relation . I would really appricate the help -
Load data from model in settings.py Django
I have model: class Settings(models.Model): class Meta: verbose_name = "Ustawienia strony" verbose_name_plural = "Ustawienia strony" title = models.CharField(_('Tytuł strony'), max_length = 120, blank = True) description = models.TextField(_('Opis strony'), blank = True) facebook_title = models.CharField(_('Tytuł strony Open Graph'), max_length = 120, blank = True,) facebook_type = models.CharField(_('Typ strony Open Graph'), max_length = 120, blank = True,) facebook_url = models.CharField(_('Link strony Open Graph'), max_length = 500, blank = True,) facebook_description = models.TextField(_('Opis strony Open Graph'), blank = True, ) template = models.CharField(_("Wygląd sklepu"), choices = TEMPLATES_LIST, max_length = 100, default="DEFAULT") Now I would like load selected model in settings.py: CURRENT_TEMPLATE = Settings.objects.all().first() But in this way I have error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Is it available to load data from model in settings.py? -
Writing validators with Django: How to display Validation Error Message?
i am testing "Writing validators" from the Django Doc more or less. So i wrote my own validator and it seems to work, but i don´t know how to display the error message in my template. models.py <...> class Animal(models.Model): name = models.CharField(max_length=40) weight = models.DecimalField(max_digits=5, decimal_places=2) species = models.ForeignKey('Species', on_delete=models.CASCADE) farmer = models.ForeignKey('Farmer', related_name='farmername', on_delete=models.CASCADE) objects = AnimalManager() # --- link to Manager def __str__(self): return self.name def get_absolute_url(self): return reverse("datainput:animal_detail", kwargs={"id": self.id}) forms.py <...> from .validator import validate_gtr <...> class AnimalForm(forms.ModelForm): weight = forms.DecimalField(validators=[validate_gtr]) class Meta: model = Animal fields = [ 'name', 'weight', 'species', 'farmer', ] validator.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_gtr(value): if value > 100: raise ValidationError( _('(value) Kg. Animal is too heavy'), params={'value': value}, ) views.py class AnimalCreateView(CreateView): template_name ="datainput/create_animal.html" form_class = AnimalForm queryset = Animal.objects.all() create_animal.html {% extends 'base.html' %} {% load static %} {% block custom_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}"> {% endblock %} {% block content %} <div class="container-fluid"> <!-- Row --> <div class="row"> <div class="col-6 offset-md-3"> <h1>Please insert a new animal</h1> {% load widget_tweaks %} <form method="post"> {% csrf_token %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor … -
Django server 403 (CSRF token missing or incorrect)
I have a basic Django server with an python command line client for posting to this service. I have a login function and a post function. Even though the cookie for CSRF is being set from the login function the server is saying forbidden when I try to access the post_product endpoint after logging in. I've been troubleshooting this for days and haven't had any luck. /api/login/ function: from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse @csrf_exempt def handle_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: if user.is_active: login(request, user) if user.is_authenticated: return HttpResponse(author.name + ' is logged in, Welcome!', status=201, content_type='text/plain') return HttpResponse(data) else: return HttpResponse('disabled account', status=400, content_type='text/plain') else: return HttpResponse('invalid login', status=400, content_type='text/plain') else: return HttpResponse('request method invalid ' + request.method, status=400, content_type='text/plain') /api/postproduct/ function: def post_story(request): if request.method == 'POST' and request.user.is_authenticated: # Pull product details from request. # Validate product details. # Create model and save. Python terminal client def run(): url ='http://127.0.0.1:8000' # For debugging logged_in = false with requests.session() as session: while True: command = input("""Enter one of the following commands: login post \n""") … -
Image upload to the rich text field from vue to amazon s3 via django REST framework
I'm experimenting Vue with Django and creating a simple blog. But I'm stuck about usage of uploading images vie CKEditor from vue. uploading images to S3 is working within django-admin. But I couldn't figure out how can I serialize RichTextUploadField and make it work with vue. My model is; class Challenge(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length = 240) content = RichTextUploadingField(verbose_name='Code',null=True,blank=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="challenges") image = models.ImageField(upload_to=upload_image_to, editable=True, null=True, blank=True) def __str__(self): return self.title serializers.py; author = serializers.StringRelatedField(read_only=True) created_at = serializers.SerializerMethodField() slug = serializers.SlugField(read_only=True) moments_count = serializers.SerializerMethodField() user_has_momented = serializers.SerializerMethodField() class Meta: model = Challenge exclude = ["updated_at"] def get_created_at(self, instance): return instance.created_at.strftime("%B %d %Y") def get_moments_count(self, instance): return instance.moments.count() def get_user_has_momented(self, instance): request = self.context.get("request") return instance.moments.filter(author=request.user).exists() views.py queryset = Challenge.objects.all().order_by("-created_at") lookup_field = "slug" serializer_class = ChallengeSerializer permission_classes = [IsAuthenticated, IsAuthorOrReadOnly] def perform_create(self, serializer): serializer.save(author=self.request.user) urls.py router.register(r"challenges", cv.ChallengeViewSet) urlpatterns = [ path("", include(router.urls)), path("challenges/<slug:slug>/moments/", cv.ChallengeMomentListAPIView.as_view(), name="answer-list"), path("challenges/<slug:slug>/moment/", cv.MomentCreateAPIView.as_view(), name="moment-create"), path("moments/<int:pk>/", cv.MomentRUDAPIView.as_view(), name="moment-detail"), path("moments/<int:pk>/like/", cv.MomentLikeAPIView.as_view(), name="moment-like"), path('ckeditor/', include('ckeditor_uploader.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) frontend vue.js; return this.loader.file .then( uploadedFile => { return new Promise( ( resolve, reject ) => { const data = new FormData(); data.append( 'upload', uploadedFile … -
Django: overriding predefined method save() using request data
I'm trying to override the save() method on a Django model so that some fields are automatically filled out. This is the model: class Blog(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=1500, null=True, blank=True) ip = models.CharField(max_length=200, null=True, blank=True) content = models.TextField(null=True, blank=True) def save(self, * args, ** kwargs): if request.user: self.user = request.user self.url = request.path self.ip = socket.gethostbyname(socket.gethostname()) super().save( * args, ** kwargs) What I'm trying to do is to automatically set the user, URL, and IP fields when I save a record, without having to do that in the view. However, in the current format the request is not "passed" to the model, and I'm not sure how I am supposed to do that. This is what I currently get: name 'request' is not defined -
Fastai attribute error 'PixelShuffle_ICNR' object has no attribute 'do_blur'
I have image processing code using fastai and pytorch embedded in a django view the code is working properly on the production server ( ubuntu machine ) but on my local windows machine it returns this error, I want this code to work on my machine to run the necessary tests so how can I do this? and what's the cause of this error? -
Is it possible to bulk_update a many-to-many relationship in django 2.2?
I have these two simple models: class school(models.Model): name = models.CharField(max_length=128) class teacher(models.Model): schools = models.ManyToManyField(School) user = models.OneToOneField(...) In a view, let's say I wan't to add a school to multiple teachers at the same time. I could do something like this: for teacher in teachers: teacher.add(school) teacher.save() This works, but it is making a lot of queries. Is there a better way to do something like this? I am using django 2.2 (so maybe I could use bulk_update?). -
how to link user of one model class to another user of a foreign class in django views
I've created an app where by a user can create a job and the other user can apply to that specific job, so far creating a job is not a problem but for the other user to apply for that specific job it is quite hard for a beginner like me. I've created tried this way down here but failed and got errors, though for me i think the problem is with my poor views models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) career_briefing = models.CharField(max_length=250, null=True) form.py class ApplicationForm(forms.ModelForm): class Meta: model = Application field = ['career_briefing',] views.py class ApplicationCreateView(CreateView): form_class = ApplicationForm template_name = 'jobs/application_form.html' message = _("succesfuly created") def post(self, request, *args, **kwargs): form = ApplicationForm(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = self.get_object() form.instance.user = self.request.user form.instance.job = self.kwargs["job_id"] apply = form.save(commit=False): apply.user = self.request.user apply.job = self.object return super().form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse( "jobs:detail", kwargs={"pk": self.kwargs["job_id"]}) urls.py urlpatterns = [ .... url(r'^details/(?P<pk>\d+)/$', JobDetailView.as_view(), name='detail'), url(r'^details/apply/(?P<pk>\d+)/$', ApplicationCreateView.as_view(), name='apply'), .... ] templates.py .... <div> <a class="btn btn-dark" href="{% url 'jobs:apply' job.id %}">{% trans 'apply' %}</a> </div> .... i expect that once the user clicks … -
Uploading a CSV or Excel file along with json data through React html form to Django
I want to submit a form to upload either a csv file or an excel file, and provide additional information provided in the form, e.g. text. For defining the form and sending the request I use React Bootstrap with axios, and for the api I'm using Django 2.2 with rest-framework. request.FILES is always an empty dict, even if I try setting the Content-Type header to multipart/form-data, and then additionally nothing is found in the post data of the request, and printing request.data.get('information') below shows None in the Django log. Please help, any support will be greatly appreciated. See below for code snippets. Form definition in render(): <form onSubmit={this.handleSubmit}> <FormGroup> <Form.Label>Upload file</Form.Label> <Form.Control type="file" onChange={this.handleFile}></Form.Control> </FormGroup> <Button block bssize="large" disabled={!this.validateForm()} type="submit"> Submit </Button> </form> Handling file change: handleFile = event => { event.preventDefault(); const fileToUpload = event.target.files[0] this.setState({ fileToUpload: fileToUpload }) } Sending the request: const payload = { file: this.state.fileToUpload, information: "somedata" } const contentType = "multipart/form-data" let accessToken = token var headers = {"Authorization" : `Bearer ${accessToken}`} headers['Content-Type'] = contentType const response = await axios({ method: "post", data: payload, url: url, headers: headers }); Django endpoint definition: class RegisterData(views.APIView): parser_classes = (parsers.JSONParser, parsers.MultiPartParser) def post(self, request): for file in … -
How to highlight code in an article using RichTextField
I have a RichTextField in the admin panel and I want to add the ability to highlight my code there as in this picture my models.py from djrichtextfield.models import RichTextField class DjangoModel(models.Model): titleDjango = models.CharField(max_length=400, verbose_name='Названия') textDjango = RichTextField() datesDjango = models.DateTimeField(auto_now=True) viewDjango = models.IntegerField(default=0) imgDjango = models.ImageField(upload_to='DjangoLessonsImagae', default="default_value",verbose_name='Каритинка 260х180') django_like = models.IntegerField(default=0) django_dislike = models.IntegerField(default=0) -
How to do complex annotations( and how to think about it!)
I am trying to annotate my Product objects with a total_item_sold field. and I can't seem to get my head around it. So, any explanation as to how I should do this will be greatly appreciated. class Order(models.Model): ... class OrderPayment(models.Model): order = models.ForeignKey(Order) successful = models.BooleanField(default=False) ... class OrderListItem(models.Model): order = models.ForeignKey(Order) list_item = models.ForeignKey(ListItem) ... class Product(models.Model): price = models.IntegerField() ... class List(models.Model): products = models.ManyToManyField(Product, related_name="lists", through="ListItem") .... class ListItem(models.Model): llist = models.ForeignKey(List) product = models.ForeignKey(Product) ... so for each product, I want to find all OrderPayments that have been "succesful" and have that product in them( which is resolved by finding the OrderListItems then ListItems and then products), and then annotate the product with total_items_sold of that product. -
Django REST Framework requires hashed password to login
Django requires me to send a hashed password to get my JWT token. When I send the following request via postman I get a "CustomUser matching query does not exist" error. { "user": { "email": "myuser", "password": "mypassword" } } I can, however, run the code with the hashed password (after looking it up from the admin) and it returns the correct value. How do I send unhashed passwords or hash the passwords before I send them? I am using a custom user model that substitutes email for username. I've tried pointing my code to the header using request.META.get("username") and request.META.get("password") but I receive a 'field required' error. I've also tried to figure out how to hash the password on the app before sending it to my API, but I have failed to find a method that works. I have my view below for handling the request. @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): username = request.data.get('username') password = request.data.get('password') if username is None or password is None: return Response({'error': 'Please provide your username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(email=username, password=password) if not user: return Response({'error': 'Invalid Credentials'},status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) I expected to get a JWT … -
How to automatically load default pictures when creating a new user in django
Whenever I create a new user and try to log-in that user my default picture wasn't loading and there's no error on my console, but when I click my view profile(profile.html) that's when my default picture will show up on my sidebar. https://ibb.co/bR79XpJ this is the url of my screenshot. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete =models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') update = models.DateTimeField(default = timezone.now) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile,self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender = User) def save_profile(sender, instance, **kwargs): instance.profile.save() base.html # My sidebar <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> profile.html # my view profile <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> I expect to automatically show my default picture on my sidebar when I create a new user. -
Django - Adding extra data in admin change_form request
I'm Customizing Django admin , now i have to add some extra fields which are created by javascript code in fieldset.html template . the reason i wrote these code in fieldset.html is that the inputs will be in main form , so they will be in post request data . Sample of fieldset.html: {% for line in fieldset %} {% if field.field.name == 'discount' %} <input type="number" name="product_code"> . . . <script> this script will create more input fields </script> {% endif %} {% endfor %} But in ModelAdmin.saveModel when i check request data , my input data does not exist. class FactorAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print('request data', request.POST) super(FactorAdmin, self).save_model(request, obj, form, change) is there any other way to include my dynamic html in Django ChangeForm template ? -
how to distinguish authentication status in frontend(vue)
When we use django template to build a website traditionally,django will handle authentication Automatically, but now I trying to build a Front-and-rear-separation website with django-restframework and vue.js, I don't know how frontend distinguish authentication status. I understand how django authentication works, It set sessionid to cookie, when we send request with cookie django server will know is this request is authenticated, but I think frontend should not be able to access cookie, so I would like to set CSRF_COOKIE_HTTPONLY=Truein django, I can sitll send request with cookie the authentication in django server is still work but how frontend tell the authentication status. what I expect is just like normal website, login or not is showing in the top righthand corner of the page. if login, my user name will be display. if not, a link to login page -
Python request.urlretrieve() returns status 500
I'm using Django with Python 3.5 and I'm trying to download a file from a URL, and giving the filename and path where the file should be downloaded. I am using urlretrieve for this operation, but every time am getting 500 error. But when tested in Postman, the API is working fine. Can anyone help me where I'm going wrong? headers = {'content-type': 'application/json'} posts= { "filepath":filepath } password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() url = 'http://'+API_dns+':'+API_pod+'/api/v1/download-file?filepath='+filepath+'&tid='+tid_selected+'&username='+str(request.user)+'&download_zip_file='+zip_file password_mgr.add_password(None, url, 'admin', 'admin') handler = urllib.request.HTTPBasicAuthHandler(password_mgr) opener = urllib.request.build_opener(handler) urllib.request.install_opener(opener) urllib.request.urlretrieve(url, os.path.join(settings.STATIC_ROOT, "to_download", zip_file)) path = '/static/to_download/'+zip_file context = {'url':path, 'status':200, 'filename':zip_file} return JsonResponse(context)