Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hide/show chart.js charts
I have this code snippet down below which basically alternates between 3 canvases, the user should chose which chart to display, and it's working fine as you can see (try to change between select values from line to bar to radar and it will display chosen chart and hide others ) I would like to do a little modification, when the page loads I want only 1 chart to be display ( the line chart), and then the same thing should be happening, if u want to change to another type of chart then using the select box do so. The problem is , when I add "hidden" to the bar and radar charts, the whole thing stops working and by choosing from the select box it doesn't work, any idea how to show only the line chart at the beginning without harming the whole process I did? thank you function updateChartType() { var all_types = ["turn_over_line", "turn_over_bar", "turn_over_radar"]; var current_shown =document.getElementById("chartType").value; for( var i = 0; i < all_types.length; i++) { if (all_types[i] != current_shown) { if (document.getElementById(all_types[i]).style.display!="none") { document.getElementById(all_types[i]).style.display="none"; } } else { if (document.getElementById(all_types[i]).style.display!="block") { document.getElementById(all_types[i]).style.display="block"; }} } } .cann { border: 3px solid darkgrey; padding: 10px; … -
two forms one submit button error | IndentationError: expected an indented block
I'm trying to submit to forms with one button. I check a few other posts in here, but I'm not sure if the code below is the correct and also I'm nor sure why I am getting the this error: ** File "/***********/main_app/views.py", line 85 else: ^ IndentationError: expected an indented block ** def cars_detail(request, car_id): car = Car.objects.get(id=car_id) profile_form = ProfileForm() booking_form = BookingForm() if request.method == 'POST': profile_form = Profile_form( request.POST,prefix="profile_form") booking_form = Booking_form( request.POST,prefix="booking_form") print(request.POST) if profile_form.is_valid() or booking_form.is_valid(): else: profile_form = Profile_form(prefix="profile_form") booking_form = Booking_form(prefix="booking_form") return render(request, 'cars/detail.html', { 'car': car, 'booking_form': booking_form, 'profile_form': profile_form }) def add_profile(request, car_id): # create a ModelForm instance using the data in request.POST form = ProfileForm(request.POST) # validate the form if form.is_valid(): # don't save the form to the db until it # has the car_id assigned new_profile = form.save(commit=False) new_profile.car_id = car_id new_profile.save() return redirect('detail', car_id=car_id) def add_booking(request, car_id): # create a ModelForm instance using the data in request.POST form = BookingForm(request.POST) # validate the form if form.is_valid(): # don't save the form to the db until it # has the car_id assigned new_booking = form.save(commit=False) new_booking.car_id = car_id new_booking.user_id = request.user.id new_booking.save() return redirect('detail', car_id=car_id) -
Django signup stopped working, no reverse match
I swore I had my signup working using a pretty standard tutorial, something akin to this: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html The error I get that I could almost swear was never in this app (it has been a while since I tinkered on this app) is: NoReverseMatch at /accounts/signup/ Reverse for 'activate' with keyword arguments '{'uidb64': 'MjQ', 'token': 'amg6x2-89f39b687cf5876c12d87bdfcd452731'}' not found. 1 pattern(s) tried: ['accounts\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] It goes on to say: Reverse for 'activate' with keyword arguments '{'uidb64': 'MjQ', 'token': 'amg6x2-89f39b687cf5876c12d87bdfcd452731'}' not found. 1 pattern(s) tried: ['accounts\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] 1 {% autoescape off %} 2 Hi {{ user.username }}, 3 Please click on the link to confirm your registration, 4 http://{{ domain }}{% url 'activate' uidb64=uid token=token %} 5 {% endautoescape %} Not sure why it doesnt like the 'activate' there, I found one stackoverflow suggestiong to make the link {% url 'appname:activate' uidb64=uid token=token %} But this is living in the standard /accounts folder. So i didn't see a need for appname, my login, logout work just fine with the same kinds of links. So not sure why all of a sudden my app doesn't allow the sign up towork anymore and throws this reverse match error -
Django validation error not working in Class Based View
I am using class Based view for update my Blog post but validation error message not showing in my Django template html. Here is my code: froms.py from .models import * from django import forms from django.core.exceptions import ValidationError class BlogPost(forms.ModelForm): class Meta: model = Post fields = ['title','author','body'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'author': forms.Select(attrs={'class':'form-control'}), 'body': RichTextField(), } def clean(self): cleaned_data = super(BlogPost,self).clean() title = cleaned_data.get('title') if title: if title(name)<30: count_text = len(title) raise ValidationError("Title is too short") views.py class blog_update_view(UpdateView): model = Post template_name = "blog_update_post.html" form_class = BlogPost html {% form.non_field_errors %} <form method="POST"> {% csrf_token %} {{form.media}} {{form.as_p}} <button class="btn btn-info">Publish</button> </form> </div> I also want to know how to handle others error in django-form such as integrityerror in class based view. -
Generic Views vs APIView vs Viewsets, vs ModelViewsets
I just started learning Django Rest Framework and I get to now about 4 concepts APIView, Viewsets, Modelviewsets, GenericView. What is the difference between them and which of them is more efficient to use in the development of rest APIs and why? -
How to delete notification by using django-notifications-hq
How can we query and select specific id of a notification..? Right now following problem i'm facing... You can see in else section i am sending notification that a person followed other person. Now In if selection when a person unfollow the person he followed. That notification should be removed so that when he follow again the previous notification get removes and new one get generated. I expect kind and help full ans from you guys . Thank you !:) if follower: profile_.follower.remove(follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) query = Notification.objects.filter(id__in=notificacion_ids).update(deleted=True) #notificacion_ids(I don't understand how to get that.) print(query,"hey heyh eh") # json_follower = some_view(user) else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) actor = User.objects.get(pk=user_id) user = User.objects.get(username=username_to_toggle) notify.send(actor, recipient=user, verb='follow you') # json_follower = some_view(username_to_toggle) is_following = True -
Django Form's Dropdown Data is not stored in Database
I am creating a form , where I am trying to fetch the options from database entries in django with a for loop. However , I am facing an issue where the dropdown's entry are stored as blank in my database. Not sure what exactly is causing that issue. This is the UI side where from where I am trying to add the details, This is the admin panel, where I am not getting the data saved: Below is the code , I have written. models.py class MakeSetup(models.Model): make_setup_id = models.IntegerField( primary_key= True) make_setup_name = models.CharField(max_length=125, default="NA") make_setup_device = models.CharField(max_length=125, default="NA") make_setup_consumable = models.CharField(max_length=125, default="NA") def __str__(self): return self.make_setup_name class Meta: db_table = "make_setup" class Device(models.Model): device_id = models.IntegerField( primary_key= True) device_name = models.CharField(max_length=125 , default="NA") device_type = models.CharField(max_length=125 , default="NA") def __str__(self): return self.device_name class Meta: db_table = "devices" views.py def make_setup(request): if request.method == "POST": make_setup_name = request.POST.get("make_setup_name") make_setup_device = request.POST.get("make_setup_device") make_setup_consumable = request.POST.get("make_setup_consumable") MakeSetup.objects.create( make_setup_name = make_setup_name, make_setup_device = make_setup_device, make_setup_consumable = make_setup_consumable ) return render( request, "make_setup.html", { 'device_n':Device.objects.all(), 'consumable_n':Consumable.objects.all(), 'msg':'Setup Added!' } ) else: return render( request, "make_setup.html", { 'device_n':Device.objects.all(), 'consumable_n':Consumable.objects.all(), } ) def add_device(request): if request.method == "POST": device_name = request.POST.get('device_name') device_type = request.POST.get('device_type') … -
Django orm, transform object name
I can not figure out how to convert the name of the object on the fly LANGUAGES = [ 'en','af', 'ar','az', 'bg','be','bn','bs',] for i in LANGUAGES: r = myCity.objects.get(id=tet.id) r.myCity_base_ (+i) =(str(z.name)) r.save You should get something like this object type standard django orm r.myCity_base_en r.myCity_base_af r.myCity_base_az r.myCity_base_bg thank you for your help -
How to delete existing Google OAuth2.0 token (Error 401: deleted_client)
I deleted the credentials I had for a test app on Google Cloud Platform and made new ones. I was trying to solve an issue I was having but unfortunately this introduced a new problem. The issue appears when I'm redirected to the Google sign-in page. I inspected the Google URL, and it would appear that it is trying to use the client ID from my old credentials to sign in. This despite me having updated the client secret JSON file. Could this token be stored in a working directory? And if so how would I find it (I'm using VSCode)?? flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(r"client secret location", scopes=scopes) flow.redirect_uri = 'redirect URL' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true' ) token = flow.fetch_token(authorization_response=authorization_response) credentials = flow.credentials Photo of the error from Google -
DRF custom serializer "Field name is not valid for model"
I have a big model that I'd like to reduce to just a name and its ID. My (relevant) code is as follows: ### Models class Person(models.Model): first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) class Employee(models.Model): person = models.OneToOneField('Person', related_name='employee', on_delete=models.CASCADE) class Job(models.Model): employee = models.ForeignKey('Employee') ### Serializers class SimpleEmployeeSerializer(serializers.ModelSerializer): def to_representation(self, instance): name = instance.person.first_name + ' ' + instance.person.last_name return { 'id': instance.id, 'name': name, } def to_internal_value(self, data): try: try: obj_id = data['id'] return Employee.objects.get(id=obj_id) except KeyError: raise serializers.ValidationError( 'id is a required field.' ) except ValueError: raise serializers.ValidationError( 'id must be an integer.' ) except Employee.DoesNotExist: raise serializers.ValidationError( 'Obj does not exist.' ) class Meta: model = Employee fields = ['id', 'name'] class JobSerializer(WritableNestedModelSerializer): employee = SimpleEmployeeSerializer(many=False) class Meta: model = MpProject fields = [ 'id', 'employee', ] Please do not concern yourself with whether this should or should not be a OneToOne relation, my model is more complicated in practice. The error I'm getting is Field name 'name' is not valid for model 'Employee'. I didn't get this error when I had not implemented to_internal_value, but I need this since I want to be able to POST a new Job with the SimpleEmployee format. Can someone … -
Django Postgres: how do I query string primary_key value containing special characters?
I have a Django REST API where I have defined the primary_key to be a string value instead of automatic integer. POST works great and everything looks good in the database. My problem is that when I try to use that primary_key value to query just one row from the database the browser gives me Page Not Found -error. The problem seems to be my id's are in the form: user#7be2e797-bd30-42e3-8686-7e14123120a0, the error I get says: The current path, api/users/user, didn’t match any of these.. I also tried to save one row to the db without that user#, then I get an error: The current path, api/users/7be2e797-bd30-42e3-8686-7e14123120a0, didn’t match any of these.. When I saved one row with id "100", the query worked fine, so I think the problem is the special characters (#/-)? This is what I have in my urls: url("users/(?P<pk>\d+)/$", UserView.as_view()). How should I modify this to get the user# prefix and the dashes to the query? -
Adding a link to the django admin panel
I have a page and I need to go to it from the admin panel. How can I specify a link in the admin panel? Maybe you can somehow add a link to the page in the header -
Invalid LngLat object: (NaN, NaN) - getElementById not returning values
The user positions a marker which adds the Latitude and longitude to a form, this lat & long are populated based on the users entry to the database. When trying to show the user where they set the marker and saved their lat and lon, I would like the mapbox marker to be placed using this lat and long figures. When using document.getElementById('savedlong'); this is returning Invalid LngLat object: (NaN, NaN). Javascript window.onload = function() { var marker_lat = document.getElementById('savedlong'); var marker_long = document.getElementById('savedlat'); var marker = new mapboxgl.Marker({ element:markerElement, draggable: false }) .setLngLat([marker_long, marker_lat]) .addTo(map); } HTML <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> {% for instance in object_list %} <p>Safezone name: {{instance.name}}</p> <p>Alert email: {{instance.useremail}}</p> <p id="savedlong">{{instance.longitudecentre}}</p> <p id="savedlat">{{instance.latitudecentre}}</p> {% endfor %} </div> </div> -
Error label innerHTml disappears when image preview is loaded
I'm working on a django project where I need to permit the user to upload images to the server. Everything's fine except when I want to show an image preview before submitting. I'm using django-crispy-forms to render the form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ["image", "caption"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = "post" self.helper.form_action = 'add-post' self.helper.add_input(Submit("add-post", "Add Post", css_class='btn-primary btn-dark mt-3')) This is the HTML template used for rendering the form: <div class="row justify-content-center mt-4"> <div class="col-md-8"> {% crispy form %} </div> </div> This based on the developer inspector in firefox yields the following input HTML: <input type="file" name="image" class="custom-file-input" accept="image/*" id="id_image" required=""> <label class="custom-file-label text-truncate" for="id_image">---</label> After hitting the submit button, the label gets filled with image name. That's exactly what I want. However, as mentioned I wanted an image preview before submitting so I took look at the following stackoverflow answer and got what I want: preview image before form submit Show an image preview before upload I managed to get an image preview using the following js and HTML: <div class="row justify-content-center mt-4"> <img id="image-preview"> </div> <div class="row justify-content-center mt-4"> <div class="col-md-8"> {% crispy form %} </div> … -
Django + Celery + RabbitMq
I have a function that iterates through a mathematical combination resulting in more than 1M iterations. At the end of each iteration, another function is called passing the current combination and the result is saved in an array that is then returned at the end of the function. This is implemented in a view and the result is displayed to the user after a request. The complete execution takes several seconds (i.e. 80 seconds) in a given machine. What is the correct approach to implement a solution using Celery and RabbitMq to reduce the overall processing time? -
how to update a field without change auto-now field?
In a loop and automatically, that is, I always check all users once every 10 minutes, and I may need to update a boll field from them How can I not change my current field when I update that bool field ? class Client(models.Model): user = models.ForeignKey ... last_activity = models.DateTimeField(_("Last Activity"), auto_now=True) joined = models.BooleanField(_("Joined in Default Channel"), default = False) ... ... i want to update joined field without change last_activity. how can i do? -
Is there a Django manage.py command for running Celery worker?
I created a short Python script to launch the Celery worker for the current Django via: from celery.bin import worker worker.worker(app=my_app).run() This works great and utilizes all the correct settings so there's no need to specify all the myriad command-line arguments of celery (and I can launch it via debugpy and remote debug it from a container in VS Code). My question is whether there is a manage.py command I can run to achieve the same thing? -
Drag and Drop File Input Require Validation
I have a file input from Django forms that renders to <input type="file" name="file" required id="id_file" accept="application/pdf"> <label for="id_file" id="labelFile"><i class="fa fa-upload"></i> <span>Upload File...</span> </label> I wanted to add a drop and drop to this file input so I did const dropHandler = function(ev){ ev.preventDefault() if(ev.dataTransfer.items){ for(const i of ev.dataTransfer.items){ if(i.kind === 'file'){ const file = i.getAsFile() console.log(file); const fileIn = document.querySelector('#id_file') fileIn.file = file console.log(fileIn.file.name); $('#labelFile span').html(fileIn.file.name) } } } } The problem is it doesn't let me submit the form because the input file field is required. Is doing fileIn.file = file incorrect for setting the input file field so it satisfies the required? -
Debuggin django log on NGINX - DigitalOcean
I have a Django application (droplet) on DigitalOcean but I have an issue showing information in a table. Everything works on my local server but when I deploy to the server on DigitalOcean I don't know where I can see the activity of the server like print outputs. I can see the gunicorn and nginx logs but none of those logs show the Django activity. What should I do? -
Error message: "'NoneType' object is not callable". - received from zappa deployed django application on AWS Lambda
I'm running into an error after deploying my django app to lambda using zappa. This is the error: {'message': 'An uncaught exception happened while servicing this request. You can investigate this with the `zappa tail` command.', 'traceback': ['Traceback (most recent call last):', ' File /var/task/handler.py, line 540, in handler with Response.from_app(self.wsgi_app, environ) as response:', ' File /var/task/werkzeug/wrappers/base_response.py, line 287, in from_app return cls(*_run_wsgi_app(app, environ, buffered))', ' File /var/task/werkzeug/wrappers/base_response.py, line 26, in _run_wsgi_app return _run_wsgi_app(*args)', ' File /var/task/werkzeug/test.py, line 1119, in run_wsgi_app app_rv = app(environ, start_response)', TypeError: 'NoneType' object is not callable]} These are my zappa settings: { "production": { "aws_region": "eu-west-2", "django_settings": "app.settings", "profile_name": "deployment", "project_name": "app", "runtime": "python3.6", "s3_bucket": "zappa-deployment-uploads", "slim_handler": true, "exclude": [".ebextensions/", ".elasticbeanstalk/", "webpack/", "app/static/"], "vpc_config" : { "SubnetIds": [ "..."], "SecurityGroupIds": ["..."] } } I've ensured that my API Gateway hostname has been added to my allowed hosts setting and redeployed. I've called zappa tail, but it gives me an even shorter error respons "'NoneType' object is not callable". Can anyone understand why I would be getting this? -
Search Django logic
I have written the following code on my web app for searching the form. Now, I want to show error if the searched object if not found. I added the else statement at the last but it shows error. def search(request): qs = Post.objects.all() location_query= request.GET.get('location') details_query= request.GET.get('details') user_query= request.GET.get('user') days_query= request.GET.get('days') people_query= request.GET.get('people') date_query= request.GET.get('date') gender_query= request.GET.get('gender') if location_query !='' and location_query is not None: qs=qs.filter(location__icontains=location_query) elif details_query !='' and details_query is not None: qs=qs.filter(detail__icontains=details_query) elif user_query !='' and user_query is not None: qs=qs.filter(author__icontains=user_query) elif days_query !='' and days_query is not None: qs=qs.filter(no_days__icontains=days_query) elif people_query !='' and people_query is not None: qs=qs.filter(no_people__icontains=people_query) elif date_query !='' and date_query is not None: qs=qs.filter(tour_date__icontains=date_query) elif gender_query !='' and gender_query is not None: qs=qs.filter(Gender_prefer__icontains=gender_query) context = { 'qs':qs, } return render(request, 'posts/search.html',context) I am trying to add this at the end: return render(request, 'posts/search.html', {'error':'The keyword you entered not found!}) -
how do i generate Django site-map without model
i have searched google a lot and read many articles and docs. but all shows how to create sitemap in django useing from django.contrib.sitemaps.views import sitemap but the problem is they all generate sitemaps on top of model(table). i have a database of images( 20,000 images ) they all have different pages and their link generated manually like... path('image/<str:name>/<str:size>/', views.image, name="image"), also my site have many static pages like about us and contact us. also many image gallery pages. so the site have thousands of urls. the image database changes frequently so url changes too how do i generate xml sitemap for this situation. or maybe there is a way around with 3rd party plug in? -
Error when adding DateField in Django "function missing required argument 'month' (pos 2)
I'm a newbie with Django, and today when I used DateField to make time value in my DB, I have got this error "function missing required argument 'month' (pos 2)" I have tried to solve this, but it can not help me. Django documentation Same question in StackOverflow but not affect to me Here is my code: class History(models.Model): code = models.OneToOneField( Passport, on_delete=models.CASCADE, primary_key=True, default=1, ) origin = models.CharField(max_length=64) originTime = models.DateField(auto_now=True) destination = models.CharField(max_length=64) destinationTime = models.DateField(auto_now=True) def __str__(self): return f"{self.code}" And this is my screen error: my db application Thank you. I'm so grateful. -
On submit a Django ChoiceField form only returns the first dictionary in the formset
I have defined a formset that has 3 forms in the following order. Type Number (Student ID) Type Text (Course Name) View.py for form in formset: if form.has_changed(): print(form.cleaned_data) When a post request is submitted the formset.cleaned_data returns [{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}] I have also added a check if a form.has_changed(), so if I submit 'History' instead of 'English' where id is equal to 1 my form.cleaned_data returns the expected dictionary. {'student_id': 1, 'course_name': 'History'} My issue: When I had a type text form for 'course_name' everything was working as intended. I only faced an issue when I changed the text form to be single-select instead, so the formset is as follows: Type Number (Student ID) Type ChoiceField (Course Name) The formset.cleaned_data returns the same list of dictionaries. [{'student_id': 1, 'course_name': 'English'}, {'student_id': 2, 'course_name': 'Math'}, {'student_id': 3, 'course_name': 'PE'}] However, if I submit 'History' to change the 'PE' course where id is equal to 3 the form.cleaned_data always returns the first dictionary in the list. {'student_id': 1, 'course_name': 'English'} Why is this happening? Is there any issue with using ChoiceField in the formset? -
Capture images from RTSP Stream without displaying the feed
I want to capture images every 30 seconds from RTSP feed from an IP camera. I don't want to display the feed, I just want to capture images from the feed store them and them upload them to a django server for image recognition. Is it possible to this with react native? if so can you please kindly suggest me how. Thank you