Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I migrate a project in Django which is made in Flask?
I have a developed a project in python using Flask and Sqlalchemy as the ORM. How do I migrate the project into Django? I have gone through a couple of blogs but couldn't really understand how it should be done. How do I migrate it in Django? -
Django count column using raw
Is there anyway how can I count my paid column in my query? It is possible? thanks in advance The error says : AttributeError: 'Cursor' object has no attribute 'paid' def dictfetchall(cursor): desc = cursor.description return[ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def sample(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid", [blank]) row = dictfetchall(cursor) datas = cursor.paid print (datas.count()) -
Django Rest - Posted data creating new rows in Foreign key referenced tables
I am trying to post data to my orders model. It has several foreign keys. When I tried to post data, it is trying to create objects in the referenced models also. My models.py: from django.db import models from django.contrib.auth.models import User from accounts.models import Profile class Nursery(models.Model): name = models.CharField(max_length=30,unique=True) state = models.CharField(max_length=40) city = models.CharField(max_length=40) profile = models.OneToOneField(Profile,on_delete=models.CASCADE) class Plants(models.Model): name = models.CharField(max_length=30,unique=True) image = models.ImageField(upload_to='static/plants') price = models.IntegerField() nursery = models.ForeignKey(Nursery,on_delete=models.CASCADE) class Order(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Plants,on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now=True) order_id = models.UUIDField(auto_created=True) is_purchased = models.BooleanField(default=False) cost = models.IntegerField() quantity = models.IntegerField() nursery = models.ForeignKey(Nursery,on_delete=models.CASCADE) So, I tried posting data into Order model, and it gave error Plant name already exists meaning that it is trying to create a row in Plants and Nursery models also. My serializers.py: from .models import Plants,Order,Nursery from rest_framework import serializers class NurserySerializer(serializers.ModelSerializer): class Meta: model = Nursery fields = "__all__" class PlantSerializer(serializers.ModelSerializer): nursery = NurserySerializer() # nursery = NurserySerializer() class Meta: model = Plants fields = ['name', 'price','image','nursery'] class OrderSerializer(serializers.ModelSerializer): user_name = serializers.CharField(source='user.username', read_only=True) product = PlantSerializer() nursery = serializers.CharField(source='nursery.name', read_only=True) class Meta: model = Order fields = ['user_name', 'product','date_ordered','order_id','is_purchased','cost','quantity','nursery'] Views.py: class PostOrder(APIView): def post(self, request, format=None): print(request.data) serializer … -
Python problem with RSA decrypting web-user password
i got a problem about decrypting a password from webfrond. I try to get password after decrypting a data,but i always get a turn which is :<bound method _UrandomRNG.read of <Crypto.Random._UrandomRNG object at 0x7f9385ea04c0>> here are my codes of decrypt-part in Django Frame. from Crypto import Random from Crypto.PublicKey import RSA import base64 from Crypto.Cipher import PKCS1_v1_5 def decrypt_pass(password): with open('crypto_info/my_private_rsa_key.pem', 'rb') as f: privkeystr = f.read() f.close() random_generator = Random.new().read RSA.generate(1024, random_generator) rsakey = RSA.importKey(privkeystr) cipher = PKCS1_v1_5.new(rsakey) return cipher.decrypt(base64.b64decode(password), random_generator) def user_login(request): random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) rsa_private_key = rsa.exportKey() rsa_public_key = rsa.publickey().exportKey() with open('crypto_info/my_private_rsa_key.pem', 'w') as f: f.write(rsa_private_key.decode()) f.close() with open('crypto_info/my_publick_rsa_key.pem', 'w') as f: f.write(rsa_public_key.decode()) f.close() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print('password_raw: ', password) print('rsa_publick_key: ', rsa_public_key) print('rsa_private_key: ', rsa_private_key) ********** Here, i just want to get my web password! password = decrypt_pass(password) print(password) ********** user = authenticate(request, username=username, password=password) if user is not None: login(request, user) status_code = 0 return JsonResponse({'code': status_code, 'url': '/'}) else: return HttpResponse('haha') return render(request, 'registration/user_login.html', {'pub_key': rsa_public_key.decode()}) -
Django - Alternative for FileSystemStorage in Production Environment
I am fairly new to django and I want to deploy my app. I have used FileSystemStorage to store my files in a Media folder in my django app however I've also read that it should not be used in a production environment. My code is essentially the same as the one shown in the geeksforgeeks website. Why can't I use FileSystemStorage in a production environment and what can I use instead? -
I am getting problem in reverse url of python django for creating the web application
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I have tried a number of different variants please take a look at my code: I have a urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from django.urls import path from .views import home_page, about_page, room_page, login_page, register_page urlpatterns = [ url(r'^$', home_page), url(r'^home/$', home_page), url(r'^about/$', about_page), url(r'^room/$', room_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^products/', include("products.urls", namespace='products')), url(r'^youadmin/', admin.site.urls), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py-myapp from django.conf.urls import url from .views import ( ProductListView, ProductDetailSlugView, ) urlpatterns = [ url(r'^$', ProductListView.as_view(), name='list'), url(r'^(?P<slug>[\w-]+)/$', ProductDetailSlugView.as_view(), name='detail'), ] A card.html <div class="card" style="width: 18rem;"> {% if instance.image %} <a href="{{ instance.get_absolute_url }}"><img src="{{ instance.image.url }}" class="card-img-top" alt="{{ instance.title }} logo"></a> {% endif %} <div class="card-body"> <h5 class="card-title">{{ instance.title }}</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="{{ instance.get_absolute_url }}" class="btn btn-primary">view</a> <!-- <a href="{% url 'products:detail' … -
What are the settings.py credentials for SMS in DJANGO of integrating the third party API like SMSBOX, other than TIWILIO
WHAT WILL BE THE CREDENTIALS IN settings.py, TO SEND THIS SMS VIA THIRD PARTY API. LIKE WHERE TO GIVE # HOST_NAME, PASSWORD, API_KEY? message = SmsMessage(body='Project Created', from_phone='+923117593775', to=['+923411727228']) message.send() -
Exclude assigned objects from edit form one to one relationship in django admin forms
I have two models named RecId and Record in OneToOne relationship, models.py class RecId(models.Model): rec_id = models.CharField(max_length=255) def __str__(self): return str(self.rec_id) class Record(models.Model): rec_id = models.OneToOneField(RecId, on_delete=models.CASCADE, null=True, blank=True) desc = models.TextField() user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) def __str__(self): return str(self.rec_id) My problem is, In default, django admin Record edit form edit field (RecId field) shows all the rec_ids in RecId table. But I need to show only records that can be assigned to a Record (because the relationship between two tables is OneToOne, one id can only be assigned to one record) I tried to do that by using formfield_for_foreignkey() method but currently stucked with the query admin.py @admin.register(Record) class RecordAdmin(admin.ModelAdmin): list_display = ['rec_id', 'desc', 'user'] search_fields = ['rec_id', 'user'] def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "rec_id": kwargs["queryset"] = RecId.objects.all().exclude(... The query ...) return super(RecordAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) I tried to query it by using ~Exists(Record.objects.filter(rec_id__eq=OuterRef('pk'))) an hour or two ago and it didn't work. So any help is greatly appreciated. -
Django (DIFFICULT!) Why is my send interest request not appearing? Its like the variables I defined are not working
ValueError at /HomeFeed/slug-1/detail/ The QuerySet value for an exact lookup must be limited to one result using slicing. interest_list = InterestList.objects.get(interestuser=account) Hi everyone this is a big problem and I'll be super grateful if you can help me identify the problem haha: There are multiple errors in my code and this error is only one of them... Ok heres the story: In my project, people get to post blog posts, and people that read the blog post and like it can send an "interest request" maybe to comment more about the blog post and the maker of the blog post can accept or reject that interest request. Its basically something like a friend request, except the request you are sending are your "thoughts" in a form. I am trying to tilt my code while building my relationship system to fit into this "submit interest system". Ok so I have 4 models in total, one for the posts, one is my user account model, one is the interest list and the second one is the interestrequest. Theres 4 major functions, accept the request, decline the request (if you are the blog post maker) and send and unsend the request (if you … -
django: unsign values without original value
I am working on a Django app and using Django's Signer to sign my pk's in urls this is my code from django.core.signing import Signer signer = Signer() value = signer.sign(1) this gives me 1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550' and then I am using this value in my templates like <a href="edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/">Edit</a> However, I can strip the value to get the only signed value but when I need to unsign it back to use in my query, it needs the original value to unsigned. How can I unsign this value without using the original value? I don't want my URLs to look like this edit/1:4CrdZAT9VZfsW3ZdFf1Ud_zwP_3JRTP6xwwFzseK550/ (Remove original pk with ':'). Thanks for any help. -
django rest-frame work jwt athentications fails although I sent correct token
I can receive valid access and refresh token after I logged in to my login endpoint API. for some views, I have given is_authenticate permission where after providing a valid token, the user can get access to that view. the problem is although I provide a valid token, still it tells me { "detail": "Authentication credentials were not provided." } how can I solve the issue. here is my code. settings. py INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'rest_framework' , 'rest_framework_simplejwt.token_blacklist' , 'bd_api' , 'op_api' , 'drf_yasg' , 'django_filters' , 'corsheaders' , ] SITE_ID = 1 REST_FRAMEWORK = { 'NON_FIELD_ERRORS_KEY': 'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } # for jwt SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME' : datetime.timedelta(minutes=3) , 'REFRESH_TOKEN_LIFETIME' : datetime.timedelta(days=1) , } # swagger SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS' : { 'Bearer' : { 'type' : 'apiKey' , 'name' : 'Authorization' , 'in' : 'header' } } } views.py class op_ViewSet(viewsets.ModelViewSet) : permission_classes = (permissions.IsAuthenticated,) queryset = Op.objects.all().filter() serializer_class = op_Serializer authentication_classes = [TokenAuthentication , SessionAuthentication , BasicAuthentication] # pagination_class = PageNumberPagination # pagination_class = StandardResultsSetPagination filter_backends = [DjangoFilterBackend , SearchFilter , OrderingFilter] filter_class = op_filter ordering_fields = ['close_date' , ] ordering = … -
Use LIMIT with Django Models on aggregate function
For measurement purposes I would like to limit the QuerySet that comes back from DjangoModels. I want to check how much time it takes to get a QuerySet with a specific amount of objects. Here I try to summarize my problem. In SQL: SELECT author, AVG(books) FROM books LIMIT 10000 I know how do aggregate in Django but not to combine. My idea is now to combine my Query like this: Books.object.all()[:10000].aggregate(Avg('books')) This doesn't work, because the object that will be returned is the result of the aggregation I know. If I send the query Books.object.all()[:10000] it works. Also the aggregation like this: Books.object.aggregate(Avg('books')). But is there a way to send a query like this with djangoModels? Thank you in advance. -
Django Template Countdown
I want to countdown the remaining days before the deadline ends and display in Label/Ageing. I have a javascript but when I get the date from my database always null value. Anyone Can give me an idea on how to get the list of Date value order by ID to make Countdown.Thank you! This is my javascript code but output always "EXPIRED" and Ageing value is "Null" <script> var Ageing = new Date({{ object.Date_resolved_inital }}); var x = setInterval(function() { var now = new Date().getTime(); var distance = Ageing - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); document.getElementById("days").innerHTML = days + "d "; if (distance < 0) { clearInterval(x); document.getElementById("days").innerHTML = "EXPIRED"; } }, 1000); </script> Django Views class CS(ListView): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) model = log template_name = 'CS/pending.html' Models.py Date_resolved_inital = models.DateTimeField(auto_now_add=False, blank=True, null=True) Table The Countdown value appears in Ageing column by ID Database This are the value to compute the Countdown, date value comes from API -
How to calculate the number of non-zero fields in a row and using that make a query in Django
My model from django.db import models class Books(models.Model): field_1 = models.IntegerField(default=0) field_2 = models.IntegerField(default=0) .......................... field_6 = models.IntegerField(default=0) Now I want to make a query to count the number of Books where exactly 3 fields are non-zero. -
How to debug built in django code with breakpoint
Is there a way to set breakpounts in Django default codes like the ones at django/cobtrib/auth/views.py I tried Import pdb And then breakpoint () But it simply ignores it. Print() does work. Any help is appreciated. -
Django User with that username already exists
My aim - Trying to create an authentication system in Django, and allows user to signup again with same username if their account is not activated. If an user try to register with a certain username and that username already exists then update that user with this current user. My Approach - I have created a form using "UserCreationForm" and defining my own methods to validate the form, and allows the user even if username already exists but user.is_active = False. Code forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from .models import User class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') name = forms.CharField() institution = forms.CharField() def clean_username(self): username = self.cleaned_data.get('username') user = None try: try: user = User.objects.get(username=username) print("is user active username", user.is_active) except ObjectDoesNotExist as e: pass except Exception as e: raise e if not user: pass elif not user.is_active: pass else: raise forms.ValidationError("This Username Already Exists") except Exception as e: raise e return username class Meta: model = User fields = ('username', 'email', 'institution', 'password1', 'password2') views.py from .forms import SignupForm def regUser(form): ''' It will save Django user and student. It recieves form.cleaned_data as argument ''' print("reg user line 1") user = User.objects.create_user(username=form['username'], email=form['email'], password=form['password1'], … -
django reset sequence for all autofields in a project
In my django project, I have a lot of models. The thing is, I want to make sure the primary key field of all these models starts with 10000 and increments from there. I am using postgresql at the backend. I know that I can run custom sql migrations for every sequence of my models. But when there are a lot of models, this process becomes not so much applicable. Any alternatives to this? thanks! -
Django how to list customers in the sidebar
I created a system with Django. A user has several customers. The sidebar is in the base.html file. I created a view for the sidebar but It is working only in homepage. When I open a different page, it dissapears. How can I fix it? views.py def base(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(companyName=userP[0].comp_name) return render(request, 'base.html', {'customer_list': customer_list}) base.html <ul> <li class="header-menu"> <span>Customers</span> </li> <li class="sidebar-dropdown"> {% for customer in customer_list %} <a href="#"> <i class="fa fa-building"></i> <span>{{customer.name}}</span> </a> <div class="sidebar-submenu"> <ul> <li> <a href="/customers/{{ customer.id }}/update"> Update</a> </li> <li> <a href="#">Analyses</a> </li> </ul> </div> {% endfor %} </li> </ul> -
Unable to create Django Project
I am trying to create a project in Django using CLI command django-admin startproject MySQLCRUD. But I am getting an error ie: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I tried various solution but couldn't get the error resolved. I already have Python and Django installed in my machine. Attached are the screenshots any solution please ? -
Add extra parameter to serializer.data
I get three fields from rest api i.e name , phone number and email id in serializer but i want to store the datetime as well when i receive the api . in database i have created 4 columns i.e name , phone number, email id , created data . How can i add current date timeparameter to my serializer.data before saving it to posgtresql database table "table_userdetails". please help me with the answers because i am new to it Below is the code for views.py @api_view(['GET', 'POST']) def UserInfo(request): if request.method == 'GET': snippets = UserDetails.objects.all() serializer=UserDetailsSerializer(snippets, many=True) return Response(serializer.data) elif request.method =='POST': context=datetime.datetime.now() serializer = UserDetailsSerializer(data=request.data) print("serializer",serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Below is the code for Models.py class UserDetails(models.Model): name=models.CharField(max_length=255) mobile_no=models.CharField(max_length=255) email_id=models.CharField(max_length=255) user_id=models.IntegerField(primary_key=True) created_date=models.CharField(max_length=255) class Meta: db_table=table_userdetails def __str__(self): return self.response Below is my code for serializer.py class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model=UserDetails fields='__all__' i added context part in post method but how to add in serializer.data .please help me with the solution and what am i doing wrong here .any kind of help is appreciated . Thank you -
<class 'segno.QRCode'> object has no attribute to_artistic (Error on Django not local device)
I am getting this error: <class 'segno.QRCode'> object has no attribute to_artistic My code (url_used is fine): qr = segno.make("sup", error='h') logo_open = urlopen(url_used) buffer = io.BytesIO() qr.to_artistic( background=logo_open, target=buffer, scale=10, border=3, kind='png', finder_dark="black", dark="white") I get this error on Django but don't get it on my local computer. Thanks! -
How to integrate Audio, Video Conferencing using Python & Django
Hello Everyone, I am creating one E-learning Software like BYJU'S where I want to have the functionality for Chat, Audio & Video Conferencing and whiteboard more similar to Zoom. Please take a look for my requirements below: Once Students/Teachers logged-in then they will be able to see their dashboard. Teachers can conduct the classes and there will be Audio, Video chat and Whiteboard similar to Zoom App. For conducting the classes Teacher will create the Room and send the Room Id to the students. Once Students put that Room Id then will jump to the Room where all the functionality will be there like Audio, Video, Chat(for Q&A) and Whiteboard. I'm trying with Open meetings but unable to get a clear idea for integrating these features. Please let me know what are the third party APIs or vendors are available with Django to have this functionality in my Software. -
Django rest framework hide columns logic
I have two tables (user_type and raw_data) while showing raw_data in list method user_type needs facility to hide raw_data columns(i.e. cid, eup, etc) explicitly how to do that? -
how to implement Django and electron.js as a Standalone local app
Does anyone tried out Django + electron.js as standalone local app running on localhost . all the material I can find are some what outdated or just hypothesis. There are some example with Flask . Appreciates your time -
Can we upload and access the uploaded image with just using the ImageField?
We are having trouble while accessing an uploaded image. The idea was to have the ImageField on its own without the CharField, but then we aren't able to find a way to access the uploaded image without the CharField input. # models.py class upload(models.Model): name = models.CharField(max_length=50) main_Img = models.ImageField(upload_to='images/') Here we want to remove the name field. # forms.py class UploadForm(forms.ModelForm): class Meta: model = upload fields = ['name','main_Img'] But then, as we want to access the uploaded image in the views.py folder for further processing on the uploaded image, we are relying on the name field.(uploads = upload.objects.get(name=a)) # Create your views here. def upload_view(request): if request.method == 'POST': form = UploadForm(request.POST,request.FILES) a=request.POST.get("name") if form.is_valid(): form.save() uploads = upload.objects.get(name=a) imgpath=uploads.main_Img.path request.session['imgpath'] = imgpath request.session['imgpt']= a #sr(imgpath) tf=is_grey_scale(imgpath) if tf==False: return redirect(rgb_view) else: return redirect(bw_view) else: form = UploadForm() return render(request, 'upload_image_form.html', {'form' : form}) Is there a way to exclude the name field and yet be able to access the image? If so, how can we do it? My team and I are new to Python and Django in general, so we are pretty confused at this point. Thanks in advance :)