Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError at /BlogAPI/ APIView.as_view() takes 1 positional argument but 2 were given
These are the screenshots of the code the 1 is error ,2 is views.py , 3 is urls.py -
Best resource to deploy a Django React Application in AWS?
I already built a project that is based on Django (Backend) and React (Frontend). I am kinda stuck here with the deployment process. I am new in DevOps so I need a good resource to follow. Can someone help me out here? -
Product detail and images in django problem
I'm trying to create a simple car dealership app and i'm stuck. I have searched days and i have tried so many times to fix this but i can't. What i'm doing wrong i don't know and my brain is not working anymore. Thanks for help. Error: NoReverseMatch at / Reverse for 'car_detail' with keyword arguments '{'slug': '2021-ram-1500-trx-crew-cab-4x4-57-box'}' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'car_detail' with keyword arguments '{'slug': '2021-ram-1500-trx-crew-cab-4x4-57-box'}' not found. 1 pattern(s) tried: ['(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)$'] Exception Location: C:\Users*\Desktop\Testdealer\envdealer\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users*\Desktop\Testdealer\envdealer\Scripts\python.exe Python Version: 3.9.7 Models.py: from django.db import models import datetime from django.urls import reverse class Car(models.Model): brand = models.CharField(max_length=100) CATEGORY = ( ('New', 'New'), ('Used', 'Used') ) slug = models.SlugField(max_length=200, null=True, unique=True) category = models.CharField(max_length=50, choices=CATEGORY) image_main = models.ImageField(upload_to='images') body_style = models.CharField(max_length=100, blank=True) engine = models.CharField(max_length=100, blank=True) stock_number = models.IntegerField(blank=True, null=True) mpg = models.CharField(max_length=100, blank=True) exterior_color = models.CharField(max_length=100, blank=True) interior_color = models.CharField(max_length=100, blank=True) drivetrain = models.CharField(max_length=100, blank=True) mileage = models.IntegerField(blank=True, null=True) sold = models.BooleanField(default=False, blank=False) transmission = models.CharField(max_length=50, blank=True) YEAR_CHOICES = [(r, r) for r in range(1940, datetime.date.today().year+1)] year = models.IntegerField( ('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) power = models.IntegerField() fuel … -
django rest framework serializer method field how to
How do I handle this serializer method field? I feel that using initial_data is wrong, do i need to validate data when extracting it from the database? Do I need to use a serializer when extracting data from database? class ListingSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField() # This one works as expected def get_rooms(self, obj): rooms = list(Room.objects.filter(listing__id=obj.id).values()) serializer = RoomSerializer(data=rooms, many=True) return serializer.initial_data # This one gives serializer errors def get_rooms(self, obj): rooms = list(Room.objects.filter(listing__id=obj.id).values()) serializer = RoomSerializer(data=rooms, many=True) if serializer.is_valid(): return serializer.data return serializer.errors class Meta: model = Listing fields = "__all__" -
Django translation {% trans '...' %} works but {% blocktrans %} does not work
I am currently trying to translate my website and somehow I am not able to get {% blocktrans %} to work. <html lang="en"> <p> {% blocktrans with USERNAME=worker.username MANAGER=manager.username%} LOGIN_INFORMATION_FOR_USER_HAVE_BEEN_RESET_BY_MANAGER {% endblocktrans %} </p> <p>{% trans 'YOUR_NEW_CREDENTIALS' %}:</p> </html> The .po file looks as follows msgid "LOGIN_INFORMATION_FOR_USER_HAVE_BEEN_RESET_BY_MANAGER" msgstr "The login information for %(USERNAME)s have been reset by %(MANAGER)s." msgid "YOUR_NEW_CREDENTIALS" msgstr "Your new credentials" And all of this results in this: What am I doing wrong here? -
Django DRF - How to update fields of an object using api_view?
At my Django application, I manage S3 backends to import data from. Now I would like to be able to update certain fields of an S3Backend but Im not sure how to do it: This is my current situation views.py @api_view(['PATCH']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated, IsAdminUser]) def s3_backend_update(request, pk): """ Updates a given S3Backend resources """ if request.method == 'PATCH': obj = S3Backend.objects.filter(id=pk) s3_storage_update_serializer = S3StorageUpdateSerializer(obj, data=request.data) try: if s3_storage_update_serializer.is_valid(raise_exception=True): s3_storage_update_serializer.save() s3_storage_serializer = S3StorageSerializer(instance=s3_storage_update_serializer.instance) return JsonResponse( {"status_code": S3Updated.status_code, "default_detail": S3Updated.default_detail, "default_code": S3Updated.default_code, "updated_s3_backend": s3_storage_serializer.data, }, status=status.HTTP_202_ACCEPTED, safe=False) except APIException: return Response( {"status_code": S3UpdateFailure.status_code, "default_detail": S3UpdateFailure.default_detail, "default_code": S3UpdateFailure.default_code, "error": s3_storage_update_serializer.errors }, status=status.HTTP_406_NOT_ACCEPTABLE ) serializers.py class S3StorageUpdateSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=S3Backend.objects.all()) class Meta: model = S3Backend fields = ('id', 'resource_name', 'access_key', 'secret_key', 'bucket', 'endpoint', 'region', 'library') extra_kwargs = {'secret_key': {'write_only': True}} # We dont want to show the secret_key def validate(self, data): try: s3_get_resource(endpoint=data['endpoint'], access_key=data['access_key'], secret_key=data['secret_key'], region=data['region']).meta.client.head_bucket(Bucket=data['bucket']) except (APIException, ClientError, EndpointConnectionError, NewConnectionError, ConnectionRefusedError) as e: raise ValidationError('S3 Bucket does not exist or you dont have access privileges.', e) return data to me it seems that DRF is not able to process the following line: S3StorageUpdateSerializer(obj, data=request.data) The error I get in return is: AttributeError: 'QuerySet' object has no attribute 'pk' I'm new to APIs so … -
django rest framework create method serializer
I have this working code and I am wondering if the code could be written shorter. Just because I have to specify the agent I am passing each peace of data like below. class ListingSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField() def create(self, validated_data): agent = self.context.get("agent") listing = Listing.objects.create( agent=agent, title=validated_data["title"], description=validated_data["description"], floor=validated_data["floor"], floor_count=validated_data["floor_count"], price=validated_data["price"], street=validated_data["street"], house_no=validated_data["house_no"], door_no=validated_data["door_no"], city=validated_data["city"], country=validated_data["country"], postal_code=validated_data["postal_code"], tilstand_report=validated_data["tilstand_report"], water_consumption_report=validated_data["water_consumption_report"], energy_level_report=validated_data["energy_level_report"], property_tax_report=validated_data["property_tax_report"], ) return listing -
Create an API endpoint that manipulates data without any model class in DRF
I am working on DRF, I have created register and login endpoints using the APIview and serializers, which used models. I wanted to create an endpoint that receives some data and returns the manipulated data using some script, but I don't have any Model for such instance as it is just a temporary back and forth process like a chatbot, for example, A user send some queries and solutions are processed and they are returned on the endpoint. Received { "query": "I need help" } Returns { "solution": "Here are some commands that might work" } This could also be a list of solutions Can someone help me as to how to implement or get started with this endpoint? -
div to image via python
i want to make a div image with python and send it as an attachment to slack, is there a way I can do this? i basiclly send message to slack with the following codes. Is what I want to do possible? <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-duyuru" id="inputGroup-sizing-default" style="font-weight: 500;">Duyuru Tipi:</span> </div> <input type="text" class="form-duyuru" name="dolusturulmatarihi" id="dolusturulmatarihi" aria-label="Default" aria-describedby="inputGroup-sizing-default"> </div> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-duyuru" style="font-weight: 500;">Açıklama:</span> </div> <textarea class="form-duyuru" name="daciklama" id="daciklama" aria-label="With textarea">XX:XX </textarea> </div> view; from django_slack import slack_message web_hook_url = 'XXXX' slack_msg = { "attachments": [ { "fallback": "test1.", "color": "#f5b400", "pretext": "test2", "author_name": "TEST ALARMI2", "author_link": "https://techopsportal.hepsiburada.com/", "author_icon": "http://flickr.com/icons/bobby.jpg", "title": "test4", "title_link": "https://techopsportal.hepsiburada.com/", "text": "test5", "fields": [ { "title": "Priority", "value": "High", } ], "image_url": "http://my-website.com/path/to/image.jpg", "thumb_url": "http://example.com/path/to/thumb.png", "footer": "Techops", "footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png", } ] } requests.post(web_hook_url,data=json.dumps(slack_msg)) -
How to test page_published signal in Wagtail?
I added a page_published signal for TraitPage, which gives a usergroup edit permission for the parent of TraitPage. My signal: @receiver(page_published, sender=TraitPage) def allow_user_edit_user_creator_page(**kwargs): instance = kwargs['instance'] page_owner = instance.owner # superusers have permissions to edit by default if not page_owner.is_superuser: user_creator_page = instance.get_parent() usergroup = Group.objects.get(name=str(page_owner.id)) GroupPagePermission.objects.get_or_create(group=usergroup, page=user_creator_page, permission_type='edit') My test: def test_edit_permission_exist_after_trait_page_added(self): # create TraitPage trait_page = TraitPage( title='test trait page', owner=self.user, live=True, bg_image=self.image) # user_profile_page - is the parent of TraitPage self.user_profile_page.add_child(instance=trait_page) # I expect this to exist edit_permission = GroupPagePermission.objects.filter( group=self.usergroup, permission_type='edit', page=self.user_profile_page).exists() self.assertTrue(edit_permission) Everything works fine from wagtail admin, however the test fails. Does creating a page with live=True trigger the page_published signal? -
Django. Django REST Framework. Got error trying to GET requesrt to Endpoint
I'm new to DRF. I have this url endpoint in my urls. path( 'show_events/start/<date:start>/end/<date:end>/', event_list, name='events_list' ), Date is my custom converter. I've registered in urls. Format of date is "YYYY-MM-DD" class DateConverter: regex = r'[0-9]{4}-[0-9]{2}-[0-9]{2}' def to_python(self, value): return datetime.strptime(value, "%Y-%m-%d").date() def to_url(self, value): return value.strftime("%Y-%m-%d") Here's my View @api_view(['GET']) def event_list(request, start, end): events = Event.objects.all() serializer = EventSerializer(events, many=True) return Response(serializer.data) When I'm trying to open link /show_events/start/2021-10-10/end/2019-10-10/ error ERROR How to fix? -
form doesn't add data to database. I tried many times from 3 days and also try from different types but still not happening. pls help me
I tried many times in 3 days and also try from different types but still did not work. pls, help me. ' #models.py from django.db import models class RegisterModel(models.Model): image = models.ImageField() name = models.CharField(max_length=100) email = models.EmailField(max_length=20) password = models.CharField(max_length=20) phone = models.CharField(max_length=12) address = models.CharField(max_length=100) ' ' #forms.py from Pages.models import RegisterModel from django.forms import ModelForm class RegisterForms(ModelForm): class Meta: model = RegisterModel fields = ["image","name","email","password","phone","address"]' ' #views.py def add(request): if request.method == "POST": form = RegisterForms(request.POST) if form.is_valid(): form.save(commit=True) print("valid") return redirect('/') else: form = RegisterForms() print("not valid") context = {'form':form} return render(request,'Pages/add.html',context) ' ' #admin.py from django.contrib import admin from Pages.models import RegisterModel @admin.register(RegisterModel) class RegisterAdmin(admin.ModelAdmin): list_display = ["image","name","email","password","phone","address"]' -
Making Ethereum transactions on a Django application using web3.py
I am developing my first ever blockchain application, and I came across this Django library called django-web3-auth This lets users sign up / login using an Ethereum wallet. Now, I want to be able to make transactions using my applications, and for this purpose I have written the following code using web3 library and ganache: import json from web3 import Web3 ganache_url = 'http://127.0.0.1:7545' web3 = Web3(Web3.HTTPProvider(ganache_url)) print(web3.isConnected()) #build a transaction #sign and send transaction #return transaction hash def transaction(account1, account2, privatekey, amount): nonce = web3.eth.getTransactionCount(account1) #build a transaction transX = { 'nonce' : nonce, 'to': account2, 'value':web3.toWei(amount,'ether'), 'gas': 2000000, 'gasPrice': web3.toWei('50', 'gwei') } #sign and send transaction signedTransX = web3.eth.account.signTransaction(transX, privatekey) hashTransX = web3.eth.sendRawTransaction(signedTransX.rawTransaction) #return transaction hash return web3.toHex(hashTransX) def checkBalance(account1): balance = web3.eth.getBalance(account1) return(web3.fromWei(balance, 'ether')) print(checkBalance('<address>')) As you can see I need a private key to complete the transaction. Asking for a private key on my application doesn't seem right for obvious reasons. Since Django-web3-auth authenticates the user using their Ethereum wallet, is there a way to sign the transaction of logged in user when they send ether to another account? Also, is there a way to run ganache on my deployment server (like replit or pythonanywhere). -
How to update a record in a Django model using forms?
I am new to Django and need some help. I am basically trying to build a Tinder-like application for movies using Django and working on the basics of the 'swiping' functionality. And, while using a form I am having trouble getting the swipe input. I only want a boolean value from the user (true for yes and false for no) and for this to get updated according to the movie id in the database. But I am unable to perform this updation. My form adds a new record instead. Perhaps an easier alternative would be to remove the swipes field from the model entirely , just use it as a variable and maintain a list of movies where this variable was selected to be true. I was unable to access the movie id in this case so this failed too ;-; How do I get this working in a simple efficient manner? Here is what my models.py looks like: class Movie(models.Model): movie_name = models.CharField(max_length=300) # unique id for room movie_description = models.TextField(default='') movie_genre = models.CharField(max_length=100) movie_date_released = models.DateField(null=True) movie_swiped = models.BooleanField(default = False) # Override the __str__ method to return the firstname and lastname def __str__(self): return self.movie_name def is_exists(self): … -
TypeError: categories.map is not a function in ReactJs
How to fix TypeError: categories.map is not a function ''' This is App.js: export default function Header() { const [categories, setCategories] = useState([]); useEffect(() => { const loadCategories = async () => { let res = await API.get(endpoints['categories']) setCategories(res.data) } loadCategories() }, []); return ( <Navbar bg="light" expand="lg"> <Container> <Navbar.Brand href="#home">ECoursesAPP</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="me-auto"> <Link className="nav-link" to="/">Trang chủ</Link> {categories.map(c => <Link className="nav-link" to="#link">{c.name}</Link>)} </Nav> </Navbar.Collapse> </Container> </Navbar> ) } ''' This is API.js: ''' import axios from "axios"; export let endpoints = { "categories": "/categories/" } export default axios.create({ baseURL: "http://localhost:8000" }) ''' -
backend design to connect to android app and web ui
I am writing a python web application in Django to save day to day personal expenses on a SQL database. I want to connect my backend both from web UI and from android app. I know I can use any web front end tech like angular JS etc. for Web UI. My question is how to write Android app for this ? Which front end tech should be used? How to connect this to my backend? Where to deploy my backend code ? --- web UI (react) sql -- web backend (running on cloud) --- --- android app (????) Thanks -
How do I access the data from inside a nested for loop
I want to do something like below in html where multiple "spots" are displayed, and within each spot the "links" associated to each specific spot is displayed. How would I write the logic to display the specific links for each spot? html {% for spot in spots %} <div> <h2>{{ spot.title }}</h2> </div> {% for link in links %} <div> <h3>{{ link.url }}</h3> </div> {% endfor %} {% endfor %} My models are as below. SpotLinks is the intermediate table for Links and Spots table. models.py class Spots(models.Model): title = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) class Links(models.Model): title = models.CharField(unique=True, max_length=155, blank=True) url = models.CharField(max_length=75, blank=True) class SpotLinks(models.Model): link = models.ForeignKey('Links', models.DO_NOTHING) spot = models.ForeignKey('Spots', models.DO_NOTHING) I tried links = Links.objects.filter(spotlinks__spot=spots) in views.py but because spots has multiple spots in it it doesn't get filtered. Will the logic be written in the views.py or as django templates in the html file? Im new to web development so any direction would help. Thanks! views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() links = Links.objects.filter(spotlinks__spot=spots) context = { 'spots': spots, 'article': article, 'links': links} return render(request, 'articletemplate.html', context) -
Import "ckeditor.fields" could not be resolved
I am trying to install ckeditor in my django forms. I seem to have no problem with the pip install django-ckeditor however once it is installed and I have added it to my settings, I can not import RichTextEditor in my models.py file. The error that comes up is 'Import "ckeditor.fields" could not be resolved'. Here is the code: settings.py: INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', ] models.py: from django.db import models import uuid from ckeditor.fields import RichTextField -
about open csv file and read line by line in and choice randomly python
I have a csv file that contains questions, options and answers. I want to open that file in a class called quiz to show the question and answer randomly and the user enters the answer And compare the answers -
How to name an object in Django by using user input? [duplicate]
Here I am on the admin site adding the topics I want to learn about. I want the object to be the topics I add to the site. Is there a way to do this? I am not sure if I would do this in the models.py file or in the admin.py file. Here is my models.py file Is there away that I can tell django to take the user input and use that input instead of the word "object"? When I click on the object I can see the name that I inputted. I wish I could use that name and replace the object that is currently being returned. -
Django Rest API returns 403 error only on iOS when using react native
I have a app which uses React Native as frontend and django as backend. When I try to fetch data from the API, it works perfectly fine on android but on iOS it returns a error 403 forbidden. In the django views, I have put the following inside every views: permission_classes = [permissions.IsAuthenticated] When fetching the API, I have put the following: const userToken = await AsyncStorage.getItem('userToken'); const headers = {"Authorization": `Token ${userToken}`} There are some views that can run on iOS. I notice that for those which cannot be run on iOS are those that I have customize the method in the views (say, I have override the get method in the view). -
Add object to database without calling save
I would like to know if it is possible to add an object to the database without calling save(). foo = Foo.objects.create( #fields ) lst_bars = [] for bar in MyModel.objects.filter( #fields ): lst_bars.append(Bar( foo_id=foo.id, # fields )) Bar.objects.bulk_create(lst_bars) foo.save() In this code I'm creating Foo, then using its id as a reference when creating Bar. After bulk creating all Bar objects, I call the foo save. In the foo save() I call each bar save(), then aggregate all bars data and fill the Foo fields. In total the method save is being called two times, but in the create() I would like to just create without saving, that way it wouldn't make calculations when there is no data. -
django-excel pyexcel show unknown parameters for django heroku
My django app deployed in heroku managed to show upload file form. However once I try uploading Excel xlsx file, it shows UnknownParameters at / Please check if there were typos in function parameters: {'model': None, 'initializer': None, 'mapdict': None}. Otherwise unrecognized parameters were given. Following installation setup has done for django-excel requirements.txt pyinstaller django-excel pyexcel-xls pyexcel-xlsx pyexcel-ods I am sure that my models.py is connected and along with the mapdict parameters matches correctly I've seen similar issue Why pyexcel throws exception "UnknownParameters: Please check if there were typos in function parameters"? and I tried installing pyinstaller along with hidden imports --hidden-import pyexcel_xls --hidden-import pyexcel_xls.xlsr --hidden-import pyexcel_xls.xlsw but unfortunately it still doesn't work for my app I wonder if there is any clue to solve this for me to run my django web application on heroku? or any advice or learning for hidden-import to run within heroku web app? -
TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list (Django)
I am trying to add a profile photo to the client through the 'Customer' model in the administration panel. models.py from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name settings.py STATIC_URL = '/static/' MEDIA_URL = '/imagenes/' STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_ROOT = [BASE_DIR/'static/images'] I think I have an error in setting static file paths; the truth is that I understand very little the way in which I should configure it and I do not understand why the error occurred .. Please, someone who can help me -
How can I add additional field in DRF model instance creation
I have a classroom model in django DRF that looks like this: class Classroom(models.Model): class PublishedClassrooms(models.Manager): def get_queryset(self): return super().get_queryset().filter(status="published") options = (("published", "Published"), ("draft", "Draft")) name = models.CharField(max_length=255) code = models.CharField(unique=True, max_length=8) subject = models.CharField(max_length=255, null=True, blank=True) section = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) status = models.CharField(max_length=10, choices=options, default="draft") owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) dateCreated = models.DateTimeField(default=timezone.now) dateUpdated = models.DateTimeField(default=timezone.now) objects = models.Manager() # default manager publishedClassrooms = PublishedClassrooms() # custom manager class Meta: ordering = ("-dateUpdated",) def __str__(self): return self.name what I want is to generate unique code field in the serializer upon creation of an instance using this code: def get_code(): codeID = shortuuid.ShortUUID().random(length=8) return codeID Can anybody guide me on this?