Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why Django showing object has no attribute?
Hope you are doing well, i am beginner to the django and python, encountered the error while practicing which is on REST API FRAMEWORK of DictField . i took an example on DictField. I have posted a code below please have a look. feel free to ask if you have any questions. please solve the issue. Thanks a lot for your help. app1/serializers.py from rest_framework import serializers class Geeks(object): def __init__(self, dictionary): self.dict = dictionary class GeeksSerializer(serializers.Serializer): dictionary = serializers.DictField() child = serializers.CharField() python manage.py shell >>> demo = {} >>> demo['name'] = "Naveen" >>> demo['age'] = 21 >>> obj = Geeks(demo) >>> serializer = GeeksSerializer(obj) >>> serializer.data Error: Traceback (most recent call last): File "rest_framework\fields.py", line 457, in get_attribute return get_attribute(instance, self.source_attrs) File "rest_framework\fields.py", line 97, in get_attribute instance = getattr(instance, attr) AttributeError: 'Geeks' object has no attribute 'dictionary' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<console>", line 1, in <module> File "rest_framework\serializers.py", line 555, in data ret = super().data File "rest_framework\serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "rest_framework\serializers.py", line 509, in to_representation attribute = field.get_attribute(instance) File "rest_framework\fields.py", line 490, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting … -
Add group and permission to group with migration django
i have problem with groups and permission in django. I want to create a group of users and admin. In django panel admin i see permission which i need: app | user | Can add user app | user | Can change user app | user | Can delete user app | user | Can view user I need create group "user" and "admin" then add perm to user "Can view user" and to admin all this perms and this is need to do with migration. My already code i suposed is totally stupid # Generated by Django 4.0.3 on 2022-09-11 10:33 from django.db import migrations, transaction from django.contrib.auth.models import Group, Permission def add_group_permissions(a,b): group, created = Group.objects.get_or_create(name='user') try: with transaction.atomic(): group.permissions.add(can_view_user) group.save() except InterruptedError: group.delete() class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.RunPython(add_group_permissions), ] If anyone can help, i need that. -
How can I add uuid to url in urls.py django?
I have django app with authentication in it and email verification. When user is created activation email is sent with link inside of it, when user clicks this link is doesn't take him nowhere. views.py class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = 'authentication/customer_register.html' def form_valid(self, form): user = form.save() user.token = str(uuid.uuid4()) subject = 'Verify your account | Zane' message = f"http://127.0.0.1:8000/accounts/verify/{user.token}/" recipient_list = [user.email] send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) return redirect('/') def activate(request, token): try: obj = models.User.objects.get(email_token = token) obj.signup_confirmation = True obj.save() return HttpResponse('Your account is verified') except Exception as e: return HttpResponse('Invalid token') urls.py path('verify/<uuid:pk>/', views.activate, name='activate'), models.py ... token = models.CharField(max_length=200, blank=True) signup_confirmation = models.BooleanField(default=False) I wonder what do I need to put in my url to trigger my function? -
Django serializer test post of file with user information
I try to test a file upload like this: def test_this(self, api_client, login_as): user = login_as('quality-controller') url = reverse('icsr-list') organization = Organization(name="test") organization.save() data = { "organization": organization.id, "import_file": FileGenerator.generate_text_file('txt'), "user": { "id": user.id, "username": user.username, } } response = api_client.post(url, data, format='json') But I receive the following error message: b'{"import_file": ["The submitted data was not a file. Check the encoding type on the form."]}' I also tried to use: format='multipart' but then I receive the following error: AssertionError: Test data contained a dictionary value for key 'user', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. How can I solve this? -
django.urls.exceptions.NoReverseMatch: Reverse for 'login_otp' not found. 'login_otp' is not a valid view function or pattern name
I have created a Django application where I have created a custom user model and using login through otp. I want to send the otp on email. I am geeting the error - "django.urls.exceptions.NoReverseMatch: Reverse for 'login_otp' not found. 'login_otp' is not a valid view function or pattern name." Not able to solve this one. Following is my model-: User = get_user_model() class S_Society_Association_Master(AbstractBaseUser): member_id = models.CharField(verbose_name = "Member_ID", primary_key=True, max_length=100, unique=True) member_name = models.CharField(verbose_name = "Member Name", max_length=100) password = models.CharField(verbose_name = "Password", default=NULL, max_length = 100, null=True, blank=True) member_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) otp = models.CharField(max_length=6, blank=False, default=0) # For HOTP Verification member_role = models.CharField(verbose_name="Member's Role", max_length=100, choices=[("P", "President"), ("T", "Treasurer"), ("S", "Secretary"), ("EC", "EC members"), ("O", "Other members")]) member_email_id = models.EmailField(verbose_name = "Member's Email", max_length=100) member_from_date = models.DateField(verbose_name = "Member From", auto_now_add=True) member_to_date = models.DateField(verbose_name="Member To") created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True, blank=True, null=True) created_by = models.ForeignKey(User, to_field='id', related_name = "assoc_created_by", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True) last_updated_date = models.DateField(verbose_name = "Updated Date", auto_now = True, blank=True, null=True) last_updated_by = models.ForeignKey(User, to_field='id', related_name = "assoc_updated_by", on_delete = models.SET_NULL, verbose_name="Last Updated By", max_length=100, blank=True, null=True) USERNAME_FIELD = 'member_email_id' Following is my views.py-: def … -
Django raise BadRequestError(msg) razorpay.errors.BadRequestError: The amount must be an integer. while refund
When I try to print it, it appears as an integer, but I get an error saying "The amount must be an integer." when I run the project if str(Payments).__contains__("pay"): paymentId = Payments.payment_id amount = int(Payments.amount_paid) refund_amount = int(amount) * 100 reamount = int(refund_amount) print(reamount) print(type(reamount)) client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) client.payment.refund( paymentId, { "amount": reamount, "speed": "optimum", }, ) # addning stock in product order_items = OrderProduct.objects.filter(order=order) for item in order_items: product = Product.objects.get(id=item.product_id) product.stock += item.quantity product.save() -
Not able to install viewflow-pro
i want to work with viewflow rest. I have my requirements.txt as django==2.2.25 djangorestframework==3.11.2 django-rest-swagger==2.2.0 django-viewflow-pro==1.4.1 django-material-pro==1.4.1 pyaml==20.4.0 celery==5.2.2 coreapi==2.3.3 I ran pip install -r requirements.txt. But it gives me error ERROR: Could not find a version that satisfies the requirement django-viewflow-pro==1.4.1 (from versions: none) ERROR: No matching distribution found for django-viewflow-pro==1.4.1 How can i use viewflow.rest package in my prject? -
How to use Backend Functions via the Front End
I am a fairly new Developer who has just build his first Full Stack App with Django Rest Framework and a REACT Front End. I want to keep my business logic primarily in my backend, but how do I trigger the functions in my backend? It is counterintuitive to me to just make an Resource Endpoint when I do not necessarily need information in my front-end. For example - I'm working on a course planning application where you need to inform several instructors via email if they are interested in supervising the course. Should I therefore just make an endpoint like this: http://127.0.0.1:8000/api/rest/course/<course_id>/inform_instructors and use the business logic there? Or are there any other ways to use the business logic in the backend? Somehow this does not look right for me. Thanks in advance! -
Show fields in the filter depending on the query
I use django-filter on my website to search for books. The filter includes the following fields: book genre, language the book is written in, publication date, and search field. The search looks for several fields in the database, including the book title, authors of the book, etc. The filter works fine, but I don't understand how to make it so that when I search for a book when I select some fields - other fields are removed depending on whether there are such objects. For example, I am looking for a book in Chinese, I select this field, and I have the genres not used removed after the results are displayed. Right now I have all the filters shown, even there are no books there The second question is, can I make it so that after I search, I can see how many objects are in each field? That is, if I entered Harry Potter in the search and got a result, I see that there are 5 objects in English. models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey( "Authors", on_delete=models.SET_NULL, null=True, blank=True, ) subject = TreeManyToManyField("Subject") published_date = models.DateField(blank=True, null=True) language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) class Subject(MPTTModel): … -
djstripe admin cannot view synced plans or products
I have a problem when I use django admin to view products and prices in djstripe. I have synced everything on Stripe portal. I get an error Exception Type: TypeError at /admin/djstripe/plan/ Exception Value: 'NoneType' object is not subscriptable How do I solve this? Been stuck here -
anyone with the right solutions--Auto mail send to student for upcoming lesson date and time, but issue here is that i have to make changes on my view
The issue here is that i have to change something from the code before the mail sent to respective subscriber schedule for that date, and not that it is sent to many of them but only one person recieved that email, maybe something the loop or my views, below is my views.py, the update is expected to run when the message delievered successfully the code works but, i have to make a change on the views before it finally sent. thanks substatus = SubscribeEmailModel.objects.filter(topic__startdate=today, sent_mail=False) print(substatus) recipient_list = {} for recipient in substatus: recipient_list[recipient.topic] = recipient.email print(recipient_list) for course in substatus: print(course.topic) top = course.topic if top != "": subject = 'Lesson Notification' from_email = 'example<example@example.com>' message = f'{course.topic} will be available online on {course.topic.startdate} starting from {course.topic.starttime} for more info reach out to your lecturer' send_mail(subject, message, from_email, [recipient_list[recipient.topic]], fail_silently=False) substatus.update(sent_mail=True) model = SubscribeEmailModel context_object_name = 'substatus' template_name = 'auto-send.html' -
Expecting property name enclosed in double quotes: line 1 column 2 (char 1) when converting Stringify to JSON [closed]
I am receiving a stringify object in Django. I am trying to convert it back to json using json.loads but getting error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). I also make sure that I am using double quotes "" instead of single quotes '' as mentioned in one of stackoverflow post but still getting it. This is the json: { "journey": { "id": 1, "name": "Test Jour", "journey_location": [ { "id": 2, "name": "2", "photo": "https://p2.png/", "sublocation": [] } ] } } This is stringify: {\"journey\":{\"id\":1,\"name\":\"Test Jour\",\"journey_location\":[{\"id\":2,\"name\":\"2\",\"photo\":\"https:\/\/p2.png\/\",\"sublocation\":[]}]}} -
I cannot send a variable to template in django
I am new to django so i would really appreciate some help.. I try to send data (for start a variable with some text) to an .html template and I cannot make it work, although I don't get any error. Here is my code.. views.py context = {'patient': 'abcde'} return render(request, 'examtable.html', context)``` examtable.html '''<div class="row d-flex align-items-center"> <div class="col-9"> <h3 class="f-w-300 d-flex align-items-center m-b-0"> <i class="feather icon-arrow-up text-c-green f-30 m-r-10"></i>$ <p>{{patient}}</p></h3> </div>''' urls.py '''urlpatterns = [ # The home page path('', views.index, name='home'), path('insert_patient',views.insert_patient,name='insert_patient'), path('nurse_patient',views.nurse_patient,name='nurse_patient'), path('examtable',views.exam_table,name='examtable'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] ''' The html file loads but the field {{patient}} is blank not showing the 'abcde'. Thank you in advance -
Problem with registrating new Django user
Can't register new user in Django, because when I try to do it the error that "user is already used" appears. Info that I put into form The result of the previous action Code (views.py) Urls.py and everything else is ok, the problem is with code. This code was taken from the youtube course and I've compared the code of the author and mine hundred times and still have this error. P.S. The admin panel is clear, there're no users apart from admin (superuser) Admin panel -
Add google maps coordinate in a database sqlite with react and django wagtail
I would like to store in a database(sqlite) some places (i.e restaurants,banks, bars and so on). Also, I would like to use the location of the user to show him/her the locations near and far from his/her location. I hope , I am clear enough . Thanks in advance, -
Can't get uuid value in email body in django
I have authentication app with email verification in it. I send an email like this: If registration form is valid then we save the form(create user) and set his token to uuid.uuid4. class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = 'authentication/customer_register.html' def form_valid(self, form): user = form.save() user.token = str(uuid.uuid4) subject = 'Verify your account | Zane' message = f"http://127.0.0.1:8000/verify/{user.token}/" send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) In my mailtrap.io email arrives but it has some weird body: http://127.0.0.1:8000/verify/<function uuid4 at 0x103f32040>/ -
Deploying a dockerized Django app on a NAS
I’m very new to Docker and trying to run a simple Django app on my Asustor NAS following this guide https://docs.docker.com/samples/django/. But I can’t figure out what should I do with the ports to access the app. The NAS is connected to the Internet via a router. Apache web server is running on port 80 on the NAS. There also is a virtual host which already hosts 2 Wordpress websites. Example1.com redirects to /Web/example1 and example2.com redirects to /Web/example2. I also have an example3.com domain, which redirects to /Web/example3. So, I upload my app to /Web/example3 and start it with "docker-compose up". It starts successfully and the containers appear in Portainer in the NAS admin panel. Docker-compose.yml command is “python manage.py runserver 0.0.0.0:9000”. I tried setting ports in docker-compose.yml to “9000:9000” and “9000:80”. In both cases accessing NAS-local-ip:9000 returns the "server isn’t responding" error. Example3.com displays Apache “Index of/“ page with a list of files and folders of my app. How should I configure the ports to access the app both within the local network and outside of it? Any help will be appreciated. -
error: Dinucleotides matching query does not exist
I am trying to fetch specific rows from table on the basis of user input in forms. on pressing submit button, getting the following error. Error: DoesNotExist at /search/ Dinucleotides matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/search/ Django Version: 4.0.6 Exception Type: DoesNotExist Exception Value: Dinucleotides matching query does not exist. Exception Location: C:\ssrdb\lib\site-packages\django\db\models\query.py, line 496, in get Python Executable: C:\ssrdb\Scripts\python.exe Python Version: 3.10.5 Python Path: ['C:\ssrdb\Scripts\chick', 'C:\python310.zip', 'C:\DLLs', 'C:\lib', 'C:\', 'C:\ssrdb', 'C:\ssrdb\lib\site-packages'] Server time: Wed, 14 Sep 2022 07:08:27 +0000 views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from ssr.models import Dinucleotides from ssr.forms import InputForm # Create your views here. def homepage(request): return render(request,'index.html') def searchpage(request): if(request.method == 'GET'): form=InputForm() return render(request,'search.html',{'form':form}) else: print(request.POST) if(request.POST['Motiff']): obj1=Dinucleotides.objects.get(SSRtype='Motiff') return render(request,'result.html',{'obj1':obj1}) -
Django - forloop to show/filter a value to show only once the entrys
I have a model (Restrictie) in which those who voted (participanti) and those who voted (votant) are registered. If I forloop in the templates, I can see who voted for whom, but one line is displayed for each record. How can I make a forloop or query in which participants are displayed only once and next to all the voters for example: name participanti - (name votant 1, name votant 2, ....) Below my code models.py class Participanti(models.Model): campanievot = models.ForeignKey(Campanie, on_delete=models.CASCADE) nume_participant = models.CharField(max_length=200, verbose_name='nume') dep_participant = models.CharField(max_length=200, verbose_name='departament') votes = models.IntegerField(default=0) def __str__(self): return self.nume_participant class Meta: verbose_name = 'Participanti' verbose_name_plural = 'Participanti' class Restrictie(models.Model): participanti = models.ForeignKey(Participanti,on_delete=models.CASCADE, verbose_name='Votat') votant = models.ForeignKey(UserVot,on_delete=models.CASCADE) def __str__(self): return str(self.participanti) class Meta: verbose_name = 'Voturi efectuate' verbose_name_plural = 'Voturi efectuate' views.py def rezultate(request): cineavotat = Restrictie.objects.all() ....... I tried this but it's show all entries like : name 1 = voters 1, name 1 = voters 2 ... {% for p in cineavotat %} {{ p.participanti }} - {{ p.votant}} {% endfor %} Please help me with a solution. Thank you! -
multiple deletion in django rest framework
I am working upon User model, So I need an urgent help on how to delete multiple users by getting id of users in views. I have tried with this in views but does'nt works: class UserDeleteView(APIView): permission_classes = (IsAdminUser,) def get_object(self,id): try: return User.objects.get(id=id) except User.DoesNotExist: raise Http404 def delete(self,request,id,format=None): userData=self.get_object(id=id) if userData: for usr in userData: usr.delete() -
Danger of DEBUG = True in production [closed]
I've read all about Django's DEBUG = True and some of the effects, but it never states WHY you should not use DEBUG = True in production, only that you shouldn't. I've also read that DEBUG=True remembers every query you make which will increase in memory over time. Recently though, I've found out you can just change the technical_500.html, technical_404.html (and maybe even the technical_500.txt) in .venv/Lib/site-packages/django/views/templates or the functions themselves in .venv/Lib/site-packages/django/core/handlers/exception.py and get no traceback and data dump whenever you get a 404 or 500 response. So my question is: is there any real danger in setting DEBUG to True and changing the html's (or functions) mentioned above, if you also have no queries? P.S I know this may be bad practice, just curious. -
Error: A bytes-like object is required, not 'list'
I am developing a small project that aims to enable to the user to submit a zip file. The system should read the file, extract it and save its contents to the database. I am having this error : a bytes-like object is required, not 'list' because I tried to use BytesIo. without it, the error said :" fpin.seek(0, 2) AttributeError: 'list' object has no attribute 'seek'" My code looks like this files = request.FILES.getlist('document[]') with zipfile.ZipFile(io.BytesIO(files), "r")as archive: for zippedFileName in archive.namelist(): with archive.open(zippedFileName) as myfile: with io.BytesIO() as buf: buf.write(myfile.read()) buf.seek(0) file = File(buf, zippedFileName).decode('utf-8') rbe = UploadedFile.objects.create(document=file) rbe.user= request.user rbe.save() return render(request, 'uploader/index.html', {'files': files}) -
Which one is better option to choose as a Primary key for Cart in Django? UUID or Session Key?
So, I have been working on a DRF eCommerce project. As, using the auto incrementing id field in the cart model isn't ideal. I chose to use UUIDField for it. I can achieve the same with session key too. But, I was wondering if there is any approach that meets the industry standard? Please suggest me the more appropriate primary key choice with a explanation from a industry point of view. class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) skey = models.CharField(max_length=250, null=True) total_price = models.PositiveIntegerField(editable=False, blank=True, null=True) date_added = models.DateField(auto_now_add=True) def __str__(self): return self.skey -
How to use simplify data access in django using context caching
class SampSerializer(CustomModelSerializer): user = serializers.SerializerMethodField() user_id = serializers.IntegerField(source="user.id", read_only=True) role = serializers.SerializerMethodField() a = serializers.SerializerMethodField() b = serializers.SerializerMethodField() c = serializers.SerializerMethodField() d = serializers.SerializerMethodField() e = serializers.SerializerMethodField() f = EscapedCharField() g = EscapedCharField(source="user.referred_by", read_only=True) h = serializers.SerializerMethodField() i = serializers.SerializerMethodField() class Meta: model = UserOverview fields = ( "id", "user", "user_id", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", ) def get_user(self, obj): print(len(connection.queries)) if obj.user: return obj.user.display_name().strip() else: return "" When I call the api linked to the above serializer? It prints the length of the connection queries as 14 and thus becomes slow. How do I speed up the query using context caching -
How can I connect zappa to local database sqlite in django application? [closed]
I got an error while using zappa to connect with local database sqlite in django.