Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not all fields are showing correctly in django admin
I've added a plan field to my custom Account class, but cannot get it to show on the individual account page in the django admin. It shows correctly in table of all accounts in the list view (as denoted by list_display), but does not show on each individual account page. Here's my Account model: class Account(AbstractUser): PLANS = ( ("free", "free"), ("pro", "pro") ) plan = models.CharField(max_length=10, choices=PLANS, default="free") def __str__(self) -> str: return self.first_name And my admin file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from accounts.models import Account from subscribers.models import Subscriber class SubscriberInline(admin.TabularInline): model = Subscriber extra = 0 class AccountAdmin(UserAdmin): inlines = [SubscriberInline, ] list_display = ("first_name", "plan", "email") # fields = ("first_name", "plan", "email") admin.site.register(Account, AccountAdmin) Why does this happen? Is the problem related to the custom Account class which inherits from the AbstractUser model? I thought to add fields to the AccountAdmin class, but that just returns the below error: ERRORS: <class 'accounts.admin.AccountAdmin'>: (admin.E005) Both 'fieldsets' and 'fields' are specified. The plan field also doesn't show in the admin panel when trying to create a new account (mind you, neither do most of the other fields as it only asks for the username, … -
ProgrammingError at /admin/customers/customers/
my model class Customers(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE) contact_no = models.CharField(max_length=25) time_joined = models.DateTimeField(auto_now_add=True) city = models.ForeignKey(to='restaurants.City', on_delete=models.CASCADE,blank=True,null=True) gender = models.CharField(max_length=10) city model class City(models.Model): city_name = models.CharField(max_length=30) zip_code = models.IntegerField() I previously had an issue with circular import but now, it's throwing this error, I tried to insert some data in the City model but it's showing the same... I am currently completely stuck i am able to run my migrations though, i have read some solutions saying delete all migrations, tried that as well still showing the same tried adding id field still the same i am also getting this error when i am trying to access customers in admin panel my Trace Traceback (most recent call last): File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (column customers_customers.city_id does not exist LINE 1: ...contact_no", "customers_customers"."time_joined", "customers... ^ ) was the direct cause of the following exception: File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\contrib\admin\options.py", line 616, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\atif\PycharmProjects\my_proj_basic\virtual-env\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response … -
uwsgi shows "TemplateDoesNotExist at /" but django runserver works fine
I am building a web server with Nginx, uwsgi and Django. But when I try to build a test app with template, it shows correctly when I run " python manage.py runserver". But when browsing through nginx/uwsgi, it shows "TemplateDoesNotExist at /". /mysite01/settings.py TEMPLATES_DIR = BASE_DIR.joinpath('templates') ... TEMPLATES = [ { ... 'DIRS': [TEMPLATES_DIR], /mysite01/myapp01/urls.py urlpatterns = [ # ex: /myapp01/ path('', views.index, name='index'),] /mysite01/myapp01/views.py def index(request): content_dict = {'insert_me': "'Hello, I am coming from myapp01/index.html template!"} return render(request, 'myapp01/index.html', context=content_dict) /mysite01/tempaltes/myapp01/index.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Polls Index</title> <link rel='stylesheet' href="{% static 'css/myapp01.css' %}"/> </head> <body> <h1>Welcome to myapp01!</h1> <p>{{ insert_me }}</p> </body> </html> And this is my uwsgi.ini config: [uwsgi] # full path to Django project's root directory chdir = /home/admin/mysite01/ # Django's wsgi file module = mysite01.wsgi # full path to python virtual env home = /home/admin/env/MyDjangoEnv # enable uwsgi master process master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /home/admin/mysite01/mysite01.sock # socket permissions chmod-socket = 664 # clear environment on exit vacuum = true # daemonize uwsgi and write messages into given log daemonize = … -
return value.utcoffset() is not None AttributeError: 'datetime.date' object has no attribute 'utcoffset'
Pardon me but I am a bit new to Django, Django does not even tell me the field having issues I keep getting an error I don't understand How do I know the field having issues? When I try to fetch a user profile(Basically a get call) on this model, see the error I keep getting I checked a lot of stack overflow posts but none seems to give me the information I need to resolve these errors on this get profile call File "/MyPath/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/MyPath/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/MyPath/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/MyPath/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/MyPath/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/MyPath/app_features/views.py", line 36, in list return Response(serializer.data) File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 745, in data ret = super().data File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data self._data = self.to_representation(self.instance) File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 663, in to_representation return [ File "/MyPath/lib/python3.8/site-packages/rest_framework/serializers.py", line 664, in <listcomp> self.child.to_representation(item) for item … -
WebRTC local and remote descriptions set but data channel is not being set
I am trying to make a video calling app using Django and WebRTC Here is my js code let video=document.getElementById('video') let video_container=document.getElementById('video-container') let video_btn=document.getElementById('video-btn') let audio_btn=document.getElementById('audio-btn') let join_btn=document.getElementById('username-btn') let username_input=document.getElementById('username') let username="" //video navigator.mediaDevices.getUserMedia({'video':true,'audio':true}).then(stream=>{ video.srcObject=stream video.muted=true var audiotrack = stream.getAudioTracks() var videotrack = stream.getVideoTracks() audiotrack[0].enabled=true videotrack[0].enabled=true video_btn.addEventListener('click',e=>{ videotrack[0].enabled=!videotrack[0].enabled if(videotrack[0].enabled==true)video_btn.innerHTML="Turn Video off" else video_btn.innerHTML="Turn Video On" }) audio_btn.addEventListener('click',e=>{ audiotrack[0].enabled=!audiotrack[0].enabled if(audiotrack[0].enabled==true)audio_btn.innerHTML="Turn audio off" else audio_btn.innerHTML="Turn audio On" }) }) //send signal async function send_signal(user_name,action,etc){ data={ 'username':user_name, 'action':action, 'etc':etc } await socket.send(JSON.stringify(data)) } //add video for new peer function add_video(user_name){ new_video=document.createElement('video') new_video.autoplay=true new_video.id="video-"+user_name video_container.appendChild(new_video) } //send offer to specific channel async function sendoffer(data){ lc =new RTCPeerConnection() rc =lc.createDataChannel('channel') await lc.createOffer().then(e=>lc.setLocalDescription(e)) await send_signal(user_name=username,action="new-offer",etc={'sdp':JSON.stringify(lc.localDescription),'channel':data['etc']['channel']}) rc.addEventListener('message',e=>console.log(e.data)) rc.addEventListener('open',e=>console.log('connection opened')) } //send Answer to all channels async function sendanswer(data){ lc = new RTCPeerConnection() lc.addEventListener("datachannel",ev=>{ console.log("data channel set") lc.rc=ev.channel }) await lc.setRemoteDescription(JSON.parse(data['etc']['sdp'])) await lc.createAnswer().then(e=>lc.setLocalDescription(e)) await send_signal(user_name=username,action="new-answer",etc={'sdp':JSON.stringify(lc.localDescription),'channel':data['etc']['channel']}) } //set answer sdp to local connection async function setanswer(data){ console.log("setting") await lc.setRemoteDescription(JSON.parse(data['etc']['sdp'])) } //Socket Handling join_btn.addEventListener('click',e=>{ username=username_input.value join_btn.disabled=true username_input.disabled=true socket = new WebSocket("ws://"+window.location.host+"/ws/") socket.addEventListener('open',async e=>{ console.log("connection opened") await send_signal(user_name=username,action="new-peer",etc={}) }) socket.addEventListener('close',e=>{ console.log("connection closed") }) socket.addEventListener('error',e=>{ console.log("connection error") }) socket.addEventListener('message',async e=>{ data= JSON.parse(e.data) console.log("message" + e.data) if(data['username']==username)return else if (data['action']=='new-peer'){ console.log('new user added') add_video(data['username']) await sendoffer(data) } else if(data['action']=='new-offer'){ console.log('new offer added') await … -
What is the differnce between templateview and detailview in django?
Each of this is for displaying a single template as we want,then what is actually it's difference which make it differ? And which is better for using and Why? -
Django Custom User Model migration return error : ValueError: Related model 'user_profile.customuser' cannot be resolved
I have modified the the user authentication to create a custom user. In my user_profile model I log in with email instead of username. I have extended AbstractUserModel for this purpose and have implemented manager and serializer as mentioned bellow. My makemigrations command is executes with success but when I run migration I get an error. I had deleted the entire database and started migrations afresh. As the project is in development I have option to manipulate database as needed. Environment Python==3.9.1 Django==3.2.3 djangorestframework==3.12.4 user_profiles manager.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if email is None: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, … -
Gmail verificated failed in django
I created two class in view.py to achieve account register and verificate. This is my thought.When user registers,django will send an active_link to user's gmail and now user.is_active = False.After clicking it so that user.is_active = True and account verificates successfully.The situation is that my gmail got the aitive_link,but User.objects still equals False after clicking the link. This is my registraion class. class RegistrationView(View): def get(self, request): return render(request, 'authentication/register.html') def post(self, request): username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] context = { 'fieldValues': request.POST } if not User.objects.filter(username=username).exists(): if not User.objects.filter(email=email).exists(): if len(password) < 8: messages.error(request, '密码不会8位都没吧,不会吧') return render(request, 'authentication/register.html', context) user = User.objects.create_user(username=username, email=email) user.set_password(password) user.is_active = False user.save() uidb64 = urlsafe_base64_encode(force_bytes(user.pk)) domain = get_current_site(request).domain link = reverse('activate', kwargs={'uidb64': uidb64,'token': account_activation_token.make_token(user)}) activate_url = 'http://' + domain + link email_body = 'Hi ' + user.username + ' 没时间解释了快点链接认证账户\n' + activate_url email_subject = '激活你的邮箱' email = EmailMessage( email_subject, email_body, 'noreply@gmail.com', [email], ) email.send(fail_silently=False) messages.success(request, '邮箱验证完这帐户就是他娘你的了') return render(request, 'authentication/register.html') return render(request, 'authentication/register.html') This is my Verification class. class VerificationView(View): def get(self, request, uidb64, token): try: id = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=id) if not account_activation_token.check_token(user, token): return redirect('login'+'?message='+'User already activated') if user.is_active: return redirect('login') user.is_active = True user.save() messages.success(request, '账户创建成功') … -
django many to many "through" table which inherits base model in sqlalchemy
I need to migrate saleor product models which is in django to fastapi using sqlalchemy orm. I am having hard time on many to many model part. In case of saleor's product model AssignedProductAttribute is a through model which itself inherits BaseAssignedAttribute abstract model which has another many to many fields. I mean the model related to product attributes look like this in django class BaseAssignedAttribute(models.Model): assignment = None class Meta: abstract = True @property def attribute(self): return self.assignment.attribute @property def attribute_pk(self): return self.assignment.attribute_id class Attribute(ModelWithMetadata): slug = models.SlugField(max_length=250, unique=True, allow_unicode=True) name = models.CharField(max_length=255) product_types = models.ManyToManyField( ProductType, blank=True, related_name="product_attributes", through="AttributeProduct", through_fields=("attribute", "product_type"), ) product_variant_types = models.ManyToManyField( ProductType, blank=True, related_name="variant_attributes", through="AttributeVariant", through_fields=("attribute", "product_type"), ) value_required = models.BooleanField(default=False, blank=True) class AssignedProductAttributeValue(SortableModel): value = models.ForeignKey( "AttributeValue", on_delete=models.CASCADE, related_name="productvalueassignment", ) assignment = models.ForeignKey( "AssignedProductAttribute", on_delete=models.CASCADE, related_name="productvalueassignment", ) class Meta: unique_together = (("value", "assignment"),) ordering = ("sort_order", "pk") def get_ordering_queryset(self): return self.assignment.productvalueassignment.all() class AssignedProductAttribute(BaseAssignedAttribute): """Associate a product type attribute and selected values to a given product.""" product = models.ForeignKey( Product, related_name="attributes", on_delete=models.CASCADE ) assignment = models.ForeignKey( "AttributeProduct", on_delete=models.CASCADE, related_name="productassignments" ) values = models.ManyToManyField( "AttributeValue", blank=True, related_name="productassignments", through=AssignedProductAttributeValue, ) class Meta: unique_together = (("product", "assignment"),) class AttributeProduct(SortableModel): attribute = models.ForeignKey( "Attribute", related_name="attributeproduct", on_delete=models.CASCADE ) product_type … -
Error while running '$ python manage.py collectstatic --noinput' while deploying app
New to Django, trying to deploy my web app but keep getting this error. I do understand the traceback. Any help will be appreciated. remote: Traceback (most recent call last): remote: File "/tmp/build_3810ef0f/manage.py", line 22, in <module> remote: main() remote: File "/tmp/build_3810ef0f/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 329, in run_from_argv remote: connections.close_all() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 225, in close_all remote: connection.close() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 190, in close remote: if not self.is_in_memory_db(): remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 280, in is_in_memory_db remote: return self.creation.is_in_memory_db(self.settings_dict['NAME']) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db remote: return database_name == ':memory:' or 'mode=memory' in database_name remote: TypeError: argument of type 'PosixPath' is not iterable remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. My requirements.txt boto3==1.9.96 botocore==1.12.96 certifi==2018.10.15 chardet==3.0.4 dj-database-url==0.5.0 Django==2.1 django-crispy-forms==1.7.2 django-heroku==0.3.1 django-storages==1.7.1 docutils==0.14 gunicorn==19.9.0 … -
How to create and save a csv file in media folder in django?
I am creating a csv file using HttpResponse in django and I also want to save it in the media folder. I have set the MEDIA_ROOT in settings.py def to_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=industry.csv' writer = csv.writer(file) data = Industry.objects.all() writer.writerow(['Name','Workplace and Designation','Contact No.','Email ID','Purpose of Visit','Self Employed Details']) for row in data: writer.writerow([row.name, row.wp_des, row.mobileno, row.email, row.purpose, row.semp_details]) return request -
Send data to the next page's form in django
I have two models Log and LogDetail (They are connected via an FK). This is the flow that I wan to create: Create a Log object, and redirect to it's detail page Inside detail page there is a link to create LogDetail object(s) When the user hits the create LogDetail link it should use Log ID as the default value of the FK in form the problem is that I don't know how to send/receive Log ID -
Calculate user input from form and display results - Django
I have a form to calculate the weight of a postal tray - the form works and when i submit it goes to the database. However, what I'd like to do now is take the information submitted in those fields and do some math to give the calculation they need. views.py @login_required def tray_calc_view(request): model = TrayCalcModel tray_form = TrayCalcForm() if request.method == "POST": tray_form = TrayCalcForm(request.POST) if tray_form.is_valid(): tray_form.save(commit=True) return redirect('tray_weight') return render(request, "tray_weight_calculator.html", {'tray_form': tray_form}) models.py class TrayCalcModel(models.Model): sheets = models.IntegerField(max_length=30) paper_weight = models.IntegerField(max_length=30) I'd like to submit the form and it take me to a new page with the filled in form and a box with the calculation in. I'd like to be able to update that form on this page and recalculate and it update that calculation. urls.py path('tray-weight-calculator/', tray_calc_view, name="tray_weight"), My form is at tray-weight-calculator/ and I'd like the calculated form to be at tray-weight-calculator/calculated-weight How would I need to set up my views.py to do this? -
How to use django social media icons instead of link_text
I am trying to use django-social-media share buttons. The share link comes with text instead of social media icons such as facebook, linkedin and twitter. How can i display the icons instead of "Post to FaceBook" text link? <a href="#!"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x" style="color:#4267B2"></i> <i class="fab fa-facebook-f fa-stack-1x fa-inverse"></i>{% post_to_facebook object_or_url %} </span> </a> <a href="{{ linkedin_url }}"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x" style="color: #0e76a8"></i> <i class="fab fa-linkedin fa-stack-1x fa-inverse"></i>{% post_to_linkedin object_or_url %} </span> </a> <a href="#!"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x" style="color: #1DA1F2"></i> <i class="fab fa-twitter fa-stack-1x fa-inverse"></i>{% post_to_twitter "New Article: {{object.title}}. Check it out!" object_or_url %} </span> </a> -
Django: Encryption for Data at Rest?
I am using Django and am trying to encrypt data at rest in my database which is making use of Django Models. What would be the best way of going about this? I am aware that there are several libraries for encryption in Django. But, I'm a little spoilt for choice and need some recommendations. Thanks in advance. -
Values Not Appending In List As Expected
test={ "licenceFile": "", "pfxFilePath": "", "pfxPassword": "", "pfxAlias": "fin", "inputs": [ { "docBase64" :"RjJVBERi0xLjMNCiX", "signedBy": "Hasan حسن.", "location": "Location", "reason": "Reason", "appearanceRunDirection": "RUN_DIRECTION_LTR", "coSign": 'true', "pageTobeSigned": "Specify", "coordinates": "BottomLeft", "pageNumbers": "1", "pageLevelCoordinates": "", "appearanceBackgroundImage": "", "appearanceType": "", "type": "PDF" } ], "signerInfo": { "rkaName": "", "kycId": "20476", "englishName": "Hasan", "arabicName": "", "mobile": "", "email": "", "address": "", "regionProvince": "", "country": "SA", "photoBase64": "" }, "SIPID": "", "logLevel": "NoLog", "tempFolderPath": "Temp", "sipIsRka": 'true', "userConsentObtained": 'true', "kYCIdProvider": "SELF_NID", "requestTimeout": 0, "proxyPort": 0, "eSignURL": "" } test2= ['hashi','jayesh','midhu'] inp= test['inputs'] inp2=[] for i in range(len(test2)): for j in test['inputs']: inp2.append(j) for i in inp2: i['docBase64'] = test2[0] test2.pop(0) print(i['docBase64']) if not test2: print(inp2) print(inp2) I'm Getting an output as [{'docBase64': 'midhu', 'signedBy': 'Hasan حسن.', 'location': 'Location', 'reason': 'Reason', 'appearanceRunDirection': 'RUN_DIRECTION_LTR', 'coSign': 'true', 'pageTobeSigned': 'Specify', 'coordinates': 'BottomLeft', 'pageNumbers': '1', 'pageLevelCoordinates': '', 'appearanceBackgroundImage': '', 'appearanceType': 'EMDHA_LOGO', 'type': 'PDF'}, {'docBase64': 'midhu', 'signedBy': 'Hasan حسن.', 'location': 'Location', 'reason': 'Reason', 'appearanceRunDirection': 'RUN_DIRECTION_LTR', 'coSign': 'true', 'pageTobeSigned': 'Specify', 'coordinates': 'BottomLeft', 'pageNumbers': '1', 'pageLevelCoordinates': '', 'appearanceBackgroundImage': '', 'appearanceType': 'EMDHA_LOGO', 'type': 'PDF'}, {'docBase64': 'midhu', 'signedBy': 'Hasan حسن.', 'location': 'Location', 'reason': 'Reason', 'appearanceRunDirection': 'RUN_DIRECTION_LTR', 'coSign': 'true', 'pageTobeSigned': 'Specify', 'coordinates': 'BottomLeft', 'pageNumbers': '1', 'pageLevelCoordinates': '', 'appearanceBackgroundImage': '', 'appearanceType': 'EMDHA_LOGO', 'type': 'PDF'}] But Im expecting … -
Django REST get query with symmetric fields
The idea is that, given two hashes, I should return the comparison number between them. These two hashes uniquely identify a database entry and the comparison is symmetric. I have the following model: models.py class Comparison(models.Model): result = models.FloatField() hash1 = models.CharField(max_length=100) hash2 = models.CharField(max_length=100) class Meta: constraints=[ models.UniqueConstraint(fields=['hash1','hash2'], name='compared') ] serializers.py class ComparisonSerializer(serializers.ModelSerializer): class Meta: model = Comparison # exclude = [''] fields = '__all__' views.py class ComparisonView(viewsets.ModelViewSet): serializer_class = ComparisonSerializer queryset = Comparison.objects.all() def get_queryset(self): h1 = self.request.query_params.get("hash1") h2 = self.request.query_params.get("hash2") try: return self.queryset.filter(hash1=h1, hash2=h2) except Comparison.DoesNotExist: try: return self.queryset.filter(hash1=h2, hash2=h1) except Comparison.DoesNotExist: return None Which works, but is clunky since the overridden method get_queryset tries searching for the data one way around and if it doesn't find anything, tries the other direction. This is necessary since I only store one entry per comparison in order to save space, for instance, hash1 = ab5d..., hash2= ef3h..., result=0.4 and not hash1 = ef3h..., hash2= ab5d..., result=0.4. Is there any way to make a query that is more "symmetric"? Finally, one other small annoyance is that ideally I want to return a single object, while currently filter returns a list containing a single object for a unique hash pair. Replacing … -
How to Deploy Multiple Django Apps on Single server using Ngnix & GUnicorn?
I am trying to Deploy Two Django apps with single AWS EC2 Instance having same IP. But it always failed when I have added the second App.sock and test Supervisor. I fond some body asked similar question before. but Not answered properly, and my use case is little different. ( Run multiple django project with nginx and gunicorn ) I have followed these steps: . Cloned my project from Git * pip install -r requiernments.txt pip3 install gunicorn sudo apt-get install nginx -y sudo apt-get install supervisor -y cd /etc/supervisor/conf.d sudo touch testapp2.conf sudo nano testapp2.conf Updated config file same as below [program:gunicorn] directory=/home/ubuntu/projects/testapp2/testerapp command=/home/ubuntu/projects/testapp2/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/projects/testapp2/testerapp/app.sock testerapp.wsgi:application autostart=true autorestart=true stderr_logfile=/home/ubuntu/projects/testapp2/log/gunicorn.err.log stdout_logfile=/home/ubuntu/projects/testapp2/log/gunicorn.out.log [group:guni] programs:gunicorn *---------- sudo supervisorctl reread sudo supervisorctl update sudo supervisorctl status The below steps will work and Site available on browser if there is only One configuration above. But when i have added an additional configuration, it shows 502 Bad Gateway on the Browser. Please help me to solve this issue. -
Creating websocket connections from Django
I’m using Django (ASGI) with channels to handle websocket connections from IoT devices. I also have a task runner in the background to handle periodic and expensive tasks. Devices connect to certain WSS endpoints. The devices lose connection from time to time but usually reconnect. I now have a situation where I need to create websocket connections to a server that acts as a proxy for other IoT devices. I will be the one initiating the connection and ensuring that it remains open. Django is based on request/response. My question is about how to handle this new requirement - with Django or some other approach. I could create a background task that opens and monitor connections for these devices. I could create a separate service that monitors and maintains connections. What is a robust approach considering the stack is Django and the data from these devices will ultimately be used in Django. -
crontab fails to write logs
I'm using crontab to run a python script every minute. This is my how my crontab file looks like: */1 * * * * source /root/.bashrc && source /home/env/bin/activate && python /home/manage.py shell < /home/script.py >> /var/log/navjob.log 2>&1 When try to check cron output in syslog with this command #grep CRON /var/log/syslog the output is like this: ...CRON[764888]: (root) CMD (source /root/.bashrc && source /home/env/bin/activate && python /home/manage.py shell < /home/script.py >> /var/log/navjob.log 2>&1) ...CRON[764887]: (CRON) info (No MTA installed, discarding output) But the log file (/var/log/navjob.log) is empty and the code is not run! -
field is required DRF
serializers.py class UserRegisterSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True, style={'input_type': 'password', 'placeholder': 'Password'}) password2 = serializers.CharField(write_only=True, style={'input_type': 'password', 'placeholder': 'Password confirm'}) is_superuser = serializers.BooleanField(default=True,read_only=True) class Meta: model = User fields = ['username','email','is_superuser','first_name','last_name','password1','password2'] def create(self,validated_data): user = User( username = validated_data.get('username'), email = validated_data.get('email'), first_name = validated_data.get('first_name'), last_name = validated_data.get('last_name') ) password1 = validated_data.get('password1') password2 = validated_data.get('password2') if password1 !=password2: raise serializers.ValidationError({'password2':'عدم همخوانی گذرواژه'}) user.set_password(password1) user.save() Token.objects.create(user=user) return user views.py class UserRegister(generics.CreateAPIView): serializer_class = UserRegisterSerializer queryset = User.objects.all() my error this is my error when I wanna register new user... plz help me to solve it........................ -
html field returning none via POST request (Django)
On submitting password field is showing none while as confirm password is working fine, don't know where I am wrong in this, tried changing name attribute doesn't work Thanks in advance! <div class="form-row"> <div class="form-group col-md-6"> <label>Create password</label> <input name="password" class="form-control" type="password"> </div> <!-- form-group end.// --> <div class="form-group col-md-6"> <label>Repeat password</label> <input name="confirm_password" class="form-control" type="password"> </div> <!-- form-group end.// --> </div> my view @csrf_exempt def register(request): city = City.objects.all() if request.method== 'POST': first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') print(email) gender = request.POST.get('gender') city = request.POST.get('city') country = request.POST.get('country') print(country) password = request.POST.get('password') <-- this returns None conf_password = request.POST.get('confirm_password') contact_no = request.POST.get('mob_number') print(conf_password,password) if password != conf_password: messages.add_message(request,messages.ERROR,'passwords does not match kindl re-enter') return redirect('/register') else: username = email.split('@')[0] print(username) user= User(username=username,first_name=first_name,last_name=last_name,email=email) user.set_password(password) user.save() customer=Customers(user=user,contact_no=contact_no,city=city,gender=gender) customer.save() return redirect('/') return render(request,'register.html',{ 'city':city } ) -
how to pass if else statement in django db for fetching model in django
i create model name item in that some of them field can be empty some of them not so what i want to render is the model field is empty then pass and go look for another and if it has some value render without throwing error right now it will throw if request a null field so how can i fix it is there any way to do that my models.py class Item(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') can_buy = models.ForeignKey(For, on_delete=models.CASCADE, related_name='for_wearing') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default='Bagh') first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) third = models.ImageField(upload_to='items', blank=False) fourth = models.ImageField(upload_to='items', blank=False) fifth = models.ImageField(upload_to='items', blank=True) rating = models.FloatField(blank=False,default='4.0') item_vedio = models.FileField(upload_to='item_vedio', blank=True) color = models.CharField(max_length=30, blank=False, default='Black') material = models.CharField(max_length=50, blank=False, default='Plastic' ) return_policy = models.CharField(max_length=100, blank=False, default='7Days Return Policy') stock = models.CharField(max_length=50, blank=False, default='In Stock') price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) about_one = models.CharField(blank=False, max_length=100, default='washable') about_two = models.CharField(blank=False,max_length=100, default='Lusturous') offer = models.CharField(max_length=4, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name my views.py class Product_detail(View): def get(self, request, item_id): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() print(item) return render (request, … -
Run a function after django server has started
I want to run a function after django server has started. Now, that function should run after all the views and URLs are initialized because the function might make requests to one of the registered routes. -
Set initial value in django model form
I want to set initial data in model form, how can i do that? I've been looking for an answer but mostly the answer is using initial or instance in view. Is there a way so we can initialize form field in model form? views.py def create_order(request, *args, **kwargs): # move this thing into model form initial_data = { 'user': request.user.username, 'products': Product.objects.get(pk=kwargs['pk']) } form = CreateOrderForm(request.POST or None, initial=initial_data) if form.is_valid(): form.save() return redirect('homepage') return render(request, "orders/create_order.html", {"form": form}) forms.py class CreateOrderForm(forms.ModelForm): # How to initialize value in this model form? class Meta: model = Order fields = ['user', 'products', 'quantity', 'address', 'total_price'] widgets = { # Make user fields disabled 'user': forms.TextInput(attrs={'disabled': True}), } Thank you.