Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework (DRF) sets JSON field to Empty in the to_internal_value function
So I am trying to upload file AND Post JSON data to my API following this solution. I have created the Parser, placed it in my viewset. I even receive the image and the JSON data in the to_internal_value function, which i think runs AFTER the parser parses the data. How ever, as soon as the to_internal_value function is run, the location field is set to empty. I overrided the function to see whats happening, and it seems the field.get_value function is returning the empty value. Here's the parser: class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # for case1 with nested serializers # parse each field with json for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value else: data[key] = value qdict = QueryDict('', mutable=True) print(data) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) Here's the Serializer: class AssetSerializer(serializers.ModelSerializer): """ Serializes data recieved/retrieved to/from endpoints concerning Assets. """ asset_location = LocationSerializer(required=False,allow_null=True) asset_devices = serializers.PrimaryKeyRelatedField(many=True,queryset=Device.objects.all(),required=False) parent = serializers.PrimaryKeyRelatedField(queryset=Asset.objects.all(),required=False) busy_ranges = serializers.CharField(required=False) time = serializers.ReadOnlyField( source='datetime') status = serializers.CharField(source="current_status",required=False) class Meta: model = Asset fields … -
how to run a html template on the project's base path 127.0.0.1:8000/ on python-django
I am learning Python-Django I want to run a html template on the project's very base site 127.0.0.1:8000/ I don't want to run it in 127.0.0.1:8000/polls or something like that. My myproject/urls.py file looks like this urlpatterns = [ path('', include('?????')), path('admin/', admin.site.urls), path('polls/', include('polls.urls')) ] I don't know what to include in place of '?????' to run a html template on 127.0.0.1:8000/ -
! [remote rejected] master -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/immense-anchorage-56196.git
i am trying to push my code to heroku but i am getting error when i am running push command command i am runnin g--> git push heroku master:main -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 1b461938974e19dafd44baf4db9e9a43f4db7f2e remote: ! remote: ! We have detected that you have triggered a build from source code with version 1b461938974e19dafd44baf4db9e9a43f4db7f2e remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku <branchname>:main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... -
How to get csv file in request in django?
I want to get csv file in post(request) in djnago. file = request.FILES['file'] #is this way is correct to get csv file I have tried code given but getting error this :- UnsupportedMediaType: Unsupported media type "text/csv" in request. pl help I have stuck two days. def post(self, request, version_id): """ upload csv file to s3 params: request (csv file) """ response = {"success": True, "data": {}, "message": ""} file = request.FILES['file'] #is this way is correct to get csv file is_valid, message = self.validate_file(file) #this function for check file is csv or not if is_valid: ImageUpload = ImageUploader() try: response = ImageUpload.upload_file(file) except Exception as e: response.update({"success": False, "message": e}) else: response.update({"message": message, "success": False}) return Response(response, 200) -
Django: How to ask user to select an option on website homepage and use that value in all website pages
I am working on a website, I am confused with following. I need to ask user on homepage to select an value from a dropdown and use that value in other pages of website. I have an Navbar on base.html which is common on all other view files via - {% extends '..base/html' %}, so nav bar will be common and below it all other pages render. So I am thinking to have a dropdown on navbar and every page I open should be able to keep the selected dropdown value at start, unless it is changed. Eg: ecommerce sites asks for PINCODE and uses that to show available products. (Similar to this). How should I solve this, I am really confused and not able to find anything. Thanks. -
Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to profenity, there after logging there after pages are not rendering properly. I've followed the examples in my lessons and checked the code a hundred times but obviously there is something I'm missing i'm having some issues on revercenotFound when i logging there i getting this error everthing working properly before when i pushed code into server i getting this error. NoReverseMatch at /user_dashboard Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/user_dashboard Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. Exception Location: /usr/local/lib/python3.8/dist-packages/django/urls/resolvers.py, line 694, in _reverse_with_prefix Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/eunagi/Project/image_processing', '/usr/local/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Tue, 27 Jul 2021 10:38:54 +0000 Error during template rendering In template /home/eunagi/Project/image_processing/templates/user_base.html, error at line 33 Reverse for 'post_text' not found. 'post_text' is not a valid view function or pattern name. 23 <span class="icon-bar"></span> 24 </button> 25 </div> 26 27 <div class="navbar-collapse collapse navbar-pad"> 28 <ul class="nav navbar-nav mynav" … -
How to remove last comma after objects in Array []?
I have a array like this: Array [ Object { "id": 1, "item": "Hair service", }, Object { "id": 2, "item": "Face service", }, ] How can i covert this Array To Array like this without last comma? Array [ Object { "id": 1, "item": "Hair service", }, Object { "id": 2, "item": "Face service", } ] Because when i try axios.post method foreign key values not adding to my model. Via postman when i try post method, everything is work done. Convert to string in my case not a good variant. Because i need post Array to my relation model. Thank you -
How to pull and run dockerized django application from docker hub
I have dockerized a django application and it is working fine as a container. I used docker-compose. Then I pushed it to hub repo. How I can pull the image and run it and what are the commands to do that? -
how can i create Db table using ForiegnKey relationship in DRF
Halo i'm working on creating multiple DB table using foreignKey but i'm having some error hoping anyone can help out, below is my code & the error msg ###models.py file class SchoolVideo(models.Model): school = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='school_video') intro_video = models.FileField( upload_to='assets/videos', blank=True, null=True) ###serializer file class VideoSerializer(serializers.ModelSerializer): class Meta: model = SchoolVideo fields = ('intro_video',) def create(self, validated_data, *args, **kwargs): if 'user' in validated_data: user = validated_data.pop('user') else: user = Profile.objects.create(**validated_data) school_video = SchoolVideo.objects.update_or_create( user=user, defaults=validated_data ) return school_video API VIEW class SchoolVideoAPi(generics.CreateAPIView): serializer_class = VideoSerializer queryset = SchoolVideo.objects.all() permission_class = [permissions.IsAuthenticated] parser_classes = (MultiPartParser, FormParser) def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data, instance=request.user.profile.school_video ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, message='Video successfully Uploaded', status=status.HTTPS_201_CREATED, headers=headers, ) def perform_create(self, serializer): print(self.request.user.profile) serializer.save(user=self.request.user.profile) -
Django exclude field from '__all__' in DjangoFilterBackend for ModelViewSet
I have multiple API classes (ModelViewSets) that are inheriting from one common ViewSet. So there are different kinds of models with their own fields but all share the same features that are defined in the common viewset. One of those features - is filtering. It looks like this: class CommonViewSet(viewsets.ModelViewSet): filter_backends = (DjangoFilterBackend,) filter_fields = '__all__' class FirstViewSet(CommonViewSet): model = FirstModel class SecondViewSet(CommonViewSet): model = SecondModel # etc... Each model has a different set of fields, except that each model has a common field user. I don't want this field to be exposed in any way. I have excluded this field from the serializers: class CommonSerializer(serializers.ModelSerializer): class Meta: exclude = ('user',) class SecondSerializer(CommonSerializer): class Meta: model = FirstModel # etc... What I want to achieve is to exclude the field user from filter_fields of CommonViewSet as well. I.e.: filter_fields = '__all__' # except 'user' Is there a standard way to do that? -
How to display one set of data between two models?
I have Model Question and Answer. What I want to accomplish is to be able to display it in the template in a way that shows like this. I would like to know a way to accomplish this. I'm trying my best to not let it loop the whole data in a model but rather one data at a time. I'm trying to make a qna data and make it display on a template. so having all the Questio data displayed before Answer data is not what I want. It has to be one by one for these two models. I'm getting kinda close...but I stil can't figure out how to accomplish this. Any help or advice would be greatly appreciated. Thank you in advance. Q.title Q.body A.body Q.title Q.body A.body Q.title Q.body A.body modesl.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Question(models.Model): title= models.CharField(max_length= 100) body= models.TextField() date_posted= models.DateTimeField(default=timezone.now) author= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.title class Answer(models.Model): body= models.TextField() question= models.ForeignKey(Question, on_delete= models.CASCADE) date_posted= models.DateTimeField(default=timezone.now) author= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.body qna.html template {% extends "info/base.html" %} {% block content %} {% for question in questions %} <h1> Q</h1> … -
How to send push notification to the user using firebase and django
I want to send a push notification to the user when the admin enter status field and saves it. Ex I am developing an e commerce website so, I have an model called orders where I have status which can contain some text it will be initially blank when the admin fills it and saves it, the user of the respective order should get notified. Please help me ... How to send push notification using firebase and django iam a beginner. I couldn't understand the documents they provided . Please help me with an simple example. -
Django How to filter all objects foreign key field
table : event_rewards table : rewards serializer : EventRewardSerializer serializer : RewardSerializer models.py class Reward(models.Model): id = models.BigAutoField(primary_key=True) category = models.IntegerField(blank=True, null=True) count = models.IntegerField(blank=True, null=True) image = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255) price = models.IntegerField(blank=True, null=True) class Meta: db_table = 'reward' class EventRewards(models.Model): event = models.ForeignKey(Event, models.DO_NOTHING) rewards = models.OneToOneField('Reward', related_name='event_id', on_delete=models.CASCADE) class Meta: db_table = 'event_rewards' serializers.py class EventRewardSerializer(serializers.ModelSerializer): class Meta: model = EventRewards fields = ['event', 'rewards'] class RewardSerializer(serializers.ModelSerializer): event_id = serializers.SlugRelatedField( read_only=True, slug_field='event_id' ) class Meta: model = Reward fields = ['id', 'category', 'count', 'image', 'name', 'price', 'event_id'] views.py class JoinRewardView(APIView): def get(self, request, pk_event, pk_post, pk_user, formant=None): reward_list = Reward.objects.all().filter(event_id=pk_event) print(reward_list) reward_list_serializer = RewardSerializer(data=reward_list, many=True) reward_list_serializer.is_valid() print(reward_list_serializer.data) return Response(reward_list_serializer.data, status=status.HTTP_400_BAD_REQUEST) postman -> all().filter(event_id=1) [ { "id": 1, "category": 1, "count": 100, "image": "img3", "name": "coke", "price": 1000, "event_id": 1 } ] postman -> all() [ { "id": 1, "category": 1, "count": 100, "image": "img3", "name": "coke", "price": 1000, "event_id": 1 }, { "id": 2, "category": 1, "count": 10, "image": "img4", "name": "coffee", "price": 2500, "event_id": 1 } ] all() -> 2 data -> ok! all().filter(category=1) -> 2 data -> ok! all().filter(event_id=1) -> 1 data -> why??? -
Django Admin: Subtotal of each TabularInline entry and set into a model field
I have SupplierBill & SupplierBillList model. I'd like to total up all of my TabularInline SupplierBillList model class attribute net_price, and save that value to my SupplierBill's sub_total attribute. I pick some code, that does not work properly. When I submit the form, sub_total does not update in SupplierBill view page. If I enter SupplierBill detail View page, then it store into db & update in SupplierBill view page. How can I solve this? Image Model.py class SupplierBill(models.Model): supplier = models.ForeignKey(Supplier,on_delete=CASCADE,null=True,blank=True) payment_method = models.ForeignKey(PaymentMethod,on_delete=DO_NOTHING,null=True,blank=True) account = models.ForeignKey( Account, on_delete=DO_NOTHING, null=True, blank=True) sub_total = models.DecimalField( max_digits=20, decimal_places=2, null=True, blank=True) class SupplierBillList(models.Model): supplier_bill = models.ForeignKey( SupplierBill, on_delete=CASCADE, null=True, blank=True) product_name = models.CharField(max_length=300,null=True,blank=True) product_code = models.CharField(max_length=300,null=True,blank=True) quantity = models.BigIntegerField(null=True,blank=True) unit = models.ForeignKey(Unit,on_delete=DO_NOTHING, null=True, blank=True) price = models.DecimalField( max_digits=20, decimal_places=2, null=True, blank=True) net_price = models.DecimalField( max_digits=20, decimal_places=2, editable=False) Admin.py class SupplierBillListInline(admin.TabularInline): model = models.SupplierBillList insert_after = 'account' readonly_fields = ['get_net_price'] exclude = ['net_price'] def get_net_price(self, obj): entry = SupplierBillList.objects.get(id=obj.id) entry_subtotal = obj.quantity * obj.price if entry.net_price != entry_subtotal: try: entry.net_price = entry_subtotal entry.save() except DecimalException as e: print(e) return "Taka:" + str(entry_subtotal) get_net_price.short_description = 'net_price' class SupplierBillAdmin(admin.ModelAdmin): list_display = ('id','supplier', 'payment_method','account', 'sub_total', ......) fieldsets = ( (None, {'fields': ( 'supplier', 'payment_method','account', 'sub_total', .....)} ), … -
Open local drives in browser using django?
I want to open a local drives in browser using django For example I am developing an API to download .mp3 files and I want to access them to local drive and getting the file I want to download. I do this but it does nothing <a href="file:///C:\Users\Diaa\Desktop\ITTechWebsite\ittech\media\api\readers">Reader</a> Please help me doing this. -
paginator function not working in django?
My issue is that i want to retrieve only 6 objects per page but its showing all 10 per page my view def home(request): if request.method == 'GET': entry = Entry.objects.all().order_by('date_added') # top_rated = Entry.objects.annotate( # no_of_likes=Count('likes')).order_by('-no_of_likes')[:2] pages = Paginator(entry, 6) if request.GET.get('page'): print('executed') page_num = request.GET.get('page') pages = pages.page(page_num) entries = pages.object_list print(len(entries)) return render(request, 'base/base.html', {'entries': entries, 'pages': pages}) -
Django create view with parent model and child information
I am a beginner with Django and feel I have a fundamental misunderstanding of how to use context dictionaries. I am trying to make a function list view where it displays a list of parent models(projects) and under each project it displays the child models(stages).NOTE: I am creating a function list view rather than using a generic list view so I can include more logic such as booting those that aren't staff. I would like the list to look like: Project A Stage A(For Project A only) Stage B(For Project A only) Project B Stage B(For Project B only) My current code prints all stages in the database for each Project even if it is not the right one, but i also tried {% for stage in project.stages %} and got an error. Here are my models class Project(models.Model): name = models.CharField(max_length=70, null=False, blank=False) completion_date = models.DateTimeField(verbose_name="completion_date", null=True,blank=True ) class Stage(models.Model): DESIGN = "DESIGN" QUOTE = "QUOTE" DEPOSIT = "DEPOSIT" SCREENSHARE = "SCREENSHARE" DIGITAL_PROOF = "DIGITAL_PROOF" SAMPLE_PRODUCTION = "SAMPLE_PRODUCTION" WHOLESALE_PRODUCTION = "WHOLESALE_PRODUCTION" SHIPPING = "SHIPPING" STAGE_TYPE_CHOICES=[ (DESIGN,'Design'), (QUOTE,'Quote'), (DEPOSIT,'Deposit'), (SCREENSHARE,'Screenshare'), (DIGITAL_PROOF,"Digital Proof"), (SAMPLE_PRODUCTION,"Sample Production"), (WHOLESALE_PRODUCTION,"Wholesale Production"), (SHIPPING,"Shipping") ] project=models.ForeignKey(Project, related_name="stages", on_delete=models.CASCADE) type = models.CharField(max_length=30, choices=STAGE_TYPE_CHOICES,) completion_date = models.DateTimeField(verbose_name="completion_date", null=True,blank=True ) … -
mocking getattr function input
this is my test @tag("third_party","mock") @patch("layers.api.serializers.import_from_service.get_wms_store_layers") def test_validate_and_publish_WMS_service_layer_serializer(self, mock_wms): mock_wms.return_value = ["some_layer","some_other_layer"] bar = foo(id=4) self.assertEqual(bar,["some_layer","some_other_layer"]) and this is my sample code from geos.helpers import stores def foo(id): ows_profile = OWSProfile.objects.get(id=id) valid_layers = getattr(stores, f'get_{ows_profile.type}_store_layers')(username=ows_profile.username,password=ows_profile.password,url=ows_profile.url) return valid_layers but I got this error AttributeError: <module 'layers.api.serializers.import_from_service' from '/home/sajjad/app/sajjad/layers/api/serializers/import_from_service.py'> does not have the attribute 'get_wms_store_layers' how to fix this Thanks -
403 Forbidden Error When Editing a Form - Javascript and Django
I'm trying to use a form to edit a previous post on my site. After clicking edit, using Javascript, I'd like this to happen without requiring a reload of the page. I'm using Django and trying to use fetch in the Javascript file but I'm pretty lost as to why it's not working. I've been having a lot of trouble with saving things to the database, but also using Javascript at the same time. Any help is appreciated. When I click edit and try to save, I get 403 forbidden error. relevant urls.py - I tried this with edit_post/ and it still didn't work: path('edit_post', views.edit_post), javascript: edit = document.querySelectorAll(".edit"); edit.forEach((element) => { element.addEventListener("click", () => { edit_handeler(element); }); }); function edit_post(id, text) { form = new FormData(); form.append("id", id); form.append("text", text.trim()); fetch("edit_post", { method: "POST", body: form, }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = text; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = text.trim(); }); } function edit_handeler(element) { id = element.getAttribute("data-id"); edit_btn = document.querySelector(`#edit-btn-${id}`); if (edit_btn.textContent == "Edit") { document.querySelector(`#post-content-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).style.display = "block"; edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); } else if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); } } views.py … -
Vim as an IDE for Django. Is it possible to?
If anyone configured vim configuring to this instruction, share the .vimrc config. I will also be glad to see your options for configuring Vim as IDE for Django. -
Django restframework unique error not processed
When I fill in the necessary fields, Django will return a message to the client, but when the field is unique, there will be an error message. Why didn't Django handle it? models.py class UserModel(models.Model): email = models.EmailField(unique=True) username = models.CharField(max_length=16, blank=True, null=True) password = models.CharField(max_length=512) is_active = models.BooleanField(default=False) sign_up_date = models.DateTimeField(auto_now_add=True) sign_in_date = models.DateTimeField(null=True, blank=True) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField() username = serializers.CharField(max_length=16) password = serializers.CharField(max_length=512) is_active = serializers.BooleanField(read_only=True, default=False) sign_up_date = serializers.DateTimeField(read_only=True) sign_in_date = serializers.DateTimeField(read_only=True) class Meta: model = UserModel fields = ( 'id', 'email', 'username', 'password', 'is_active', 'sign_up_date', 'sign_in_date',) views.py class SignupView(CreateAPIView): serializer_class = UserSerializer queryset = UserModel.objects.all() error IntegrityError at /api/signup/ duplicate key value violates unique constraint "User_email_key" DETAIL: Key (email)=(test@gmail.com) already exists. -
Django creating a route that takes the last part of the URL as parameter for a view?
For example: I would like: http://localhost:8000/computers/laptops/ To return the same as: http://localhost:8000/computers/?c=laptops What would be the best way to do it? -
Rendering Django Templates using Python Dictionaries
How do I use a python dictionary to automatically render multiple html templates in Django? Each button in picture 1 should create an output similar to picture 2. Picture 1 Picture 2 This is the code I have written in views.py and it has been linked in urls.py: class RandomView(TemplateView): template_name = "random.html" def dict_lookup(request): dic = ({ "Linkam": ["Optical spectra vs Temperature", "Reflectance vs Temperature", "Video of crystallisation (formed by composing images)"], "Vector Network Analyser (VNA)": ["Permittivity", "Permeability"], "Four Point Probe": ["Resistivity", "Resistivity vs temperature"], "Static Tester (Optics Lab)": ["Switching times (Reflectivity vs Time and Power)"], "Transient Grating Spectrometer": ["Elastic Tensor", "Thermal diffusivity"], "Raman Microscope": ["Intensity vs Energy", "Intensity vs Frequency"], "Perkin Elmer Spectrometer": ["Reflectivity vs wavelength","Transmissivity vs wavelength"], "Scanning Electron Microscope":["Images"], "SEM - Energy dispersive X-ray Analysis (EDX)" : ["Fluorescent intensity vs energy"], "SEM - Electron Backscattering diffraction (EBS)": ["?"], "X-ray Diffractometers": ["Intensity vs angle", "X-ray reflectivity (thickness, density, roughness)"], "Ellipsometer": ["Refractive index vs wavelength"], "Atomic Force Microscope (AFM)": ["Thickness vs length", "Map of roughness"] }) return render(request, "random.html", dic) This is the code written in random.html under templates: {% for key, value_list in dic.items %} {% for value in value_list %} <div class ="row pt-3"> <button type="button" … -
GCP: connect to Memotystore from cloud run Django app?
I'd like to add cache to my Django app hosting on Cloud Run. From Django official docs, we can connect Django to a memory-based cache. Since I'm using Cloud Run, the memory get cleaned. Memotystore seems good for this purpose, but there's only tutorial for flask and redis. How could I achieve this? Only should I just use a database caching? -
Django how to write query for get current logged in user email?
I have abstract user model. I am using this queryset for getting current logged in user username. currentuser_username = UserManagement.objects.filter(username=request.user) my terminal result: I am not understanding how to write queryset for get current user email. If I don't know the username of current user then I can write this queryset currentuser_username = UserManagement.objects.filter(username=request.user) and it will give me the username of current user. How to apply same method for getting mail for current user??? here my models.py class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False)