Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Jquery Not Updating Management Formset
Very new to Django in general. View, template is working great, but for some reason, jquery.formset.js is not updating TOTAL_FORMS. Thus, while I can add entries and they are rendered in the HTML, only one is submitted. Oddly enough, adding several forms and then removing one correctly sets the value of TOTAL_FORMS properly. Probably time for a javascript course... Here is Jquery script I am referring to. Views.py def submit(request): order = Order() order_form = OrderForm() SelectionFormSet = get_ordereditem_formset(SelectionForm,extra=1,can_delete=True) if request.method == 'POST': order_form = OrderForm(request.POST, instance=order) formset = SelectionFormSet(request.POST, request.FILES,instance=order,prefix='horseselection_set') if order_form.is_valid() and formset.is_valid(): order_form.save() formset.save() return HttpResponseRedirect(order.get_absolute_url()) else: order_form = OrderForm(instance=order) formset = SelectionFormSet(instance=order,prefix='horseselection_set') return render(request,'orderform/order_form.html',{'form': order_form,'formset': formset}) order_form.html {% extends "base.html" %} {% block title %}{% endblock %} {% block content %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ formset.management_form }} {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for … -
Django CreateView not working with TinyMCE 5
I'm trying to use TinyMCE 5 with Django CreateView and can't get it to save to the database with the submit button; the form doesn't get submitted, i.e form_valid doesn't get called. The HTML template I'm using works with both CreateView and UpdateView successfully without TinyMCE and the model gets saved to the database. One of the fields in my model is a TextArea so wanted to try TinyMCE. I downloaded the SDK and have it stored locally. I then placed the following in the tags as per the documentation: <script src="{% static 'tinymce/js/tinymce/tinymce.min.js' %}"></script> <script type="text/javascript"> tinymce.init({ selector: '#id_description', }); </script> With this in place, I can see and use the TinyMCE editor when both Creating a new model and updating an existing one, but I can no longer save new model data to the database. Funny thing is though, I can still update and save edited data. Since I can update existing data, but not new data, I think this is probably a bug. Can anyone confirm please. Thanks -
Site doesn't show admin panel when i write http://localhost:8001/admin/
Site doesn't show admin panel. What should I do? Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/admin/ Raised by: news.views.PageViews With what it could be connected? I don't know what to do. class PageViews(ListView): template_name = 'page.html' paginate_by = 8 context_object_name = 'posts' ordering = ['-datetime'] model = Page paginate_orphans = 1 def dispatch(self, request, *args, **kwargs): slug = kwargs.get('slug') try: self.category = Category.objects.get(slug=slug) except Category.DoesNotExist: raise Http404 return super().dispatch(request, *args, **kwargs) def get_queryset(self): return Page.objects.filter(category=self.category) -
Modifying the models.Integerfield() appearance
Apologies if such question has been already asked before but I am not really sure how the feature I need is actually called. Is it possible to create models.Integerfield() that would look something like this: https://ibb.co/9VhBL5L where I would be able to define any word to show up beside the Integerfield() instead of "$". For instance, I have a basic mathematics task where kids need to calculate a number of animals in a forest. So the field would be blank and on the side of the field it would say "animals". So far, I can create only an empty field in Django: answer_1 = models.IntegerField( min=0, label='How many animals do you see?') Thanks. -
Django: Url translation is wrong
I have the following translation: {% url 'admin:organizers:settings:index' request.organizer.slug as business_settings_url %} {% blocktrans trimmed %} Looking for <a href="{{ business_settings_url }}">business settings</a>? {% endblocktrans %} However, I always get the wrong url: http://127.0.0.1:8000/admin/everett-vega-and-davis/survey-test/settings/%E2%80%9C/admin/everett-vega-and-davis/settings/%E2%80%9D It should be http://127.0.0.1:8000/admin/everett-vega-and-davis/survey-test/settings/ Do you see what I am doing wrong here? -
Django Models: Default for Choice Foreign Key
I have a Type model class as follows: class Type(models.Model): ENVIRONMENT = 'A' HUMANENV = 'B' HUMAN = 'C' ANIMAL = 'D' UNKNOWN = 'H' TYPE_CHOICES = [ (ENVIRONMENT, 'Environment'), (HUMANENV, "Human-related Environment"), (HUMAN, 'Human'), (ANIMAL, 'Animal'), (UNKNOWN, 'Unknown'), ] code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True) class Meta: ordering = ['code'] def __str__(self): return self.get_code_display() And another Sample model where one of the fields is a foreign key to the Type model as follows: class Sample(models.Model): sample_id = models.CharField(max_length=20, unique=True) type = models.ForeignKey("Type", on_delete=models.CASCADE, blank=True, default=get_default_type()) class Meta: ordering = ["sample_id"] def __str__(self): return self.sample_id where get_default_type is a function that returns the pk for the default Type model instance: def get_default_type(): return Type.objects.get(code="H").id The problem is when I run Sample.objects.create(sample_id="some_id"), it is giving me the error IntegrityError: null value in column "type_id" violates not-null constraint DETAIL: Failing row contains (28113, some_id, null). As you can see in the second line of the error message, the type_id is null instead of the pk as returned by the get_default_type function. I have tried setting null=True for the foreign key and when I do that I am able to create the Sample model instance, but with a None type instead of the Unknown … -
Copy contents from a model to another model
I need to copy the full contents from a table to another everytime that the user add an object. I have this two models: from django.contrib.gis.db import models from django.contrib.gis.geos import Point from mapbox_location_field.models import LocationField class AddPointManager(models.Model): description = models.TextField( 'Short description', max_length=500, help_text="Max 500 characters.", ) location = LocationField() def __int__(self): return self.pk def get_absolute_url(self): return reverse("point", kwargs={"pk":self.pk}) class Meta: ordering = ['-pk'] class AddPoint(models.Model): description = models.TextField( 'Short description', max_length=500, help_text="Max 500 characters.", ) geom = models.PointField() def __int__(self): return self.pk def get_absolute_url(self): return reverse("point", kwargs={"pk":self.pk}) def save(self, *args, **kwargs): manager = AddPointManager.objects.all() lat = self.manager.location[0] lon = self.manager.location[1] self.geom = Point(x=lon, y=lat, srid=4326) self.description = AddPointManager.description super(AddPoint, self).save(*args, **kwargs) @property def coordinates(self): return str(self.geom.x) + ', ' + str(self.geom.y) class Meta: ordering = ['-pk'] I think that my save method isn't correct because when I add a point by admin panel I can see itself in AddPointManager but not into AddPoint. The table of AddPoint remains empty. admin.py from django.contrib.gis import admin from mapbox_location_field.admin import MapAdmin from .models import AddPointManager class AddPointManagerAdmin(MapAdmin): class Meta: model = AddPointManager admin.site.register(AddPointManager, AddPointManagerAdmin) -
How to emulate native CREATE response
I am trying to emulate the type of JSON response I get from a ModelSerializer when doing a GET. I have this ViewSet: def create(self, request, *args, **kwargs): recipe_ingredient = RecipeIngredient.objects.create( base_ingredient=Ingredient.objects.get(pk=request.data['base_ingredient']), recipe=Recipe.objects.get(pk=request.data['recipe']) ) data = serializers.serialize('json', [recipe_ingredient, ]) struct = json.loads(data) data = json.dumps(struct[0]) return Response(data) This returns a JSON the physical recipe_ingredient instance instead of just the data like it would with my RecipeIngredientSerializer when I make a GET request. Once I have created an object through .create(), how can I return a JSON that would have all the same serialization as my RecipeIngredientSerialzer returns when I do a GET? -
Django update view only seems to work with regex urls
I am getting my hands dirty with Django and have a simple use case in which i have to create a function based view for updating a Model. Below is my function based view function: def update_post(request, id=None): obj = get_object_or_404(PostModel, id=id) form = PostModelForm(request.POST or None, instance=obj) if form.is_valid(): obj = form.save(commit=False) print(f"The object that i am going to save is {form.cleaned_data}") obj.save() messages.success(request, f"Updated object with id {id}") return HttpResponseRedirect(f"/blog/read/{id}") context = { "form": form } return render(request, "blog/update-post.html", context) Below is my update-post.html: <html> <form method="POST" action="."> {% csrf_token %} {{form.as_p}} <input type="submit" value="Change"> </form> </html> And this is my urls.py file : from django.urls import path, include from django.conf.urls import url from .views import list_posts, read_post, create_post, update_post app_name = "blog" urlpatterns = [ path('posts/', list_posts, name="list"), path('read/<int:id>', read_post, name="read"), path("create/", create_post, name="create"), #url(r'^(?P<id>\d+)/edit/$', update_post, name="update") path("update/<int:id>", update_post, name="update"), ] The update view only seems to work when i use the above regex url pattern for editing the post . Otherwise i get the below error message: Can someone please tell me where i am going wrong with this. -
Toastr JS appears in source code but is invisible
I am trying to use Toastr JS, initially i could not figure out why it just wont appear but it actually does(figured out by changing Timeout to 10min and looking at the source code) but it is invisible and i have no idea why. It Appears below everything instead of top right. My Template code {% block javascript %} {% if messages %} {% for message in messages %} {% if message.tags == 'success'%} <script> toastr.success("{{ message }}")</script> {% elif message.tags == 'info' %} <script> toastr.info("{{ message }}")</script> {% elif message.tags == 'warning' %} <script> toastr.warning('{{ message }}")</script> {% elif message.tags == 'error' %} <script> toastr.options = { closeButton: false, debug: false, newestOnTop: false, progressBar: true, positionClass: "toast-top-right", preventDuplicates: false, onclick: null, showDuration: "9000", hideDuration: "1000", timeOut: "0", extendedTimeOut: "1000", showEasing: "swing", hideEasing: "linear", showMethod: "fadeIn", hideMethod: "fadeOut" } toastr.error("{{ message }}") </script> {% endif %} {% endfor %} {% endif %} {% endblock %} -
Getting 500 Internal Server Error After Creating a Letsencrypt https certificate
Ok so I have a django project hosted on Linode served via apache webserver. After creating a certificate from Letsencrypt I get this error whenever I visit my site. Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.34 (Ubuntu) Server at www.mysite.com Port 443 I did not get this error on http before. It might something from their side or wrong configuring on my apache side. Has anyone had experience with this issue? Thank you -
Django unused import statement: virtualenv issue
I have looked all over and nobody seems to be having the same issue as me. I am new to Django and have followed many tutorials but nothing is working. Before I found out that it is best practice to setup a virtualenv for your django projects I had installed it normally (globally) on my pc (ubuntu) and everything worked fine. I wanted to follow best practice though and started fresh and setup a project in a virtualenv. The landing page works and everything, but when I go to and editor I get errors wherever imports using django are. Example: Project->polls app->views.py from django.shortcuts import render Error given: Unused import statement I am completely lost at this point. I really would love to start using Django but I really want to follow best practice with virtualenv. Any help is appreciated! -
Django Contact Form With Google Recaptcha v3
I want to implement Google Recaptcha v3 into a working Django contact form. I tried following these tutorials: https://simpleisbetterthancomplex.com/tutorial/2017/02/21/how-to-add-recaptcha-to-django-site.html https://foxrow.com/using-recaptcha-v3-with-django https://medium.com/@mihfazhillah/how-to-implement-google-recaptcha-v3-on-your-django-app-3e4cc5b65013 But have had no luck trying to figure it out. Can someone please help me out? Settings.py: GOOGLE_RECAPTCHA_SECRET_KEY = '<KEY>' Html: <script> grecaptcha.ready(function() { grecaptcha.execute('<SITE_KEY>', {action: 'contact'}) .then(function(token) { document.getElementById("form").appendChild(document.CreateElement(`<input type="hidden" name="g-recaptcha-response" value=${token}`); }); }); </script> <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <script src='https://www.google.com/recaptcha/api.js?render=<SITE_KEY>'></script> <div class="g-recaptcha" data-sitekey="<SITE_KEY>"></div> <button type="submit">Submit</button> </form> Views.py: def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" +'', ['GMAIL_ADDRESS'], headers = {'Reply-To': contact_email } ) email.send() messages.info(request, "Success") return render(request, 'contact.html', { 'form': form_class, }) Forms.py: from django import forms class ContactForm(forms.Form): contact_name = forms.CharField(required=True) contact_email = forms.EmailField(required=True) content = forms.CharField( required=True, widget=forms.Textarea ) # the new bit we're adding def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['contact_name'].label = "Name:" self.fields['contact_email'].label = "Email:" … -
Django cannt import any function from views
I am trying to import functions which is in file say aaa.py there I am importing views.py as aaa.py from .views import * and in views.py I am importing aaa.py as views.py from .aaa import * But in aaa.py I get an import error saying, cannot import name 'function_name' from 'folder_name.views' -
How the updating of m2m fields are working? Django Rest Framework
I have code where Product model has M2M field Comment model. I made methods in views.py for getting Product by id and all objects of Product, but there's problem with updating it. I can't fully understand how to update Product comments field. I already tried a lot of different answers and ideas, but nothing helps me. I'm using PUT method for update. My main questions: Where and how target Product id in order to update comments field in it? After I find Product by it's id how I can update M2M field comments in it? I tried: Completely Lost: Many To Many with Serializers and Update in Django Rest Framework Doesn't work at all, screams for 'collections.OrderedDict' object has no attribute 'id' Django Rest update many to many by id It's making PrimaryKeyRelatedField which is not correct for me. How to update many to many Django REST? Not enough information in answer, got stuck on it. I read https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers, but found no usefull information on my problem products/models.py from django.db import models from comments.models import Comment # Create your models here. class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=150, blank=True) description = models.TextField(default="No description") category = models.CharField(max_length=255, blank=True) … -
Python(Django) - Convert URL from post to a embed YouTube IFrame
Basically what I trying to achive is to find the URL in the post, for example if I post this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. https://www.youtube.com/watch?v=example It will be looking like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. YouTube Player {% extends "Feed/wrapper.html" %} {% block content %} <div class="card"> <h2 class="text-info">{{newsfeed_articles.title}}</h2> <h6 class="text-info">{{newsfeed_articles.date|date:"d-m-Y в H:i:s"}}</h6> <p>{{newsfeed_articles.post|safe|linebreaks}}<p> <div class="fakeimg" style="height:200px;">Image</div> </div> {% endblock %} -
django.db.utils.IntegrityError "error makemigrations"
django.db.utils.IntegrityError: The row in table 'biblioteka_book' with primary key '1' has an invalid foreign key: biblioteka_book.info_id contains a value '1' that does not ha ve a corresponding value in biblioteka_extrainfo.id. from django.db import models # Create your models here. class ExtraInfo(models.Model): OCENY = { (0, 'Nieznany'), (1, 'Słaba'), (2, 'Średnia'), (3, 'Dobra'), (4, 'Bardzo dobra'), (5, 'Arcydzieło') } ilosc_stron = models.IntegerField(default=0) ocena = models.IntegerField(default=0, choices=OCENY) class Book(models.Model): nazwa = models.CharField(max_length=60) opis = models.TextField() gatunek = models.CharField(max_length=30) cena = models.DecimalField(max_digits=400, decimal_places=2) wydanie = models.IntegerField(null=True, blank=True) autor = models.CharField(max_length=30) zdjecie = models.ImageField(null=True, blank=False, upload_to='Pictures') przecena = models.BooleanField() info = models.OneToOneField(ExtraInfo, on_delete=models.CASCADE, primary_key=True,) def __str__(self): return self.nazwa_with_wydanie() def nazwa_with_wydanie(self): return str(self.nazwa) + " (" + str(self.wydanie) + ")" -
Why does django admin change_form has a sorting by Primary Key query? Isn't it fetching just one object to edit it?
I have a payments_event model that has millions of data, when I click on one of them to edit it, the page takes tooo much time to load, and when I look at the queries, it has this query: SELECT ••• FROM "payments_event" ORDER BY "payments_event"."id" DESC And it's duplicated two times.. -
Rendering arcGIS pro customized map in the front end
I am new to arcGIS Pro. I created my own map in the arcGIS Pro. I want to render this map dynamically in the front end like a GoogleAPI. I connected arcGIS Pro into Pycharm. But I don't know how to render in the frontend. Could anyone tell a way to render the map??? -
I am not sure how to request Django rest-framework Social Oauth2
I am trying to add Google & Facebook social auth to my DRF api. I followed steps from readme, I read the docs but I don't know how to request my api from my react app - docs shows this example for facebook login: curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_scret>&backend=facebook&token=<facebook_token>" http://localhost:8000/auth/convert-token` And here my problem comes - I don't understand what is "client_secret" in curl request? Should it be the same as SOCIAL_AUTH_FACEBOOK_SECRET in settings (that is copied from facebook developers site)? -
Store encrypted file in django database using IPFS storage
I am developing a project where I need to upload file from template, then it is retrieved at the backend, encrypted using cryptography module and then stored in database using IPFS File storage system. However I am able to encrypt the file but not able to store it in database. Here is the code: encryption.py from cryptography.fernet import Fernet import os.path def encrypt_file(paper): key = Fernet.generate_key() input_file = paper filepath = 'static/encrypted_files' output_file = os.path.join(filepath,str(paper)+'.encrypted') data = input_file.read() fernet = Fernet(key) encrypted = fernet.encrypt(data) with open(output_file, 'wb') as f: f.write(encrypted) data_1 = open(output_file,'r') return [key,data_1] views.py paper = request.FILES.get('paper',None) content = encrypt_file(paper) queryset, created = Request.objects.update_or_create(tusername=request.user.username,defaults = {'paper':content[1],'status':'Uploaded','key':content[0]}) models.py paper = models.FileField(storage=InterPlanetaryFileSystemStorage()) -
What Should I learn after completion of django?
I have learnt django and django rest api. After completion of django should I go for React or numpy,pandas? -
Django-mail-queue does not attach file on Centos 7
I have been trying to attached and PDF file to Django-mail-queue. But seem it does not working on centos 7. On local (MacOS) is working well. I've tried to chmod the folder and file to 777 permissions, but that fails, too. This is what I tried: class TestSendMail(View): def get(self, request): send_mail_queue( settings.SERVICE_INVOICE_MAIL_TILE, '<p>Hello</>', 'it48thwru@gmail.com', [os.path.join(settings.BASE_DIR, 'test.pdf')] ) return render(request, 'frontend/pages/test_send_mail.html') def send_mail_queue(subject, html_content, to_address, files=None): from mailqueue.models import MailerMessage try: new_message = MailerMessage() new_message.subject = subject new_message.to_address = to_address new_message.from_address = settings.DEFAULT_FROM_EMAIL new_message.html_content = html_content if files: # add attach file for file in files: attach_file = File(open(file, "rb")) new_message.add_attachment(attach_file) new_message.save() except Exception as ex: import logging logger = logging.getLogger(__name__) logger.error(ex) pass How can I fix that? Thanks! -
Shared volume between Jobs ~ Gitlab Shared Runners
I am running a Gitlab pipeline on a Django + Postgres project and I am trying to build and then run my tests inside my gitlab pipeline. I am using a custom docker image in order to use docker-compose in my pipeline. I have 2 seperate jobs : build and test but the problem is by default jobs environments are not shared, so after my first build job I can't simple run my test with docker-compose exec -it app python manage.py run test How can I achieve this without having to relauch a build in my second job for my tests ? -
Marked library is not working on django template
i'm trying to render html code in my django project using 'marked' but it does not work <p class=" content-markdown" >{{object.content }}</p> <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.7.0/marked.min.js"></script> <script type="txt/javascript"> $(document).ready(function(){ $(".content-markdown").each(function(){ var content = $(this).text() console.log(content) var marked = marked(content) console.log(marked) $(this).html(marked) }) }) </script>