Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get count of objects from ManyToManyField in Django Rest Framework
I have a User and Event model, class User(AbstractUser): bio = models.CharField(max_length=255, blank=False, default='') class Event(models.Model): name = models.CharField(max_length=50) user = models.ManyToManyField("User", related_name='event_player') I wand get the number of Users registered in events, I tried Try 1 class EventSerializer(serializers.ModelSerializer): players_count = serializers.IntegerField( source='user_set.count', read_only=True ) class Meta: model = Event fields = ('id', 'name','players_count') Try 2 class EventSerializer(serializers.ModelSerializer): players_count = serializers.SerializerMethodField() class Meta: model = Event fields = ('id', 'name','players_count') def get_players_count(self, obj): return obj.user_set.all().count() Try 3 class EventSerializer(serializers.ModelSerializer): def to_representation(self, instance): return {'id': instance.pk, 'players_count': instance.user__count} class Meta: model = Event fields = ('id', 'name','players_count') But none of them make a sense, How do I get the total count of nested ManyToMany Users. I'm new to DRF please help me to solve this. Any help is appreciated, Thanks. -
I need to update image for specific user Django
I need to update image for specific user Django . Now if I updating the image for specific user , image updates for all users . Is there any solutions ? Here is my code : models.py class UserWithImage(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True) def __str__(self): return self.user.username views.py if 'imagechange' in request.POST and request.FILES['image']: image = request.FILES['image'] fs = FileSystemStorage() image_fs = fs.save(image.name, image) image_new = UserWithImage.objects.update(image=image_fs) html page <form id='myform' enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" class="settings__background__file" name="image" enctype="multipart/form-data" id="backgroundimage" placeholder="Upload image"> <button id="submit-image" name="imagechange" type="submit"> Upload Image </button> </form> -
Streaming Django template with large generator in context
I want to render large log files in a Django template. To do so, the template renders individual lines provided by a generator that streams the log file from disk. The template rendering just stops after some time though and I'm not sure where I've gone wrong. My Django app is running with gunicorn & nginx (config below). I can see that the relevant response headers are set, so I don't know why the logs stop rendering ~30-40 seconds in: HTTP/1.1 200 OK Server: nginx/1.17.4 Date: Wed, 12 Feb 2020 12:53:43 GMT Content-Type: text/html; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive X-Frame-Options: SAMEORIGIN Relevant part of the template: <div class="log-body"> {% for line in log %} {{ line }} {% endfor %} </div> The rendering function in views.py def render_log(request): log = read_log_file_gen("some_path.log") if not log: log = ["No logs found"] template = loader.get_template('show_log.html') context = { 'log': log, } return StreamingHttpResponse(template.render(context, request)) def read_log_file_gen(path): _256KB = 256 * 1024 try: with open(path) as f: while True: lines = f.readlines(_256KB) if not lines: break yield "".join(lines) except IOError: return None The app runs through docker-compose: version: '3' services: web: build: ./app command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 -k gevent volumes: - static_volume:/usr/src/app/static - … -
How to send captured webcam image and save to server via input field
I was working on a project where a user can change his profile pic by using his webcam. I successfully capture the image by webcam but I cannot append that capture image to my form here is my HTML code <div class="form-group"> <label for="exampleInputFile">Profile Picture</label> <div class="input-group"> <div class="custom-file"> <input type="file" id="photo" class="custom-file-input" name = "profile_pic" accept="image/png,image/jpg,image/jpeg"> <label class="custom-file-label" for="exampleInputFile">Choose Image</label> </div> </div> </div> <div class="camera"> <video id="video">Video stream not available.</video> <button type="button" id="startbutton" class="btn btn-success" data-toggle="modal" data- target="#modal-success">Take photo</button> </div> Here is my js code I follow this tutorial for help <script> (function() { // The width and height of the captured photo. We will set the // width to the value defined here, but the height will be // calculated based on the aspect ratio of the input stream. var width = 770; // We will scale the photo width to this var height = 900; // This will be computed based on the input stream // |streaming| indicates whether or not we're currently streaming // video from the camera. Obviously, we start at false. var streaming = false; // The various HTML elements we need to configure or control. These // will be set by the startup() … -
want to add submit button in my javascript
I want to add submit button in my javascript but I am not able to add this how to do this in code?I want to send this file to s3 using submit button.but when I am trying to add submit button it doesnt work can anyone provide code for adding submit button in my javascript. I want to add submit button in my javascript but I am not able to add this how to do this in code?I want to send this file to s3 using submit button.but when I am trying to add submit button it doesnt work can anyone provide code for adding submit button in my javascript <script type="text/javascript"> $(document).ready(function(){ $("#genBtnID").on("click",function(){ var condition = $("#conditionID").val(); var replicates = $("#replicatesID").val(); var single_pair = $("input[name=single_pair]:checked").val(); var condition_array = []; $(".condition_class").each(function(){ condition_array.push($(this).val()); }); var condition_counter = 0; if(condition == "" || replicates == ""){ alert("Either condition or replicates value is missing. Enter both values"); }else{ var totalRecords = parseInt(condition) * parseInt(replicates); if(single_pair == "Single"){ var tableTag = "<table border='1' style='border-collapse: collapse;'>" +"<thead><tr><th>Condition</th><th>Read 1</th></tr></thead><tbody>"; for(var i = 0;i < totalRecords;i++){ if(i % replicates == 0){ tableTag +="<tr><td rowspan='"+replicates+"'>"+condition_array[condition_counter]+"</td><td><form name="myform" input type='file'></td></tr>"; condition_counter++; }else{ tableTag +="<tr><td><form name="myform" input type='file'></td></tr>"; } } tableTag … -
problem in rendering data from django models to chart.js using Django
i'm new on django. I want to show group by data on chart.js bar graph. i'm trying through .annotate in views.py but didn't got a relevant solution. I'm using PostgreSQL. Here is my table trendmania_sentiments Now i want to get a count of group by data from sentiments_analysis column. Firstly I write SQL query for group by data. select sentiments_analysis, count(sentiments_analysis) from public.trendmania_sentiments group by sentiments_analysis output: then i write equivalent Django query in views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"] = Sentiments.objects.values('sentiments_analysis').annotate(cn=Count('sentiments_analysis')) print(context) return context models.py class Sentiments(models.Model): user_id = models.PositiveIntegerField(default=0,null=True) video_id = models.PositiveIntegerField(default=0, null=True) sentiments_analysis = models.PositiveIntegerField(default=0, null=True) html file <script> $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Negative', 'Positive'], datasets: [{ label: 'Sentiment Analysis', data: [{% for item in qs %}{{ item.sentiments_analysis }},{% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: … -
Django: loading images from URLs (not static files)
I'm trying to load a page in Django with data from an API that include image URLs. I am loading the API data into my modules (example: News module which has a banner_url attribute). In my HTML template, I am loading the banner into an img tag: <img src={{ news.banner_url }}> Obviously this won't work, but I haven't been able to find a solution on the internet. My news module looks like this: class News(models.Model): banner_url = models.URLField(null=True) #null is true for the initialization before a URL is fetched. I tried also using many other fields like CharField and ImageField but to no avail in any way.Any help is appreciated! -
How to send django formset data with ajax and update/create appropriately
I utilised django-extra-views to create a modal which displays a formset. With dynamic-formset-views I've added the functionality to add and remove forms from the formset dynamically. On opening of the modal we follow a many-to-one relationship and get all employees of a certain desk. For each employee instance we create a form. I'm currently trying to send the changes to existing employee and newly added employees with ajax to an api rather than using a django view so I can display potential errors, which come back from the server, in the modal without page reload. Problem: How to serialize the formset data? Is $(form).serialize() appropriate here or do I need to create a a JSON object? How do I distinguish between existing employee which the user modified and new employees which the user added? Do I need to serialize them separately and do a ajax PATCH for the first and an ajax PUT for the second group? Or do I need to configure this behaviour in the api? views.py class DeskEditEmployeesView(AjaxTemplateMixin, ModelFormSetView): model = db_models.DeskEmployeeMap ajax_template_name = 'my_modal.html' form_class = forms.DeskEmployeeMapForm success_url = reverse_lazy('finance:tc_desk') slug_field = 'desk' factory_kwargs = {'extra': 0, 'can_delete': True} api_url = 'api_desk_employee_map-list' template [...] <script language="JavaScript"> … -
Get count as a separate result attribute Django
I need my code to return count for a specific cam id that is active and i want it to return only once and separately. But it is occurring with every single record. My code is as below for model class: def activeness(self): result = MinuteRecords.objects.filter( cam_id=self.cam_id, face_status='Active', ).count() return result For my serializer: class MinuteRecordsSerializer(serializers.ModelSerializer): timeago = serializers.DateTimeField(read_only=True) activeness = serializers.IntegerField(read_only=True) class Meta: model = MinuteRecords fields = '__all__' read_only_fields = ('timeago',) The result that i get is [ { "id": 1, "timeago": "5 days, 21 hours", "activeness": 2, "cam_id": 1, "timestamp": "2020-02-06T14:55:26.852392Z", "face_status": "Active" }, { "id": 6, "timeago": "1 week", "activeness": 2, "cam_id": 1, "timestamp": "2020-02-04T15:17:34.590323Z", "face_status": "Active" } ] The result that i expect is : [ { "id": 1, "timeago": "5 days, 21 hours", "cam_id": 1, "timestamp": "2020-02-06T14:55:26.852392Z", "face_status": "Active" }, { "id": 6, "timeago": "1 week", "cam_id": 1, "timestamp": "2020-02-04T15:17:34.590323Z", "face_status": "Active" }, "activeness": 2, ] The crux being that i want to return the total number of records after my query as a separate record rather than being appended with every result. -
ValidationError: ["'02/12/2020' value has an invalid date format. It must be in YYYY-MM-DD format."]
i have a form that takes in a date and class_id. when the user posts the data i want to use the date to query my models for any instance with the same date.. but i end up getting this error code ValidationError: ["'02/12/2020' value has an invalid date format. It must be in YYYY-MM-DD format."] this is my views.py: if request.method == 'POST': class_name = get_object_or_404(ClassRoom, pk=request.POST['class_name']) # class name attendance_date = request.POST['date_field'] # date # get the students in the class which is current active # check if the student is current active students_attendance = StudentAttendance.objects.filter(attendance_date=attendance_date) and my models.py implementation is: class StudentAttendance(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_attendance') attendance_date = models.DateField() status = models.ForeignKey(AttendanceStatus, on_delete=models.PROTECT) notes = models.CharField(max_length=150, blank=True) private_notes = models.CharField(max_length=500, blank=True) #signed_by = models.ForeignKey(Teacher, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (("student", "attendance_date", 'status'),) ordering = ('-attendance_date', 'student',) any suggestion on how to solve this bug... NB: 1. i changed my settings.py to localize the time like this from django.conf.locale.en import formats as en_formart en_formart.DATE_FORMAT = ('%d %m %y', ) en_formart.DATE_INPUT_FORMATS = ('%m/%d/%Y', '%Y-%m-%d', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B … -
IntegrityError NOT NULL constraint failed in Django
I have two models, Question and Answer. I am getting this error when I try to add an answer from user side. (adding from admin panel is okay). I have gone through few solutions in stackoverflow and other site. I everytime I deleted existing database and ran migrations, but nothing worked. Here is my code: models.py from django.conf import settings from django.db import models from django.utils import timezone class Question(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=300) optional_description = models.TextField(blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Answer(models.Model): question = models.ForeignKey('ask.Question', on_delete=models.CASCADE, related_name='answers') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_answer = models.BooleanField(default=False) def approve(self): self.approved_answer = True self.save() def __str__(self): return self.text relevant section from views.py def add_answer_to_que(request, pk): que = get_object_or_404(Question, pk=pk) if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.que = que answer.save() return redirect('ques_detail', pk=que.pk) else: form = AnswerForm() return render(request, 'ask/add_answer_to_que.html', {'form': form}) forms.py class AnswerForm(forms.ModelForm): class Meta: model = Answer fields = ('author', 'text',) Clicking writing an answer button leads to This page But after adding something and clicking send leads to this error. -
how can i automatically fill my created_by input with my login username in django admin
''' Process_Entity_ID=models.CharField(max_length=25, unique=False, primary_key=True) Short_Description=models.CharField(max_length=25) Full_Description=models.CharField(max_length=65) Superior_entity_ID=models.CharField(max_length=20) Job_Description=models.CharField(max_length=4000) Entity_Level=models.CharField(max_length=20, choices=ENTITY_CHOICES, default=MANAGEMENT,) Created_By=models.ForeignKey(User, on_delete=models.CASCADE, related_name='create_ent', blank=True) Modified_By=models.ForeignKey(User, on_delete=models.CASCADE, related_name='modify_ent', blank=True) ''' this give a dropdown to select users in django admin form but what i went is for the created_by field to automatically be populated by the login username -
Override default L10N formatting of a date in all edit forms?
In an update view, a DateField in a model form on my site shows an existing date as (say) 2020-01-25. My locale is set to en-GB.utf8. Is there any way to override the defaults arising from USE_I10N globally, in this context only? I would like to get existing dates, in edit form fields only, displayed as 'dd/mm/yy' if I can. Users will otherwise complain that I am forcing them to type in dates in an alien format. I do have DATE_INPUT_FORMATS set to accept %d/%m/%y and it works, but the visual cue is that it won't be accepted (and also they'll have to erase the initial value). I tracked down the DateTimeInput widget documentation and it says format The format in which this field’s initial value will be displayed. If no format argument is provided, the default format is the first format found in DATE_INPUT_FORMATS and respects format localization. "respects format localization" is the problem, meaning it ignores DATE_INPUT_FORMATS. explicitly passing format would solve the problem, except I don't know how to cause this widget setting to become the default for all DateFields in all model forms automatically generated from model and fields in UpdateView for example. Fixing all the … -
wsgi:error but not detailed error log by apache
I have this error wsgi.py on apache , however there is not details. [Wed Feb 12 20:25:17.320785 2020] [wsgi:error] [pid 4980] [client 172.17.1.**:27264] Using TensorFlow backend. [Wed Feb 12 20:26:00.367810 2020] [wsgi:error] [pid 4983] [client 172.17.1.**:27302] Using TensorFlow backend. [Wed Feb 12 20:29:39.482686 2020] [wsgi:error] [pid 5010] [client 172.17.1.**:27394] Using TensorFlow backend. The wsgi module is successfully installed. $ pachectl -M | grep wsgi wsgi_module (shared) This is my wsgi setting for apache. I have no clue to start. Could you help me?? <VirtualHost *:80> ServerAdmin webmaster@dummy-host.example.com ServerName example.server.com DocumentRoot "/var/www/html/myapp/current/" <Directory /var/www/html/myapp/current/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /var/www/html/myapp/current/myapp/wsgi.py WSGIDaemonProcess myenv user=ubuntu group=ubuntu python-path=/home/ubuntu/anaconda3/envs/py37/lib/python3.7/site-packages </VirtualHost> LoadModule wsgi_module /home/ubuntu/anaconda3/envs/py37/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so #WSGIScriptAlias /myapp /var/www/html/myapp/current/myapp/wsgi.py WSGIPythonHome /home/ubuntu/anaconda3/envs/myenv/ WSGIPythonPath /var/www/html/myapp/current/ <Directory /var/www/html/myapp/current> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> Alias /static/ /var/www/html/myapp/current/static/ <Directory /var/www/html/myapp/current/static> Order allow,deny Allow from all </Directory> -
How to set a dynamic field name in a objects.get() function
I want to create a mixin that allows me to change the field of a get function as follows: class MyMixin(self): myfield = 'field1' def myfunct(self): i = MyModel.objects.get(self.myfield=myvar) Such that the desired code runs MyModel.objects.get(field1=myvar). However, this approach returns SyntaxError: expression cannot contain assignment How can I set field names like this dynamically? -
i try intrgrate paypal with django and when i enter page form paypal show problem [closed]
Hello Guys i Have problem when i enter page paypal form https://i.stack.imgur.com/S7xvM.png def process_payment(request): order_id = request.session.get('order_id') orders = get_object_or_404(order, id=order_id) host = request.get_host() paypal_dict = { 'business':settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % orders.get_total_cost().quantize(Decimal('.01')), 'item_name': 'Order {}'.format(orders.id), 'invoice': str(orders.id), 'currency_code':'USD', 'notify_url': 'http://{}{}'.format(host,reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host,reverse('payment:done')), 'cancel_return': 'http://{}{}'.format(host,reverse('payment:canceled')), } form = PayPalPaymentsForm(initial=paypal_dict) context = { 'order':orders, 'form':form, } return render(request,'process.html',context) -
Migrate database values in Django
I have a db table 'UserSite' with User, Site and Group in it. A site is from a user and can put into just one group. Now I want a user to be able to add a site to multiple groups. Therefor I created a new db table UserSiteGroups to handle the many to many relation. So I need to migrate all the group keys from the old UserSite table to the new UserSiteGroups table. I want to do is by a migrations script. I already made a migration to create a new database table UserSiteGroups with user, site and group. Now I just need to copy the values. I have this migration script: from django.db import migrations def migrate_groups_data(apps, schema_editor): UserSiteGroup = apps.get_model("site", "UserSiteGroup") UserSite = apps.get_model("site", "UserSite") # UserSiteGroup.objects.all().update(group=F("groups")) for user_site in UserSite.objects.all(): usersitegroup = UserSiteGroup.Objects.filter( user_site__user=user_site.user, user_site__site=user_site.site ).first() usersitegroup.group = user_site.group usersitegroup.save() class Migration(migrations.Migration): dependencies = [("site", "0035_usersitegroup")] operations = [ migrations.RunPython(migrate_groups_data), ] but I got this error-log: psycopg2.errors.UndefinedColumn: column site_usersite.group_id does not exist LINE 1: ...s_is_muted", "site_usersite"."notes_is_muted", "site_u... ... django.db.utils.ProgrammingError: column site_usersite.group_id does not exist LINE 1: ...s_is_muted", "site_usersite"."notes_is_muted", "site_u... -
Message: stale element reference: element is not attached to the page document DJANGO PYTHON SELENIUM
I keep getting an exception for stale element when trying to locate the search bar... basically, my function will take passed in data (a playlist) and iterate through it to search each song on who sampled's website.... from there it will populate two lists, one with the "found connections" and the other list for un-found connections. I am using CHROMEDRIVER i just want it to return the two lists before i work on the algorithm to search for song name only and not the artist. since they are in the same div from a web scrape beforehand to acquire the data def whosampled_submit(request, id): if not request.user.is_authenticated: return render(request, 'login.html') else: options = webdriver.ChromeOptions() options.add_argument('--ignore-certificate-errors') options.add_argument('--ignore-ssl-errors') # options.add_argument('--headless') prefs = {"profile.default_content_setting_values.notifications" : 2} options.add_experimental_option("prefs",prefs) driver = webdriver.Chrome(chrome_options=options) #GOTTA CHANGE THIS TO FIREFOX OR EDGE # GO TO ----> https://github.com/mozilla/geckodriver/releases TO FIX BMP ISSUE user = request.user AcceptedConnections= [] exceptions= [] specific = Search.objects.get(pk = id) songs = get_list_or_404(Song, search=id) for x in songs: print(x,'\n') song = str(x) # searching for songs driver.get("https://www.whosampled.com/") search = driver.find_element_by_xpath('//*[@id="searchInput"]') search.send_keys(song) search.submit() try: top_connection = driver.find_element_by_class_name('connectionTitle').text print("\nSAMPLE FOUND") print(song) print(top_connection) AcceptedConnections.append(str(top_connection)) except NoSuchElementException: print('\nDID NOT FIND\nNO CONNECTION----->', song) exceptions.append(str(song)) pass pass driver.quit() print('ACCEPTED') pprint.pprint(AcceptedConnections) print('---------------------------------------') … -
Django: hwo to make queries between 2 tables that are not related in the model?
I have 2 models that are not related (maybe it should...) I need to make a query that select all records of my table Stock WITH related rows in Parametrage based on asp_sto_loc=asp_par_loc Something like SQL: select * from pha_asp_sto left join pha_asp_par on pha_asp_par.asp_par_loc=asp_sto_loc; How can I make such a query in Django? models.py class Stock(models.Model): asp_sto_cle = models.AutoField(primary_key=True) asp_sto_loc = models.CharField("Site concerned", max_length=10, null=True, blank=True) asp_sto_pla = models.IntegerField("Quantity of placebos available", null=True, blank=True,) asp_sto_asp = models.IntegerField("Quantity of aspirin available", null=True, blank=True) class Parametrage(models.Model): asp_par_cle = models.AutoField(primary_key=True) asp_par_loc = models.CharField("Site concerned by settings", max_length=10, null=True, blank=True) asp_par_ale = models.IntegerField("Site alert value for the site", null=True, blank=True,) asp_par_con = models.IntegerField("Site confort value for the site", null=True, blank=True,) -
Form validation in Django 2.2! Can't display any validation errors
I am working with this simple form and can't able to display inline validation in each line. I want validation as it worked in the Django admin site, with particular fields. How could it be done! It only shows the HTML validation like "Please fill out the field" models.py class MemberRegistration(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=50) def __str__(self): return self.name forms.py from django import forms from . models import MemberRegistration from django.core import validators class MemberForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder':'Name'}), max_length=100, error_messages = { 'required':"Please Enter your Name"}) email = forms.EmailField(widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder':'E-mail'}), required=True, max_length=100) phone = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder':'Phone'}), required=True, max_length=100) class Meta: model = MemberRegistration fields = "__all__" def clean_name(self): all_clean_data = super().clean() name = all_clean_data['name'] if name == "": raise forms.ValidationError("Name field is required") member_form.html: {% block body_block %} <div class="container"> <h1>This is member reg form</h1> <form method="post"> {% csrf_token %} <div class="form-group"> <label for="">Name</label> {{ form.error.name }} {{form.name}} </div> <div class="form-group"> <label for="">Email</label> {{form.email}} {{ form.errors.email }} </div> <div class="form-group"> <label for="">Phone</label> {{form.phone}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> {% endblock %} How I can do this with Django's built-in validation? -
Django form CharField TextInput characters problem
I have problem with CharField validation I want to my charfield validate return valid when import all characters Example: 'acbakjcb678' 'vasc4545$#@' 'acs ncjsabc 678' My Form: class ProjectsForm(forms.ModelForm): proje = forms.CharField( max_length=255, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Proyektin Adı', })) description = forms.CharField( max_length=1000, widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Proyekt haqqında qısa məlumat', 'rows' : '4', }) ) def clean(self): proje = self.cleaned_data.get('proje') description = self.cleaned_data.get('description') return { 'proje': proje, 'description': description } class Meta: model = Projects fields=('proje', 'description',) ``` My Models: class Projects(models.Model): proje = models.CharField(_("Proyekt adı"), max_length=255, unique=True) description = models.CharField(_("Proyekt haqqında qısa məlumat"), max_length=1000) keyword = models.CharField(_("Proyektin url üçün unicodelaşdırılmış adından törəyən açar sözü"), max_length=255 ) url = models.CharField(_("Proyekt üçün ayrılan api url"), max_length=255) def __str__(self): return "{} {}".format(self.proje, self.description) class Meta: verbose_name='Project' verbose_name_plural='Projects' My view.py function: def add_proje(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) data['proje'] = str(data['proje']) print(data) form = ProjectsForm(data) if form.is_valid(): proje = form.cleaned_data.get("proje") description = form.cleaned_data.get("description") name_low = proje.lower().replace('ə','e') name_to_url = unidecode(name_low).replace(" ","_") if name_to_url.isalpha(): url = socket.gethostbyname(socket.gethostname())+'/'+name_to_url+'/data/' print(url) new_proje = Projects(proje=proje,description=description,keyword=name_to_url,url=url) new_proje.save() return JsonResponse({'status': 'OK', 'url': url}) return JsonResponse({'status': 'BAD', 'errors':form.errors}) return HttpResponseNotFound() -
Trigger django-simpleJWT auth manually
I'm trying to repurpose django-rest-framework-simplejwt to authenticate in a completely different way (phone number and SMS validation code in two different requests). The thing is I have everything developed, but due to the tight integration of this auth system in the project I would have to trigger manually the TokenObtainPairView so the user still receives the token and is authenticated in the system. Is there any way I can do that? I thought about triggering the view manually, but that wouldn't work since even if I customize the serializer for that view, I can't override standard username/password for the user (the user doesn't have a password and the username is random) Any ideas on how to do this? My current code is this: class LoginResource(APIView): permission_classes = (permissions.AllowAny,) def post(self, request): payload = json.loads(request.body) try: profile = UserProfile.objects.get(phone=payload.get('phone', '')) code = codegenerator() profile.authentication_code = code profile.save() # TODO: Send the generated code over SMS send_mail( 'Your authentication code', 'Your authentication code is: {}'.format(code), settings.EMAIL_SEND_FROM, (profile.email,), fail_silently=False, ) payload = { "status": "success" } return JsonResponse(payload, status=200, safe=False) except Exception as e: payload = { "status": "error", "message": "Unable to obtain the user: {}".format(e) } return JsonResponse(payload, status=500, safe=False) class ValidateCodeAndLogin(APIView): … -
Is there any way to display dxf in browser?? If not do I required any viewer to integrate it to my project?
At first I tried to convert dxf to svg but it is outputed in black and white color. So it didn't work. Now I am trying to render the dxf to the browser but couldnot. Is there any to do. It will be better if there is any way in python. -
How can I use a custom logging handler with django?
I'm trying to integrate logging with loki in my django app like this: handler = logging_loki.LokiHandler( url="http://localhost:3100/loki/api/v1/push", tags={"app": "django", "env": ENV}, version="1", ) LOGGING = { # some logging configs } What do I need to change so that django uses this custom handler? I tried just referencing the handler object in the logging dict but that didn't need to be the right approach. -
The form does not save the written address to database
I want to build a form that collects shipping addresses from users! There is views.py def is_valid_form(values): valid = True for field in values: if field == '': valid = False return valid class EnCheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } shipping_address_qs = Address.objects.filter(user=self.request.user, address_type='S', default=True) if shipping_address_qs.exists(): context.update({ 'default_shipping_address': shipping_address_qs[0] }) return render(self.request, 'en-checkout-page.html', context) except ObjectDoesNotExist: messages.info(self.request, 'You do not have an active order.') return redirect('core:en-checkout') def post(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) except ObjectDoesNotExist: messages.warning(self.request, 'You do not have an active order') return redirect('core:en-order-summary') form = CheckoutForm(self.request.POST or None) if form.is_valid(): use_default_shipping = form.cleaned_data.get("use_default_shipping") if use_default_shipping: print('Using the default shipping address') address_qs = Address.objects.filter(user=self.request.user, default=True) if address_qs.exists(): shipping_address = address_qs[0] order.shipping_address = shipping_address order.save() else: messages.info(self.request, 'No default shipping address available') return redirect('core:en-checkout') else: print('User is entering a new shipping address') customer_name = form.cleaned_data.get('customer_name') phone = form.cleaned_data.get('phone') email = form.cleaned_data.get('email') shipping_address1 = form.cleaned_data.get('shipping_address1') shipping_address2 = form.cleaned_data.get('shipping_address2') en_shipping_country = form.cleaned_data.get('en_shipping_country') shipping_zip = form.cleaned_data.get("shipping_zip") if is_valid_form([customer_name, phone, shipping_address1]): shipping_address = Address( user=self.request.user, customer_name=customer_name, phone=phone, email=email, street_address=shipping_address1, apartment_address=shipping_address2, country=en_shipping_country, zip=shipping_zip, address_type='S' ) shipping_address.save() order.shipping_address = shipping_address order.save() set_default_shipping = form.cleaned_data.get('set_default_shipping') …