Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template won't display model object attributes on page
I am attempting to display the attributes of my model object in a Django template but the data will not appear in the page source. In views.py def view_func(request): ... data = ModelObj.objects.all() print(data) #prints <QuerySet [ <ModelObj: ModelObj object (primary_key)>, ... ]> return render(request, "templates/app/page.html", {'data': data}) In page.html ... formatted html ... <thead> ... </thead> <tbody> { % for i in data % } <tr> <td> {{ i.name }} </td> <td> {{ i.time }} </td> <td> {{ i.value }} </td> </tr> { % endfor % } <tbody> When I view the page source after running the Django site: ... html ... <tbody> { % for i in data % } <tr> <td></td> <td></td> <td></td> </tr> { % endfor % } <tbody> If I add <td> {{data}} </td> to the html page, I can see the <QuerySet [ <ModelObj: ModelObj object (primary_key)>, ... ]> display on the page, but Django will not display the model object attributes on the page. Any help with this error is appreciated, thank you. -
How to import and manage the database in postgresql on the docker?
I have my Django project with structure like this: myapp/ manage.py Dockerfile docker-compose.yml my-database1.sql my-database2.sql requirements.txt pgadmin/ pgadmin-data/ myapp/ __init__.py settings.py urls.py wsgi.py This is my docker-compose.yml file: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data - ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql - ./my-database2.sql:/docker-entrypoint-initdb.d/my-database2.sql environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - PGDATA=/var/lib/postgresql/data pgadmin: image: dpage/pgadmin4:4.18 restart: unless-stopped environment: - PGADMIN_DEFAULT_EMAIL=admin@domain.com - PGADMIN_DEFAULT_PASSWORD=admin - PGADMIN_LISTEN_PORT=80 ports: - "8090:80" volumes: - ./pgadmin-data:/var/lib/pgadmin links: - "db:pgsql-server" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db volumes: db-data: pgadmin-data: I have three problems with my app: 1 - how can I import my my-database1.sql and my-database2.sql databases into postgresql? The solution (I mean ./my-database1.sql:/docker-entrypoint-initdb.d/my-database1.sql) in my code doesn't work. 2 - after successful import databases from previous step how can I see them inside pgadmin? 3 - my code should write something inside tables of my-database1.sql. How should I connect to it after import to postgresql? -
Why is the ajax status ifModified always success?
There is such an ajax code: $(document).ready(function(){ setInterval(poll_for_new_messages, 2000); function poll_for_new_messages(){ $.ajax( { url: 'messages.json', type: 'get', dataType: 'json', ifModified: true, cache: true, timeout: 2000, success: function(messages, status) { if (status === "success") { console.log('true') } else { console.log('false') } } } ) }; }); The messages.json structure [ { "name": "Test", "datetime": "09.05.2021 22:05:07", "messages": "Hello" }, { "name": "Test2", "datetime": "09.05.2021 22:05:10", "messages": "Hello Help" } ] messages.json is handled by a simple view in views.py: def messages(request): messagesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'messages.json') messagesFile = json.load(open(messagesPath)) return JsonResponse(messagesFile, safe=False) Where did I do something wrong? When the server starts, ajax, as intended, makes requests every two seconds, but every time it gets a success status, even if there was no file change. I want to make a general chat on the site, and I have already done the very adding of messages via ajax, but I also need to make sure that users receive all these messages that fall in messages.json If you help, I will be grateful. -
Trouble with pip install psycopg2
Trying to learn Django. Followed the tutorial and created my virtual environment. Now I'm trying to install psycopg2. I can install psycopg2-binary, but I've been told for "psycopg2-binary is good for development and testing but it is advised to use psycopg2 for production". So I'd like to figure this out. In my venv I'm running pip install psycopg2 it starts with this: Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Using legacy 'setup.py install' for psycopg2, since package 'wheel' is not installed. Installing collected packages: psycopg2 Running setup.py install for psycopg2 ... error Then gives this error: ERROR: Command errored out with exit status 1: command: /Users/Me/Documents/Learn/PythonDjango/dev/project/venv/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/setup.py'"'"'; __file__='"'"'/private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-record-30vttiiv/install-record.txt --single-version-externally-managed --compile --install-headers /Users/me/Documents/Learn/PythonDjango/dev/project/venv/include/site/python3.9/psycopg2 cwd: /private/var/folders/hf/9bs1zgkx5pj9gt84snhwrq780000gn/T/pip-install-atdy12xg/psycopg2_cd32e59009264d2bbf87b0a9def98b4e/ Then it's a long list of generated warnings. I've done some research and I've been unable to get it to work. Running Python 3.9.0 on macOS Big Sur 11.2.1 -
Django AJAX get next project using pagination
I'm trying to get next and previous projects by using django pagination and AJAX. I have below code: views.py product_list = Product.objects.filter(product_status=True) # Pagination page = request.GET.get('page', 1) paginator = Paginator(product_list, 1) try: product_list = paginator.page(page) except PageNotAnInteger: product_list = paginator.page(1) except EmptyPage: product_list = paginator.page(paginator.num_pages) context = { 'product_list': product_list, } return render(request, 'store/product_detail.html', context) urls.py path('product/<slug:category_slug>/<slug:slug>', views.product_detail, name='product_detail'), html template <div class="previws-next-div-block" id="box"> {% if product_list.has_previous %} <a href="#" class="previews-product w-inline-block"> <button id="previous_button"><img src="{% static 'images/Arrow.svg' %}" loading="lazy" width="25" alt="" class="left-arrow-products"></button> {% else %} <button disabled><img src="{% static 'images/Arrow.svg' %}" loading="lazy" width="25" alt="" class="left-arrow-products"></button></a> {% endif %} {% if product_list.has_next%} <a href="#" class="next-product w-inline-block"> <button id="next_button"><img src="{% static 'images/Arrow.svg' %}" loading="lazy" width="25" alt="" class="right-arrow-products"></button></a> {% else %} <button disabled><img src="{% static 'images/Arrow.svg' %}" loading="lazy" width="25" alt="" class="right-arrow-products"></button> {% endif %} </div> AJAX script <script> $('#next_button').on('click', function () { {% if product_list.has_next %} page={{ product_list.next_page_number }}; {% endif %} $.ajax({ type: "GET", url: './', data: { page: page }, success: function (data) { $('#box').html(data) }, }); }); $('#previous_button').on('click', function () { {% if product_list.has_previous %} page={{ product_list.previous_page_number }}; {% endif %} $.ajax({ type: "GET", url: './', data: { page: page }, success: function (data) { $('#box').html(data) }, }); }); … -
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?