Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Direct assignment to the forward side of a many-to-many set is prohibited. Use fieldname.set() instead
Custom User Model from django.db import models # from roles_tasks.models import mst_org_roles # from organizations.models import config_orgs # from projects.models import mst_projects from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class UserManager(BaseUserManager): def create_user(self,email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None, is_admin=False, is_staff=False): if not email: raise ValueError("email id is required") if not password: raise ValueError("password must required") if not first_name: raise ValueError("first_name is required") if not last_name: raise ValueError("last_name is required") if not role_id: raise ValueError("role_id is required") if not org_id: raise ValueError("org_id is required") if not status: raise ValueError("status is required") if not created_by: raise ValueError("created_by is required") if not modified_by: raise ValueError("modified_by is required") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name=first_name user_obj.last_name=last_name user_obj.role_id=role_id user_obj.org_id=org_id user_obj.project_id=project_id user_obj.status=status user_obj.created_by=created_by user_obj.modified_by=modified_by user_obj.admin=is_admin user_obj.staff=is_staff user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=False, is_staff=True ) return user def create_superuser(self,email,first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, project_id, status, created_by, modified_by, password=password, is_admin=True, is_staff=True ) return user Status = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ('Deleted', 'Deleted') ] class User(AbstractBaseUser): username = None last_login = None email=models.EmailField(max_length=255,unique=True) admin=models.BooleanField(default=False) staff=models.BooleanField(default=False) first_name=models.CharField(max_length=200) last_name=models.CharField(max_length=200) role_id = models.ForeignKey('roles_tasks.mst_org_roles', … -
Half Hours choice fields for TimeField in Django model
I want to have field choice in form that user can pick hours with half hours choice. I have this model and this TimeField: class Sample: start_time = models.TimeField(choices=global_vars.TIME_MAP_HALF_HOURS_CHOICES,) I want to show half hours time to customer. This is my Choices: TIME_MAP_HALF_HOURS_CHOICES = ( (datetime.time(00, 00, 00), '00:00'), (datetime.time(00, 30, 00), '00:30'), (datetime.time(1, 00, 00), '01:00'), (datetime.time(1, 30, 00), '01:30'), (datetime.time(2, 00, 00), '02:00'), (datetime.time(2, 30, 00), '02:30'), (datetime.time(3, 00, 00), '03:00'), (datetime.time(3, 30, 00), '03:30'), (datetime.time(4, 00, 00), '04:00'), (datetime.time(4, 30, 00), '04:30'), (datetime.time(5, 00, 00), '05:00'), (datetime.time(5, 30, 00), '05:30'), (datetime.time(6, 00, 00), '06:00'), (datetime.time(6, 30, 00), '06:30'), (datetime.time(7, 00, 00), '07:00'), (datetime.time(7, 30, 00), '07:30'), (datetime.time(8, 00, 00), '08:00'), (datetime.time(8, 30, 00), '08:30'), (datetime.time(9, 00, 00), '09:00'), (datetime.time(9, 30, 00), '09:30'), (datetime.time(10, 00, 00), '10:00'), (datetime.time(10, 30, 00), '10:30'), (datetime.time(11, 00, 00), '11:00'), (datetime.time(11, 30, 00), '11:30'), (datetime.time(12, 00, 00), '12:00'), ) But When I want to save object, the form not validate and raise error: Choose a valid option. How can I fix this error? -
get() returned more than one Post : return 2
i was trying to make like button for my django blog but i'm getting error while hitting like the error is get() returned more than one Post -- it returned 2! here is my code views.py class PostLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404(Post) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): obj.likes.add(user) return url_ models.py class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True,related_name='post_likes') content = models.TextField() img = models.ImageField(upload_to='pics',blank=True) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('LoveTravel-Details', kwargs={'pk': self.pk}) urls.py path('blog/<int:pk>/like/', PostLikeRedirect.as_view(),name='Like'), -
Python Django Model Commit behaviour?
My model class is Document as below. I want to update all status to 'Superseded' for every new or update record based 'DocumentNo' field to database. I succeeded to achieve this goal, But Please explain me if any error occurred on save will commit to database or not ? will these save method behave like database transaction ? class Document(models.Model): DocumentNo = models.CharField(max_length=100) Rev = models.CharField(max_length=10) Description = models.TextField(max_length=500) Area = models.CharField(max_length=100,blank=True,null=True) ReceivedDate = models.DateField() Status = models.CharField(max_length=20,choices=[('Current','Current'),('Superseded','Superseded')],default='Current') class Meta: constraints=[ models.UniqueConstraint(fields=['DocumentNo', 'Rev'], name='unique_document'), ] indexes=[ models.Index(fields=['Area','Status']) ] ordering=[ 'DocumentNo', 'Rev' ] def __str__(self): return self.DocumentNo + ' (' + self.Rev +')-Status: ' + self.Status def save(self, *args, **kwargs): existing_documents=Document.objects.all().filter(DocumentNo=self.DocumentNo) for doc in existing_documents: doc.Status='Superseded' doc.saveIndividual() super().save(*args, **kwargs) def saveIndividual(self, *args, **kwargs): super().save(*args, **kwargs) ``` -
django all fields not appearing in admin form
I have following model in django: class ProjectScheme(models.Model): name = models.CharField(max_length=250, blank=False,null=False) parent_scheme_id = models.ForeignKey(ProjectSchemeMaster, on_delete = models.CASCADE) rule = models.TextField(blank=True) created_on = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.IntegerField(blank=True,null=True) updated_on = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.IntegerField(blank=True,null=True) def __str__(self): return str(self.name) And in admin.py # Register your models here. class ProjectSchemeAdmin(admin.ModelAdmin): exclude = ('id',) class Meta: model = ProjectScheme admin.site.register(ProjectScheme, ProjectSchemeAdmin) But date fields: updated_on, created_on don't show up on admin form. I also tried without ProjectSchemeAdmin class, and also: class ProjectSchemeAdmin(admin.ModelAdmin): pass But the same. I need to get all the fields in admin form. -
create log file in specific directory django
in my server's root directory i have lrwxrwxrwx 1 root root 7 Jul 11 2018 bin -> usr/bin dr-xr-xr-x. 6 root root 4096 Apr 17 02:41 boot drwxr-xr-x. 2 root root 87 Dec 19 08:15 bundle drwxr-xr-x 16 root root 2680 May 4 05:00 dev drwxr-xr-x. 134 root root 8192 May 4 05:00 etc drwxr-xr-x. 10 root root 4096 May 1 08:20 home lrwxrwxrwx 1 root root 7 Jul 11 2018 lib -> usr/lib lrwxrwxrwx 1 root root 9 Jul 11 2018 lib64 -> usr/lib64 drwxr-xr-x. 2 root root 6 Apr 11 2018 media drwxr-xr-x. 2 root root 6 Apr 11 2018 mnt drwxr-xr-x. 3 root root 25 Apr 11 2018 opt dr-xr-xr-x 150 root root 0 May 4 05:00 proc dr-xr-x---. 10 root root 4096 May 4 10:01 root drwxr-xr-x 42 root root 1340 May 4 05:00 run lrwxrwxrwx 1 root root 8 Jul 11 2018 sbin -> usr/sbin drwxr-xr-x. 2 root root 6 Apr 11 2018 srv dr-xr-xr-x 13 root root 0 May 4 08:56 sys drwxrwxrwt. 12 root root 98304 May 4 09:58 tmp <-- i want to create logs inside this directory drwxr-xr-x. 13 root root 155 Jul 11 2018 usr <-- my file is located … -
Django without any Default Migration setting
I am going to build a simple API without auth and admin application. Is there anyway to exclude the all the build-in table? I tried to annotate all the default setting however I can't run the server. # 'django.contrib.admin', # 'django.contrib.auth', # 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.messages', # 'django.contrib.staticfiles', -
Could not retrieve AJAX request data value in Django view function
I have an AJAX request to pull some data from post model"I am using Django3 and python 3.8". When I print the request.GET.get to the console, I got "None". There was no Data. However, when I alert the passed data in javascript I got the right value. I could not figure out which portion of my code should be tweak a little bit to work. Here is the AJAX call: <script type="text/javascript"> // to submit the get request and prevent the default submission $(document).on('click', '#post-det', function(e) { e.preventDefault(); var post_id = $(this).children(':first-child').text(); var post_id = parseInt(post_id); alert(post_id); $.ajax({ 'type':'GET', 'url': "{% url 'get_post_details' %}", 'data':post_id, 'processData': false, 'cache':false, 'contentType': false, 'dataType': 'json', csrfmiddlewaretoken:'{{ csrf_token }}', success: function(data) { alert(data) }, }); }); </script> I got "2" for the post_ID However, I could not retrieve it in Django view function. Here is the view function: def post_details(request): if request.method == 'GET' and request.is_ajax: post_id = request.GET.get('data') print("this is to check if the post_id is passed", post_id) print(request.GET.get) data = GetPostDetails(post_id) data = json.dumps(str(data)) return JsonResponse(data, safe=False) return JsonResponse({"error": "there was an error"}, status=status.HTTP_400_BAD_REQUEST) The print function print this line. this is to check if the post_id is passed None <bound method … -
Cannot create links to some allauth files which I changed
I customized the 'allauth' password_reset and password_change files and my file structure looks like: Templates _account ____login ____logout ____password_reset ____password_change The problem is I cannot create links to those two files (but I can create links to the other files in the same folder. For example: <a href="{% url 'account_login' %}">Login</a> works, but <a href="{% url 'account_password_reset' %}">Reset Password</a> doesn't. The error I get is: NoReverseMatch at /accounts/login/ Reverse for 'account_password_reset' not found. 'account_password_reset' is not a valid view function or pattern name. I've tried a lot of things but just can't figure it out. Any help would be greatly appreciated. Thank you. -
Django/JavaScript button click shows value - reload page removes value
I'm creating a game in Django more specifically in oTree with a Django Template Language and JavaScript frontend. When I click a button a value needs to be shown (got that covered) this is done with some JavaScript. But when I refresh/reload the page I need that value to still be displayed and not click the button all over. Does anybody know if there is a workaround for this in either Django or JavaScript? -
How to stop django from generating empty csv file
with open(file_name, 'w') as output_file: data = campaign_dict try: writer = csv.DictWriter(output_file, data[0].keys()) writer.writeheader() writer.writerows(data) except: pass with open(file_name, 'r') as myfile: response = HttpResponse(myfile, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+file_name return response Above code was used to generate and download csv file in django.But also django generate empty file and download .I want to stop file from downloading if file is empty.. -
ModelForm in Django not saving anything
I am making a twitter clone app in Django. I have a model, and a modelform as so: Class Tweet(models.Model): content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) class TweetForm(forms.ModelForm): class Meta: model = Tweet fields = ['content',] def clean_content(self): content = self.cleaned_data.get('content') if len(content) > MAX_TWEET_LENGTH: raise forms.ValidationError('This tweet is too long') I have a view for this: def tweet_create_view(request, *args, **kwargs): if request.method == 'POST': form = TweetForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() form = TweetForm() context = { 'form': form } return render(request, 'components/form.html', context) and the template: <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary" type="submit">Save</button> </form> When I submit the form data, in the database the value is shown as NULL, even if I pass in some text. What am I doing wrong?? -
Get some infomation from crawler service by scrapy
I have a crawler service that crawl some website on google , now i want to write scipt that take a domain from that crawler service, can i do that and how , tks you , can i use the python requests to get the url of scrapy service and get that domain data import requests r = requests.get("scrapy url") Can i use example like this , tks you -
'EACCES' error for django dumpdata on heroku
I want to copy the database from heroku to import into my local development environment. In the past I've done this with: heroku run python manage.py dumpdata -- > data.json However when I run this command now I get the following message: Running python manage.py dumpdata on [[projectname]]... up, run.5450 (Free) internal/fs/utils.js:230 throw err; ^ Error: EACCES: permission denied, write at writeSync (fs.js:599:3) at SyncWriteStream._write (internal/fs/sync_write_stream.js:24:3) at doWrite (_stream_writable.js:442:12) at writeOrBuffer (_stream_writable.js:426:5) at SyncWriteStream.Writable.write (_stream_writable.js:317:11) at Dyno.ondata (_stream_readable.js:695:22) at Dyno.emit (events.js:310:20) at addChunk (_stream_readable.js:286:12) at readableAddChunk (_stream_readable.js:268:9) at Dyno.Readable.push (_stream_readable.js:209:10) { errno: -13, syscall: 'write', code: 'EACCES' } From looking around it seems that this error has to do with a not properly logged in heroku CLI. However, I am logged in and can run other commands such as heroku run python manage.py shell etc. Anybody have a clue what's going wrong? -
Override POST in CreateAPIView
In my django app I have two models i.e. Package and Address Models.py class Package(models.Model): sender_name = models.CharField(max_length=255, default=0) sender_company = models.CharField(max_length=255, blank=True, null=True) sender_phone = models.CharField(max_length=255, default=0) sender_city = models.CharField(max_length=255, default=0) sender_state = models.CharField(max_length=255, default=0) sender_country = models.CharField(max_length=255, default='India') ... class Address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, default=0) city = models.CharField(max_length=255, default=0) state = models.CharField(max_length=255, default=0) country = models.CharField(max_length=255, default='India') I am overriding the post method in my CreateAPIView like the following: class package(APIView): permission_classes = (permissions.IsAuthenticated,) def post (self, request, format=None): ... if serializer.is_valid(): serializer.save() print("s data", serializer.data) Address.objects.create(user=request.user.id, name=request.data["name"], city = request.data["city"]...) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Is there any other way to save Address from package model when a Package object is created ?? -
Python MongoDB ReferenceError: weakly-referenced object no longer exists
I am an error ReferenceError: weakly-referenced object no longer exists in my code, I have tried to debug it that I don't know why am I getting this. I am using mongodb and python 3.6.10 here is my code, please help a = 't1' b = ['v1', 'v2', 'v3'] services = dict() for value in b: record = MyModel.objects.filter(myid=id, a=a, value=value).first() keys = record['services'].keys() for key in keys: key_value = record['services'][key] if key in services: services[key].extend(key_value) # Getiing error here in this line else: services.update({key: key_value}) print(services) MyModel looks like { "myid" : "1", "a" : "t1", "b" : "v1", "services" : { "service_1" : [ { "serviceid" : "1012", "service_type" : "service_1" } ] } { "myid" : "1", "a" : "t1", "b" : "v2", "services" : { "service_2" : [ { "serviceid" : "1013", "service_type" : "service_2" } ] } code works fine if there is only one value in b, but if code iterate the second time and tries to perform services[key].extend(key_value), code generates the error. -
How to build a django model to store twitter conversations?
I'm building a tool, that gets user timeline tweets and their responses and I need to find out how to store those conversations in a database to render them afterwards in a template. To get a conversation, I use a while loop, that gets 'in_reply_to_status_id' of a tweet, then retrieves the status object of this reply by the id, finds its 'in_reply_to_status_id' etc till the whole conversation gets retrieved. This is the code I use: conversation = [] while True: response = api.get_status(id=tweet_id, tweet_mode='extended')._json if response['in_reply_to_status_id'] == None: break else: message_dict = {} message_dict['author'] = response['user']['screen_name'] message_dict['text'] = response['full_text'] message_dict['created_at'] = response['created_at'] message_dict['author_profile_url'] = response['user']['profile_image_url'] conversation.append(message_dict) tweet_id = response['in_reply_to_status_id'] if len(conversation) == 0: return None return reversed(conversation) In my models.py I have a Tweet model and I need to find out how to make a model that stores the whole conversation/dialogue/thread retrieved by the script above. Also, it should be possible to render the conversation as a simple chat dialogue afterward. My first thought was to add "replies" field to my Tweet model and store the conversation as a JSON but this doesn't look like the right solution to me. -
How to use ManytoMany relationship in django custom user model?
My Custom User Model from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class UserManager(BaseUserManager): def create_user(self,email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None, is_admin=False, is_staff=False): if not email: raise ValueError("email id is required") if not password: raise ValueError("password must required") if not first_name: raise ValueError("first_name is required") if not last_name: raise ValueError("last_name is required") if not role_id: raise ValueError("role_id is required") if not org_id: raise ValueError("org_id is required") if not status: raise ValueError("status is required") if not created_by: raise ValueError("created_by is required") if not modified_by: raise ValueError("modified_by is required") user_obj=self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.first_name=first_name user_obj.last_name=last_name user_obj.role_id=role_id user_obj.org_id=org_id user_obj.status=status user_obj.created_by=created_by user_obj.modified_by=modified_by user_obj.admin=is_admin user_obj.staff=is_staff user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=password, is_admin=False, is_staff=True ) return user def create_superuser(self,email,first_name, last_name, role_id, org_id, status, created_by, modified_by, password=None): user=self.create_user( email, first_name, last_name, role_id, org_id, status, created_by, modified_by, password=password, is_admin=True, is_staff=True ) return user Status = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ('Deleted', 'Deleted') ] class User(AbstractBaseUser): username = None last_login = None email=models.EmailField(max_length=255,unique=True) admin=models.BooleanField(default=False) staff=models.BooleanField(default=False) first_name=models.CharField(max_length=200) last_name=models.CharField(max_length=200) role_id = models.ForeignKey('roles_tasks.mst_org_roles', on_delete=models.DO_NOTHING) org_id = models.ForeignKey('organizations.config_orgs', on_delete=models.DO_NOTHING) project_id = models.ManyToManyField('projects.mst_projects', blank=True) status = models.CharField(choices = Status, default = 'Active', max_length = 15) … -
So, im doing the updation in my django project and i'm getting a error for reverse match
THE ERROR IS-- NoReverseMatch at /updatemedicine/2 Reverse for 'updatemedicine' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['updatemedicine/(?P<pk1>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/updatemedicine/2 Django Version: 2.2.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'updatemedicine' with keyword arguments '{'pk1': ''}' not found. 1 pattern(s) tried: ['updatemedicine/(?P<pk1>[0-9]+)$'] Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.4 Python Path: ['D:\\django project\\admin4', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\lenovo\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\Pythonwin'] MY HTML CODE IS === {% extends 'Pharmacetical/homepage.html' %} {% block content %} <div class="box box-warning"> <div class="box-header with-border"> <h3 class="box-title">Add Medicines Here</h3> </div> <!-- /.box-header --> <div class="box-body"> <form role="form" method="POST" action="{% url 'updatemedicine' pk1=med.pk1 %}" enctype="multipart/form-data"> <!-- text input --> {% csrf_token %} <div class="form-group"> <label>Disease Name</label> <select class="form-control" name="desigid"> {% for i in d %} <option value="{{ med.dsg_id }}">{{ i.diseas }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Medicine Name</label> <textarea class="form-control" rows="3" name="medname" id="" value="{{ med.medicine }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Uses</label> <textarea class="form-control" rows="3" name="uses" id="" value="{{ med.uses }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Side Effects</label> <textarea class="form-control" rows="3" name="effects" id="" value="{{ med.sideeffects }}" placeholder="Enter ..."></textarea> </div> <div class="form-group"> <label>Precautions</label> <textarea class="form-control" rows="3" name="precaution" id="" value="{{ med.precautions }}" placeholder="Enter ..."></textarea> … -
I've tried to set my default python version as python3 but is still coming up with python 2.7
I'm trying to install Django on my mac (2013) and i have set my default python version to python3 but when i try install django i get an a warning saying python 2.7 has reached the end of it's life. Then it says that i can only install django versions 1.x.y DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable ERROR: Could not find a version that satisfies the requirement django==2.0.7 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, … -
How to sort key:value output with structlog?
I use structlog with Django and noticed that key:value output is alphabetical, which means that when I bind a new key beginning with _ like log.bind('_id'=id) then it is added at the very first. The documentation mentions a processor boolean parameter sort_keys but it doesn't seems to have an effect. How can I sort key:value based on time they are binded? This is my config: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(sort_keys=False), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(pad_event=43, colors=True, force_colors=True ), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer( key_order=['timestamp', 'level', 'logger', 'event'], sort_keys=False ), }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "json.log", "formatter": "json_formatter", }, "flat_line_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "flat_line.log", "formatter": "key_value", }, }, "loggers": { '': { "handlers": ["console", "flat_line_file", "json_file"], "level": "WARNING", 'propagate': False, }, 'app1': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", 'propagate': False, }, 'app2': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", 'propagate': False, }, 'app3': { "handlers": ["console", "flat_line_file", "json_file"], "level": "INFO", 'propagate': False, } } } structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.processors.TimeStamper(fmt="%Y-%m-%d %H:%M:%S.%f"), # (fmt="iso"), structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], context_class=structlog.threadlocal.wrap_dict(dict), logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, … -
model linked with model through M2O relation which is further linked with model through M2O relation raises error
I am working on an online-shop in django. I have linked the order model with the cart model through ForeignKey which is further linked with products model through ForeignKey. models.py: class products(models.Model): image = models.ImageField(upload_to='products/') name = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) title = models.CharField(max_length=50) price = models.FloatField() def __str__(self): return self.name class cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(products, on_delete=models.CASCADE) ### slug = models.CharField(max_length=50, default='#') quantity = models.IntegerField(default=1) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.item.name}' def get_total(self): total = self.item.price * self.quantity floattotal = float("{0:.2f}".format(total)) return floattotal class order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(cart, on_delete=models.CASCADE) ### slug = models.SlugField() quantity = models.IntegerField() created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.item.item__name}' I wanted to create object of order as: def order_view(request, slug): cart_qs = cart.objects.filter(user=request.user, slug=slug) cart_item = cart_qs[0] order.objects.create(user=request.user, item=cart_item.item.name, slug=slug, quantity=cart_item.quantity) #### It raises error as: Cannot assign "'The latest one'": "order.item" must be a "cart" instance. Why this error arises and how can I resolve this? -
Django, how to set inline formset factory with two ForeingKey?
I have create a code that works perfectly except for one little problem. I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice commesse and lavorazione fields and subsequently in the inline formset the other fields. In other word: How can I set two ForeignKey in a inline formset factory? -
Convert String of List to List in Python
I need to convert a string of list to List in Python ..... I have seen many of the similar questiions but none of them are works in this case ..... I am passing some values through PostMan ..... The key passing as a form data Key = controls value = [CR1,CR2] I am fetching the data like this c_list = self._kwargs['data'].get('controls', []) print(c-list) print(type(c-list)) I am getting the following o/p [CC-2,CC-3] <class 'str'> But I need to get it as a list so I have tried the following method import ast c_list = self._kwargs['data'].get('controls', []) res = ast.literal_eval(c_list) But I am getting the following Error malformed node or string: <_ast.Name object at 0x7f82966942b0> -
How to make calculationa dn assign condition in ManytoMany models in Django
Guys i am new in Django and explore its docs and youtube. But i can't find answer to my specific questions as i am sure i am making an error in my code. models.py class Profiles(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) class Meta: db_table='profiles' class Year20(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='year20' class Year19(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) math=models.DecimalField(decimal_places=2,max_digits=1000) english=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='year19' class Faculty(models.Model): name=models.CharField(max_length=200) profiless=models.ManyToManyField(Profiles) acting=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='faculty' i have 2 questions: Wheather i am doing right assiging ManytoMany model in such way? Profiles model relates to all tables as it contains their name and surname. How to filter values from multiple tables , conduct calculation and assign condition? I assigned ManytoMany model to each table in hope be able to make calculations using variables form different tables. I do not want you think i ask without researching and trying. What i could do is filtering and calculation just from 1 table. score_merit=Year19.objects.annotate( final_grade=F('math') / F('english')).filter(final_grade__gt=61,) However i want to get final score which is : ath_avrg=(year19.math+year20.math)/2 eng_avrg=(year19.eng+year20.eng)/2 final_score=(math_avrg+eng_avrg+acting)/3 and finally print name and surname of student where final_score > 70 I want to learn how to combine values from diferent tables and make calculations and finally filter based on conditions …