Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show my reset password page in React using Django Rest Framework and Dj-rest-auth
I have an app that has a React front end and a Django api backend. I'm trying to get the password reset page to work but I can't work out how to set up the urls/routing. I had it working locally, but I think that was because the ports for the frontend and backend are different locally, so they were essentially different domains. My Django url patterns includes: path('api/v1/dj-rest-auth/password/reset/confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm') I have a catchall url in my Django urls to make the rest of the frontend work. My React Router includes: <Route path="/api/v1/dj-rest-auth/password/reset/confirm/:uid/:token/" component={ResetPassword} /> My React password reset page contains: let url = process.env.REACT_APP_API_PATH + '/api/v1/dj-rest-auth/password/reset/confirm/' + this.props.match.params.uid + '/' + this.props.match.params.token + '/'; let headers = {token: this.props.match.params.token, uid: this.props.match.params.uid, new_password1: this.state.newPassword, new_password2: this.state.newPasswordConf } axios .post(url, headers) This takes the token and uid from the password reset link then sends them, along with the user's new password to the password reset endpoint. The dilemma seems to be, I need to access the reset link via React to be able to get the token and uid, but then I need to access the same link as a call to the API to be able to reset the … -
How to learn python and django
Hay I want to learn python but I don't know where to find a good resource I have C++ experience but I want to be a server side developer where can I find a good python and django resources -
Python Django, cannot save the main urls.py file without running into errors
So I was following Mosh's course for beginners on django and it was going pretty well but then, when I had to map URLs to Views I started having problems. The minute I am stack in is minute 30:43 and here is the link of the course: https://www.youtube.com/watch?v=rHux0gMZ3Eg I couldn't continue the course without getting errors, I tried to modify the main urls.py file but when I saved the file instead of redeploying I could have seen from the terminal that it ran into errors instead, the list is so long but here there is a link to a free text hosting service where I putted the errors: https://droptext.cc/5hib9 -
Django generic ListView, refering to each items in the object_list
I want to know the amount of trainees for each training in the ListView adding a context. I've search for how to reference each item in the ListView in order to perform a further query on each one. If anyone know a more efective way, i'll be grateful class TrainingsView(ListView): model = NewHireTraining template_name = 'nht/trainings.html' context_object_name = 'trainings' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['headcount'] = Trainee.objects.filter(new_hire_training = self.SOMETHING).count() return context Adding NewHireTraining and Trainee models: class NewHireTraining(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) program = models.ForeignKey(Program, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer, on_delete=models.RESTRICT) start_date = models.DateField() nesting_date = models.DateField() production_date = models.DateField() def __str__(self): return str(self.program) + ' ' + str(self.project) + ' ' + str(self.start_date) class Trainee(models.Model): first_name = models.CharField(max_length=55) last_name = models.CharField(max_length=55) employee_number = models.IntegerField() hire_date = models.DateField() is_term = models.BooleanField(default=False) new_hire_training = models.ForeignKey(NewHireTraining, on_delete=models.CASCADE, default="") def __str__(self): return self.first_name + ' ' + self.last_name -
Display the results of a prefetch_related queryset in a Django template
I'm trying to display a list of objects in a Django template. This list of objects relies on a queryset in which I've used the prefetch_related method to fetch a many to many field. My queryset is queryset = Photo.object.prefetch_related('taggeditem_set__tag').all() The TaggedItem is linked to a photo with a many to many field, and it's also linked to a tag with a one to many field (the Tag contains the name, and this is what I want to display). I then convert this to a list and send it to a view. I would like to display the name of all photos and the name of every tag associated to a photo. However, I cannot found a way to list the associated tags. Is this achievable only in the template or do I have to implement a specific logic in the view? It seems I cannot access photo.taggeditem_set__tag elements in my template. <html> <body> <ul> {% for photo in photos %} <li>{{ photo.name }}, <LIST OF ASSOCIATED TAGS HERE> {% endfor %} </ul> </body> </html> -
Django - How to unit test view managing M2M relationship
I have a view that implements a m2m relationship, and I would like to unit test it, which I did not manage yet. The view seems working with the page I defined, but any suggestion is also welcome. The context is the following: I would like to manage users' groups in a Django app, and, of course, as I need additional fields, I built a model dedicated to user's management in my app. I defined a page with to multiple select boxes, one for the list of users, the other one with users selected to be part of the group. Inbetween are action icons to move users from one group to the others. At the stage, there is no control if a users shall not belong to more than one group, all users that do not belong to the current group are displayed (I assume it's just a question of filtering data). My page currently looks like this (btw, if you have any suggestion to make titles displayed above the selection boxes, I would also appreciate, even if it's not the topic here. I would like to unit test the contain of each group and, later on, the impact of … -
When i run migrate command. AttributeError: 'Model' object has no attribute '_meta'
When i run the following command python manage.py makemigrations I am using Django version 3.0.3 and python 3.8 I am learning django from documentation but it could not run makemigrations comman python manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files (x86)\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\sergio\Documents\Django-Project\2. AdvanceView\mysite\polls\models.py", line 8, in <module> class Question(models.Model): File "C:\Users\sergio\Documents\Django-Project\2. AdvanceView\mysite\polls\models.py", line 9, in Question question_text = models.Model(max_length=200) File "C:\Program Files (x86)\Python38-32\lib\site-packages\django\db\models\base.py", line 408, in __init__ opts = self._meta AttributeError: 'Model' object has no attribute '_meta' -
How to design ArrayField in django rest framework?
I am making API for cook book with Django Rest Framework. I don't know how to design ingredients model to make data to be like this: { "id": 1, "name": "spaghetti", "recipe": "recipe", "ingredients": [ [{name:'pasta',amount:100},{name:'tomato',amount:200},{...}] ], } My model: class Meal(models.Model): name = models.TextField() recipe = models.TextField() ingredients = ? Also how to serialize this field? -
django: M2M annotate Count is slow
When I run Count with annotate from an object that has m2m associated with it as shown below It is slow for some reason. And the same table is being accessed twice, and the second query is taking a long time. What could be causing this and how can I fix it? Also, I want to do order_by on this count, but doing order_by makes the speed even worse. # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) is_actress = models.BooleanField(default=False) class Video(models.Model): tags = models.ManyToManyField(Tag, blank=True, db_index=True) # This is slow. Tag.objects.annotate(count=Count("video")) -
Which cloud server for django, sqlite, cron job equivalent [closed]
I am looking for a Python cloud service provider that offers sqlite (reading and writing) support, as well as django and supports a scheduler library like APschedule or cron job or similar. Preferably more than only one job. Would like to start with a free version. It's a website that is accessed just by myself and contains not too many data. AWS, Azure, google, heroko do not offer all these requirements combined, I suppose?! Can you recommend a free provider? Thanks -
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" }) '''