Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Has anyone ever used django-plotly-dash to call an API every second and live plot the API data?
I am trying to create a page that calls an ISS locator API every second and then live updates a line plot every second with the latitude/longitude data from the API. I am using Django to create this page so I'm trying to use django-plotly-dash to do this. Does anyone have experience with this or something similar that could help? -
How to deploy django aplication on linux server with gunicorn and virtualenv?
I'm new to django and this is my first project, so I'm trying to understand how things work. Is it possible to run my app without port, as for example http://127.0.0.1/myapp/ not http://127.0.0.1:8000/? I was looking for some tutorials but the only ones that I have found are showing how to deploy the app with address + port. Is it possible to do this without sudo (because I'm not an admin on my server) and with virtualenv and gunicorn? And if it is possible then could you tell me how? -
How do I customize Django language switcher options?
I am building a multilingual dictionary website using Django. I am interested in building a language switcher that distinguishes, say, American English from British English. On Django's docs I found the following language switcher: {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> In my settings.py I have restricted the set of available languages to the following: LANGUAGES = [ ('en-us', _('English (U.S.)')), ('en-gb', _('English (U.K.)')), ] This results in the select menu having two options. I expected those two options to be: English (U.S.) (en-us) English (U.K.) (en-gb) However, I got: English (en) British English (en-gb) How can I turn the current behavior into my desired behavior (both in terms of language code and the name of the language itself)? -
How go display only values from query set? <QuerySet [<Matches: MUMBAI INDIANS (MI) VS CHENNAI SUPER KINGS (CSK),2020-09-19>]>
I am learning Django and I am not able to display only values from this query set. The template tags I am using is: {% for win in match_wins %} <td >{{ win.matchdetail.all }}</td> {% endfor %} Views.py file class MatchWinsView(ListView): context_object_name = 'match_wins' model = models.Wins template_name = 'match_wins.html' And my model looks like below: class Wins(models.Model): matchdetail = models.ManyToManyField(Matches) What should I fix to get only values? -
How to solve error with syncing PostgreSQL with Vercel
I have a database using PostgreSQL but the published site is Vercel and when deploying for production is gives the error below. The error doesn't happen for Heroku django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "123.456.789.102", user "example_user", database "example_db", SSL off How do I solve this error, thank you. I have checked Google results aren't really helpful 😥😥 -
(Django) Problem installing fixture 'rules.json': 'NoneType' object has no attribute 'id'
I'm trying to populate my db with fixtures with the next command: python .\manage.py loaddata .\rules\fixtures\rules.json But I get the next error: AttributeError: Problem installing fixture 'C:\Users\Ángel - Trabajo\Documents\AVC.\rules\fixtures\rules.json': 'NoneType' object has no attribute 'id' This is my model: class Rule(LogsMixin, models.Model): """Definición de modelo para Reglas""" FIELDS = [ ('user_name', 'Nombre de usuario'), ('user_code', 'Codigo de usuario') ] string = models.CharField("Cadena de referencia", max_length=100, null=False, default="", blank=False) profile = models.ForeignKey(Profile, null=False, default=None, on_delete=models.DO_NOTHING) license = models.ForeignKey(License, null=False, default=None, on_delete=models.DO_NOTHING) field = models.CharField("Campo objetivo", max_length=50, default='nombre_usuario', choices=FIELDS) include = models.BooleanField("Incluye", null=False, default=True) order = models.IntegerField("Orden", null=True, default=None) uppercase_sensitive = models.BooleanField("Sensible a las mayúsculas", null=False, default=False) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) And this is my json: [ { "model":"rules.rule", "pk":null, "fields":{ "string": "DINAMITZADORA", "profile": "1", "license": "1", "field": "user_name", "include": "1", "order": "0", "uppercase_sensitive": "0" } }, { "model":"rules.rule", "pk":null, "fields":{ "string": "adm", "profile": "1", "license": "1", "field": "user_name", "include": "1", "order": "0", "uppercase_sensitive": "0" } }, { "model":"rules.rule", "pk":null, "fields":{ "string": "admin", "profile": "1", "license": "1", "field": "user_name", "include": "1", "order": "0", "uppercase_sensitive": "0" } }, { "model":"rules.rule", "pk":null, "fields":{ "string": "alum", "profile": "1", "license": "1", "field": "user_name", "include": "1", "order": "0", "uppercase_sensitive": "0" } }, ] I've tried … -
How to schedule a celery task through a django view
Is there any way to define a date and time in a django view and run a celery task at the defined time? For example def test(request): date = '2020-09-12' time = '11:34' # run the below task at the specified time test_celery_test.delay() ... I want the task to run only once at the specified time and should not repeat -
how can I format django-html code in vscode
So, recently I have been coding in Django and in its templates folder, as we know, we put HTML files. So earlier when I use to code in HTML only(not Django-HTML), vscode used to auto-format the code and align the tags with tab spaces properly. but in Django-html, the code is not getting auto formatted, also I have enabled the 'prettier extension' but still this problem exists: {% extends 'base.html' %} {% block title %}Contact Us {% endblock title %} {% block contactactive %} active{% endblock contactactive %} {% block body %} <div class="container my-4"> <h2>Contact our developers!</h2> <form action="/contact/" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="enter your full name" /> </div> </div> {% block body %} but I want my code to be formatted like this: {% extends 'base.html' %} {% block title %}Contact Us {% endblock title %} {%block contactactive %} active{% endblock contactactive %} {% block body %} <div class="container my-4"> <h2>Contact our developers!</h2> <form action="/contact/" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="enter your full name" /> </div> </div> {% block body %} are there any settings or any tools which I should … -
Rest-Framework: Serialize model with relationship to same model
I have a Tag model as follows: class Tag(models.Model): name = models.CharField(max_length=50) aliases = ArrayField( models.CharField(max_length=50), size=8, ) parent = models.ForeignKey(to="self", null=True, on_delete=models.CASCADE) class Meta: db_table = "tags" def __str__(self): return self.name Notice I have the parent field which is a ForeignKey to another tag object. In my serializer if I add the field parent to fields I get the following ImproperlyConfigured error. Could not resolve URL for hyperlinked relationship using view name "tag-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. class TagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = ["name", "aliases", "parent"] extra_kwargs = {"aliases": {"validators": []}} What I initially thought was I could add the TagSerializer for the parent attribute, but at this time it wouldn't be defined. So how would I serialize the parent tag? -
Decimal Field unable to update value
I have a DemicalField and have a def() for change the value of it. However, the value unable to change through the def(). May I know why? Models.py: class BillingAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) district = models.CharField( max_length=2, ) deliver = models.CharField(max_length=4, null=True) shipping_fee = models.DecimalField(decimal_places=2, max_digits=10, default=0) def __str__(self): return self.street_address def fee_caculate(self): if self.deliver == 'deli': if self.district == 'K': self.shipping_fee = 20 elif self.district == 'T': self.shipping_fee = 30 else: self.shipping_fee = 50 return self.shipping_fee -
Queryset to call ModelFormField into Chart JS - Django
I am attempting to pass user submitted data from a django model form into a Chart.js chart that renders on a detail view page. I am having trouble figuring out why I cannot call values from an instance of the model form submission in my views.py and subsequently pass that to the js which renders the chart. When I hardcode values into my class-based view defined variables for TAM and LTM_sales the chart renders. Please see code below: Models.py: class Strategy(models.Model): total_addressable_market = models.IntegerField(blank=True, null=True) last_twelve_months_sales = models.IntegerField(blank=True, null=True) Views.py def strategy_detail(request, id): strategy = get_object_or_404(Strategy, id=id) .... context ={ 'strategy': strategy, .... } return render(request,'hypo_app/strategy_detail.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, default=None): strategy = Strategy.objects.all() TAM = ?? LTM_sales = ?? labels = ['TAM', 'LTM Revenue'] default_items = [TAM, LTM_sales] data = { "labels": labels, "default": default_items, } return Response(data) URL from django.urls import path from .views import UserExperimentListView, ChartData from . import views urlpatterns = [ .... path('chart_data/', ChartData.as_view(), name='chart_data'), ] JAVASCRIPT within the strategy_detail.html file <script> {% block jquery %} var endpoint = '/chart_data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = … -
Integrate React in an existing Django project
I have been working on a django project for a while now and I would like to add React to it. I know there are some materials online, I have been checking them, especially the following three: link1 link2 link3 I am not an expert yet I am a bit confused which method I have to follow. I just want to add React to one of my apps first. I am kinda afraid of adding it if it would mess with other apps in my project. So, could somebody please tell/enlight me on the correct way which would allow me to have just a part of a website using Django working with React, while other parts are just working like before using js/html. If you have done this before, I also would be glad to hear your feedback and how you did it ! Thanks Cheers, Roman. -
Django - get_context_data() missing 1 required positional argument: 'form'
I am trying to add inlineformset to the Django Blog project. I got post and I want to add multiple images to the post via Class Based Views. But when I am trying to get_context_data I receive this error: get_context_data() missing 1 required positional argument: 'form' Models.py: class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='gallery/') description = models.CharField(max_length=300, blank=True) Forms.py class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['title' , 'content' ] PostImageFormSet = inlineformset_factory(Post, PostImage, fields=['image', 'description'], exclude=['post'] , max_num=30, extra=3) Views.py class PostCreateView(LoginRequiredMixin, CreateView): form_class = CreatePostForm template_name = 'blog/post_form.html' def get_context_data(self, form): context = super(PostCreateView. self).get_context_data(**kwargs) if self.request.POST: context['post_images'] = PostImageFormSet(self.request.POST) else: context['post_images'] = PostImageFormSet() return context def form_valid(self, form): context = self.get_context_data(form=form) formset = context['post_images'] form.instance.author = self.request.user if formset.is_valid(): response = super().form_valid(form) formset.instance = self.object formset.save() return response else: return super().form_invalid(form) Any idea why I am receiving this kind of error? Thank you. -
How to display Django reverse ForeignKey Data?
I have 2 models, and I want to display data through my first model, suppose Model1 have some fields and Model2 have ForeignKey of Model1, and I am getting data through Model1 on the display page, but I want to display some records from Model2 also, Please let me know how I can display data from Model2. here is my models.py file... class Model1(models.Model): namefield=models.Charfield(blank=True)class Model1(models.Model): emailfield=models.Charfield(blank=True) phone=models.Charfield(blank=True) class Model2(models.Model): name=models.CharField(default=None) type=models.CharField(default=None) father=models.CharField(default=None) model1=models.Foreignkey(Model1, related_name='model_one', on_delete=models.CASCADE) here is my views.py file... def display_data(request, id): test_display = Model1.objects.filter(pk=id).first() context = { 'test_display': test_display } return render(request, 'page.html', context) please note I am displaying data here from Model1...but I want to display name, type and father from Model2 here is my test.html file... <p>{{ test_display.namefield }}</p> <p>{{ test_display.emailfield }}</p> <p>{{ test_display.phone }}</p> <p>{{ test_display.model_one.name }}</p> <p>{{ test_display.model_one.type }}</p> <p>{{ test_display.model_one.father }}</p> these last 3 records displaying nothing -
ModuleNotFoundError: No module named 'fcntl' when I try to deploy my django project on heroku
I try to deploy my django project on heroku, and follow commands below heroku login git init git add . git commit -m "first commit" heroku create heroku git:remote -a name pip install gunicorn gunicorn application.wsgi when it comes to the latest command, error occurs: ModuleNotFoundError: No module named 'fcntl' How can I solve it? -
rest framework ManyToMany field related data get in createApiView?
i want to learn about django rest framework.how can i get many to many field related data get in CreateApiView. i have a shopkeeper create api form template. if shopkeeper select a book from option menu then the book price show in html input using ajax ? models.py class Book(models.Model): name = models.CharField(max_length=20) price = models.IntegerField(null=True) class Keeper(models.Model): books = models.ManyToManyField(Book) serializer.py class KeeperSerializer(serializers.ModelSerializer): books = serializers.SlugRelatedField(queryset=Book.objects.all(), slug_field='name') for book in books: print('selected book price:' book.price) class Meta: model = Keeper fields = ['id', 'books'] -
Webpack dev server redirects to
I am running a Webpack development server for my React single page app (Django backend). Django serves the React app from '/'. I also have a Django URL configured for '/admin' as that's where inbuilt admin section lives for the site. This works fine in production but, on development server, when I type in 'localhost:3000/admin', it gets redirected to '/' and the single page app is served. I am unable to go to any URL after slash to get a 404 error, everything gets redirected to '/' and the React app is served. Is there a way to configure the webpack development server to pass through requests after '/' to the backend, as in production? -
Django recursive serializer
Currently i'm trying to set a recursion limit of a self referentiated model, but im failing to grasp how this serialzier recursion works in Django 3.0. Currently I have 5 users and my output is as follows: { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ { "user": "user_5", "sponsor": 4, "reply_set": [] } ] } ] } ] } ] }, ... But I would like to set a limit to the recursion, giving me a tree with with the relations between the user_1 and user_4 only (between only 4 users). { "user": "user_1", "sponsor": null, "reply_set": [ { "user": "user_2", "sponsor": 1, "reply_set": [ { "user": "user_3", "sponsor": 2, "reply_set": [ { "user": "user_4", "sponsor": 3, "reply_set": [ ] } ] } ] } ] }, In the case above, the user_5 still exists and have the user_4 as it's parent, but I do not want to show him in the user_1 tree. Only the relationships between 4 users. My model # models.py class SponsorTree(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) sponsor = models.ForeignKey('self', related_name='reply_set', null=True, on_delete=models.SET_NULL) points = models.DecimalField(default=0, … -
ValidationError at /blog/addblog/ ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
This is how it shows in datepickerI have tried mostly everything but not able to find the solution. I am new to Django and basically a beginner so help me to do this. Tried many resources still the error shows up: ValidationError at /blog/addblog/ ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] In my views.py def addblog(request): if request.method == "POST": title = request.POST.get('title', '') head0 = request.POST.get('head0', '') chead0 = request.POST.get('chead0', '') head1 = request.POST.get('head1', '') chead1 = request.POST.get('chead1', '') head2 = request.POST.get('head2', '') chead2 = request.POST.get('chead2', '') pub_date = request.POST.get('pub_date', '') thumbnail = request.POST.get('thumbnail', '') add = Blogpost(title=title, head0=head0, chead0=chead0, head1=head1, chead1=chead1, head2=head2, chead2=chead2, pub_date=pub_date, thumbnail=thumbnail) add.save() que = True return render(request, 'blog/addblog.html', {'que': que}) return render(request, 'blog/addblog.html') In my models.py class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=5000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=5000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=5000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.title In my settings.py DATE_FORMAT = 'd-m-Y' DATE_INPUT_FORMATS = [ '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%d-%m-%Y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, … -
How to use Wagtail's admin widgets in custom form?
I'd really love to reuse the same widgets used in the admin part of my website made with Wagtail in my custom templates. Is there an easy way to do that ? For example : Picture of a field in wagtail's admin Will look like this when used in my html template : Same field but in my view My model currently looks like this : @slugify_field('name') class Company(models.Model): # more CharFields that I erased for brevity address = models.CharField( blank=True, max_length=255, help_text="The company's address.", ) founded = models.DateField( blank=True, null=True, help_text='The foundation year.', ) short_description = models.TextField( blank=True, help_text='A short description for the search view.', ) description = RichTextField( blank=True, help_text='A complete description for the company view.', features=['h4', 'bold', 'ul', 'link'] ) website = models.TextField( blank=True, help_text="The company main website", ) panels = [ FieldPanel('status'), FieldPanel('owner'), FieldPanel('name'), MapFieldPanel('address'), FieldPanel('founded'), FieldPanel('employees_count'), FieldPanel('contact', widget=autocomplete.ModelSelect2(url='contact-autocomplete')), FieldPanel('short_description'), FieldPanel('description'), FieldPanel('website'), FieldPanel('tags', widget=autocomplete.ModelSelect2Multiple(url='unseekable-tag-autocomplete')), FieldPanel('seeking', widget=autocomplete.ModelSelect2Multiple(url='seekable-tag-autocomplete')), FieldPanel('offering', widget=autocomplete.ModelSelect2Multiple(url='seekable-tag-autocomplete')), ] def __str__(self): return self.name class Meta: verbose_name = 'Company' verbose_name_plural = 'Companies' And my Form is like this : from django.forms import ModelForm, Textarea from wagtail.admin.edit_handlers import FieldPanel from .models import Company class CompanyForm(ModelForm): class Meta: model = Company exclude = [ 'status', 'owner', 'name', 'contact', 'slug', … -
django post_delete signal not triggered by delete foreign key object
i have a problem with my django project. I have two models: class A(models.Model): ... class B(MyFile): a = models.ForeignKey('otherapp.A', on_delete=models.CASCADE, related_name="files") thisfile = models.FileField(storage=MyStorage(), upload_to=create_path) ... I would like to delete the file if the object from class B will deleted. For this i have add a signal in the signals.py: @receiver(post_delete, sender=B, dispatch_uid='delete_b') def delete_b(sender, instance): instance.thisfile.delete(save=False) and edit the apps.py class BappConfig(AppConfig): name = 'bapp' def ready(self): import bapp.signals Now if i delete an instance of class B all works fine and the file delete also. But if i delete an instance of class A the instance of class B delete also but not the file. I think that the post_delete not triggered if the foreign key object delete. But Why? -
What the best way to create Family Tree with Django?
Is there any tutorials about it? The main goal is creation of the tree of persons (e. g. like a cards) with plus signs (or any possibility to add) that will add a different family relations to our person for every registered user. I already created a prototype of website with registration/signup/forgot_password and profile/profile_edit pages. But I don't understand where to move next. What I need to learn to achieve my goal? (javascript? some articles in django documentation? I need to use ManyToManyFields relations? more jinja implementation in html?) -
How to show users past order history in django?
I am a BCA student and new to django. I am doing my final year project in django. I am having a problem as to how to show a users all past order history. I declared two classes in models.py as OrderModel and OrderedItem. I want to show a users all order history, but whenever i run my code it shows multiple item details with a single order. Here's models.py: class OrderModel(models.Model): username = models.CharField(max_length = 150) email = models.EmailField(max_length = 254) phoneno = models.CharField(max_length = 20) address = models.TextField() timestamp = models.DateTimeField(auto_now = True) status = models.CharField(max_length = 20, default = "pending") paid = models.BooleanField(default = False) class OrderedItem(models.Model): orderid = models.ForeignKey(OrderModel, on_delete = models.CASCADE, null = True) name = models.CharField(max_length = 50) img = models.ImageField(upload_to='pics') quantity = models.CharField(max_length = 10) category = models.CharField(max_length = 30) price = models.IntegerField() total_price = models.IntegerField() Here's views.py: @login_required(redirect_field_name='login') def user_orders(request): orders = OrderModel.objects.filter(username = request.user.username) length = len(orders) if length == 0: context = {'orders': orders} else: items = OrderedItem.objects.all() context = { 'orders': orders, 'items': items } return render(request, "myorders.html", context) Here's html file: <h2 style="text-align: center">Past Orders</h2> {% if not orders %} <div> You haven't order anything yet. </div> {% … -
How can I remove the default rules of django UserCreationForm such as the password shouldn't match the personal info etc
Im working on a project for my classmates so we can interact make some events etc . so Im using Django's UserCreationForm , but it has many rules such as the password shouldn't match with personal info or it should be of more than 8 characters so how do i remove these rules. -
page view count for django detail view
I want to get the number of views to the details page, and I did, but I have a problem, Every time I refresh the page, the number of views increases. I want the view to increase only once for each user, not to increase the number of visits each time the page refresh. model: class Product(models.Model): name = models.CharField(max_length=300) create = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=True) information = models.TextField(blank=True, null=True) views = models.IntegerField(null=True, blank=True, default=0) view: def details(request, id): product_view = Product.objects.get(id=id) product_view.views = product_view.views + 1 product_view.save() return render(...)