Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble rendering MathJax equations wrapped in span tags
I'm trying to render math equations in my template using Django, along with CKEditor. When I render my math equation, in inspect element, it looks like this: <p><span class="mathjax-latex">\(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\)</span></p></p> However, even with the MathJax scripts enabled, the formula doesn't render when I go look at it. Here is my MathJax script in the template: <script type="text/x-mathjax-config"> MathJax.Hub.Config({ showProcessingMessages: false, //Close js loading process information messageStyle: "none", //Do not display information extensions: ["tex2jax.js"], jax: ["input/TeX", "output/HTML-CSS"], tex2jax: { inlineMath: [ ["$", "$"] ], //In-line formula selection$ displayMath: [ ["$$","$$"] ], //The formula selection in the paragraph$$ skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'], //Avoid certain tags ignoreClass:"comment-content", //Avoid tags containing the Class processClass: "mathjax-latex", }, "HTML-CSS": { availableFonts: ["STIX","TeX"], //Optional font showMathMenu: false //Close the right-click menu display } }); MathJax.Hub.Queue(["Typeset",MathJax.Hub]); </script> <script src="https://cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> What do I need to do to render math equations with the span tags attached? -
How to write multiple rows with unique column in django model field
I have a django model with the following presentation in mysql: id project_id X Y where the model called ProjectModel, and here it is: class ProjectModel(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, unique=False) X = models.TextField(null=True) Y = models.TextField(null=True) and this is my code: projects = Project.objects.all() for project in projects: model = ProjectModel() all_dict = extract_dict(project) # its like all_dict = {'item1':{'X': 221, 'Y': 'NewYork'}, 'item2':{'X':2.3, 'Y':'Milan'}, ...} for k, value in all_dict.items(): model.project_id = project.id model.X = value['X'] model.Y = value['Y'] model.save() I expect something like this out put: id project_id X Y 1 21 221 NewYork 2 21 2.3 Milan 3 23 65 Berlin 4 24 38 Amsterdam .... I want to write every single item with even equal project_id in one row and then aggregate them using groupby. but I get error like: django.db.utils.IntegrityError: (1062, "Duplicate entry '21' for key 'project_id_UNIQUE'") -
Star Rating in Django
I've seen other posts about this but still, I'm too dumb :/ So I have this site with products, each product has its unique page-detail where you can leave comments. And now I want to add the possibility to 'star-rate' the product when you write a comment, like in the picture. Im guessing the first step is to add an Integer field on the "comments model" . But what are the steps from now on ? Im guessing a little JS is needed but i don't rlly know js :/ models.py class CommentsModel(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) component = models.ForeignKey(ProductsModel,on_delete=models.SET_NULL, null=True) text = models.TextField(null=False) date = models.DateTimeField(default=timezone.now) rating = models.IntegerField(default=0, validators = [ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return '%s %s' % (self.component.name, self.user.username) views.py def comments_view(request, id): component = get_object_or_404(ProductsModel, id = id) comments = CommentsModel.objects.filter(component = component).order_by('-id') if request.method == 'POST': comment_form = CommentsForm(request.POST or None) if comment_form.is_valid(): text = request.POST.get('text') comment_form = CommentsModel.objects.create(component=component, user=request.user, text=text) comment_form.save() return HttpResponseRedirect(component.get_absolute_url()) else: comment_form = CommentsForm() context = {'object':component, 'object2':comments, 'comment_form':comment_form} return render(request, 'templates/comments/comments.html', context) this is my site with some stars in the template referring how I d like to look and work -
How to avoid django integrityerror for update existing blog post
I am using this clean method in my froms.py for prevent user to create blog post using duplicate title or title that already exist in my website. But I am also getting this integrityerror while I am going to update my old blog post. see the picture how to avoid integrityerror for update old blog post. here is my code: #froms.py from .models import * from django import forms from django.core.exceptions import ValidationError from django.db import IntegrityError class BlogPost(forms.ModelForm): def clean_title(self): title = self.cleaned_data['title'] if IntegrityError(title): raise forms.ValidationError('This title already exists. Please use different title') return title 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(), } views.py class blog_update_view(UpdateView): model = Post template_name = "blog_update_post.html" form_class = BlogPost -
Django Rest Framework - Register Multiple Viewsets Against a Single URL, Based on Header Data
I need to use Multiple ViewSets with the same URL where the active ViewSet needs to be selected dynamically based on request header logic. Django rest framework allows you to do this to register the viewsets against different urls: router.register(r"type_1", Type1ViewSet, basename="type_1") router.register(r"type_2", Type2ViewSet, basename="type_2") However, in my case, the viewsets are very similar. So I'd like to do this in the urls.py file: if request.header['flag'] is True: router.register(r"type", Type1ViewSet, basename="type_1") else: router.register(r"type", Type2ViewSet, basename="type_2") In my case, the following wouldn't work: Using a single ViewSet but picking different Serializers from the header logic instead of dealing with multiple ViewSets. Is there a way to get access to the request object in the urls.py so that I can use it to orchestrate my conditional? If not, how this can be achieved? -
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?