Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to call __init__ in abstract model?
I have a abstract model: @python_2_unicode_compatible class BaseModel(TimeStampedModel, SoftDeletableModel): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='%(class)s_wallet', on_delete=models.CASCADE ) first_field = models.CharField(max_length=5) second_field = models.CharField(max_length=10) def __init__(self): super().__init__() self._set_default_value() ... def _set_default_values(self): first_field = self.__class__._meta.get_field('first_field') second_field = self.__class__._meta.get_field('second_name') if self.__class__.__name__.lower().startswith('some'): first_field.default = 'some value' second_field.default = 'some value ... and several models that are inherited from it @python_2_unicode_compatible class SomeModel(BaseModel): pass But when I try to makemigrations, I get a message stating that No changes detected. What am I doing wrong? Why is the inor method not called? -
django input value in paginator set and read user entered input
I am working on widget for paginator in django framework. I have the following in the template When navigating by default the value should be shown as page number, if user enters a specific page # it has to navigate to that page number. I am setting value for input box using paginator.number from django Paginator, and if user enters then how can I read that value? since it was already set value as paginator.number which shows up page# but how to read a user entered value. I have added <input type="text" OnChange="location.ref='?page={{paginator.user_entered}}'" value ={{paginator.number}} > First << [input-textbof] >> Last -
Pass context into a template using Ajax, Django
I have one view that I'm trying to display data from a few different places to. My thought would be to do this via Ajax since I won't have a way to execute 3 or 4 urls when this page loads. I'm able to get the data to the page using the Django Rest Framework and I can view the correct data in the console with my ajax request. I just don't know how to get that data into my html template to start displaying it. Normally I would just pass the context through the view but this is uncharted territory. I think i'm missing something very small with Jquery as I'm pretty new to javascript and Jquery. views.py class LoadLaneHistoricalCarriers(APIView): authentication_classes = () permission_classes = () def get(self, request, pk): load = Load.objects.get(pk=pk) load_state = load.shipper.state load_equipment_type = load.equipment_type historical_loads_in_state = Load.objects.filter(shipper__state=load_state) carriers = CarrierCompany.objects.filter(state=load_state) historical_carriers = [] historical_loads = [] for load in historical_loads_in_state: historical_loads.append(load.id) historical_carriers.append(load.carrier.name) data = { 'historical_loads': historical_loads, 'historical_carriers': historical_carriers } return Response(data ) Template this is a modal in case it matters. <script> var endpoint = '/carrier_notifications/load/historical_carriers/400192/data/' $.ajax({ method: "GET", url: endpoint, success: function (data) { carriers = data.historical_carriers console.log(carriers) //This works }, error: … -
how create calandar in django and html and javascript
I want to create a complete calendar and then choose a date of this calendar to use this date in my program the calender must be on the interface every day -
nginx,uwsgi - load on startup
I wanted to execute a ini file on startup. So I created a file /etc/init/uwsgi.conf with # simple uWSGI script description "uwsgi tiny instance" start on runlevel [2345] stop on runlevel [06] respawn exec uwsgi --ini /home/iiits/Mahimusic/mahimusic.ini But this did not execute when I rebooted the system.Can I know why? -
Django Chartit graph not displaying. Jquery issue?
There are about another 4-5 other posts with the same issue I have but either a.) the solution does not work for me or b.) there are no suggested solutions. I'm hoping someone can help me out with this. Using Chartit and looks like I am passing my object's data properly and I've got my template hitting all the necessary JavaScripts finally and now I am getting this issue from the console: VM49842 chartloader.js:3 Uncaught ReferenceError: $ is not defined at VM49842 chartloader.js:3 highcharts.js:10 Uncaught Error: Highcharts error #13: www.highcharts.com/errors/13 at Object.a.error (highcharts.js:10) at a.Chart.getContainer (highcharts.js:250) at a.Chart.firstRender (highcharts.js:265) at a.Chart.<anonymous> (highcharts.js:241) at a.fireEvent (highcharts.js:30) at a.Chart.init (highcharts.js:240) at a.Chart.getArgs (highcharts.js:239) at new a.Chart (highcharts.js:239) at Object.<anonymous> (VM49842 chartloader.js:5) at Function.each (jquery.1.7.2.min.js:2) Here is the line in reference to chartloader.js line 3: $(document).ready(function() I've read that it could possibly be interfering with other scripts but I've got no other javascript on my Django project besides what's included in the admin portal. Settings.py has 'chartit' in installed apps and because I've also heard that scripts could be loading slower than expected from https I've installed them all locally in my static directory and I've run 'python manage.py collectstatic' to install/move them … -
AttributeError on a test case without using print
I am fairly new to Python/Django and I am self taught, so perhaps I am missing something fundamental here... I am trying to write a test case for Model Form in Django. I create an instance of my form, which I can print to see how Django renders the form. Using form.cleaned_data also works, returning the values of the form. bulk_image_form = BulkTestForm(data={'daisy': 3, 'dandelion': 0, 'tulips': 0, 'sunflowers': 1, 'roses': 0}) test_form = bulk_image_form print(test_form) print(test_form.cleaned_data) However, as soon as I remove the first print statement (print(test_form)), the test_form.cleaned_data no longer works. The console reads the following: AttributeError: 'BulkTestForm' object has no attribute 'cleaned_data' Why would a print statement have an impact on accessing the attributes of an object? -
Disconect models signals in test mode
everyone. Is there any way to disconect models signals in test mode Django 1.11? Or maybe create an object without orm to prevent dispathing signal fron post_save method. thx for help -
run Django with uWSGI in a Anaconda environment
I use a virtual environment, with Django installed, located in the ~/minconda3/envs/MYENV directory, to change to our project's directory, and to use the wsgi.py file stored within the inner MYAPP directory to serve the file with: uwsgi --http :8080 --home /home/USER/miniconda3/envs/MYENV/ --chdir /home/USER/sites/MYAPP -w myapp.wsgi However, this returns that the module is not installed: ModuleNotFoundError: No module named 'django' So the global anaconda is user instead and the --home (or -H) command is failing -
Make 2 Divs side by side Html Django
My problem is that I can't place 2+ divs in a single line . I can't use float because I have an unstable number of divs (A div for every post in django ) This is the code I am using : Index.html <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static "Css/indexstyle.css" %}"> <title>Temporary</title> </head> <body> {% for post in posts %} <a href="#"><div class="cl1"> <img src="{% static 'Img/img.jpg' %}" id="picture"> <center>{{ post.title}}</center> </center> </div></a> {% endfor %} </body> </html> indexstyle.css .product { height: 350px; width: 250px; background-color: #E5E5E5; border-radius: 10px; margin-right: 2em; float: left; } img{ height: 200px; width: 250px; border-radius: 10px 10px 0px 0px; } a{ text-decoration : none; color: inherit; } -
slow django project on heroku
I have a django application which works well and I uploaded the application to the web with heroku cli but i noticed a lot of issues which I would appreciate if assisted. The application takes a long time to load when in use. The application's static files is store in amazon s3 but when loading up, the images do not load up and as a result the images don't get displayed but the image path is correct and if I click on the image link , it gets displayed. I use font awesome which works well in the development mode but the moment I put it on heroku it stopped showing up and was showing broken icons. I am using heroku hobby-dev and everything I am using currently is free since the app is in beta stages so if I have to upgrade anything kindly put me through -
Django: ManyToMany association name not defined
this is my models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from userprofiles.models import UserProfile # Create your models here. import os class Category (models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Image(models.Model): owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) in_gallery = models.ManyToManyField(Gallery) title = models.CharField(max_length=100) def __str__(self): return self.title class Gallery(models.Model): name = models.CharField(max_length=100) have_images = models.ManyToManyField(Image) def __str__(self): return self.name class ImageInGallery (models.Model): image = models.ForeignKey(Image) gallery = models.ForeignKey(Gallery) line 22, in Image in_gallery = models.ManyToManyField(Gallery) NameError: name 'Gallery' is not defined I want to have manytomany relation for Image and Gallery and class ImageInGallery to store the Image~Gallery relation sets. also, I want images belonging to a certain gallery accessible from a gallery and vice versa, so I put both models.ManyToManyField(Gallery) and models.ManyToManyField(Image) in both classes whats the reason of the error: line 22, in Image in_gallery = models.ManyToManyField(Gallery) NameError: name 'Gallery' is not defined -
post function in django formview not called when jquery post is used
I have to call SearchView when "search" button is clicked. With a few print statements, I could see that SearchView is being called but post function in the SearchView is not called. Below is the code I have used in SearchView: class SearchView(FormView): template_name = 'search.html' #form_class = SearchForm success_url = ‘/mypage/downloadresult' print(" i am inside SearchView") def post(self, request, *args, **kwargs): # form = self.form_class(request.POST) form_class =SearchForm form = self.get_form(form_class) # form_class = self.get_form_class() # form = self.get_form(form_class) print(" i am inside post") if form.is_valid(): if self.request.is_ajax(): // handle form and generate result Below is the display view for my form: class DisplayView(FormView): template_name = 'search.html' form_class = SearchForm print(" i am inside displayview") success_url = ‘/sampleapp/search' When the form is displayed using the DisplayView above, once the user clicks on "search" button "SearchView" is called on successful form post. Url patterns in sample app urlpatterns = [ #url('',SearchView.as_view()), #url('', SearchView.as_view()), url('',displayformview.DisplayView.as_view(),name='displayview'), url(r'^search/$',SearchView.as_view(),name='search'), url(r'^downloadresult/$',downloadresultview.DownloadResultView.as_view(),name='downloadresult') ] urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(‘sampleapp.urls')), ] Below is the jquery i am using: $('#search').click(function(){ $.post('/sampleapp/search', $(this).serialize(), function(){ //alert("submit called") }) .done(function(){ alert("done") }) }) I am new to jquery and django. So, I am not sure if the above jquery is acutally … -
Updating a variable value of a user object in Django
I am trying to implement some functionality that allows a user to edit their personal information in a Django project using Django forms. When a user enters the new value in the form and hits enter, they are brought back to the main profile page which is correct however, the values remain the same as before. Below is how I have tried to implement the functionality: Forms class UpdateProfile(forms.ModelForm): email = forms.EmailField(required=False) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) age = forms.IntegerField(required=False) height = forms.IntegerField(required=False) weight = forms.IntegerField(required=False) class Meta: #Here are the fields that i want editable model = User fields = ('email', 'first_name', 'last_name', 'age', 'height', 'weight') #Here im trying to commit the changes to the user and return the user def save(self, commit=True): super(UpdateProfile, self).__init__(commit) if commit: user.save() return user Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('account/profile.html')) else: form = UpdateProfile() args['form'] = form return render(request, 'account/edit_profile.html', args) HTML % block head %} <title>Profile</title> {% endblock %} {% block body %} <div class="container"> <form method="POST" action="{% url 'account:profile' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> <br> </div> {% endblock %} -
Django: Get current username in model field as default value
# models.py from django.db import models from django.contrib.auth.models import User class SiteInfo(models.Model): site_owner = models.OneToOneField(User, on_delete=models.CASCADE, ) site_url = models.CharField(max_length=40, unique=True, blank=False, default= site_owner, ) How to make "site_url" default value = User.username or site_owner instance? -
In Django, how can I average the difference in time between two datetime fields?
I have a model with two datetime fields on it. class LogPost(models.Model): created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I want to query to get the average time between created and modified. For this I tried: updated = ExpressionWrapper( F('modified_at') - F('created_at'), output_field=fields.DurationField()) updated_average = models.LogPost.objects.all().annotate(updated=updated ).aggregate(Avg('updated')).get('updated__avg', 0) which gave me the error: File "/project/apps/data/views.py", line 622, in get ).aggregate(Avg('updated'))).get('updated__avg', 0) File "/project/lib/python3.5/site-packages/django/db/models/query.py", line 358, in aggregate return query.get_aggregation(self.db, kwargs.keys()) File "/project/lib/lib/python3.5/site-packages/django/db/models/sql/query.py", line 469, in get_aggregation result = compiler.apply_converters(result, converters) File "/project/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 792, in apply_converters value = converter(value, expression, self.connection, self.query.context) File "/project/lib/python3.5/site-packages/django/db/models/expressions.py", line 283, in convert_value return float(value) TypeError: float() argument must be a string or a number, not 'datetime.timedelta' How can I average these datetime.timedelta objects at the database level rather than through iteration after they are returned? -
how to create django super user in docker container
I am trying to create a django super user in docker container with the password (it should prompt the user to enter a password). Any suggestions would be helpful! -
How to submit comment form in Django
I'm coding a new website.Now I'm coding the news_detail.html.There is a comment function in this page for people to comment to the news. But I can't submit the comment successfully. Here is my news/urls.py: path('-<int:news_pk>', NewsDetailView.as_view(), name="news_detail"), Here is the news/views.py: class NewsDetailView(View): def get(self, request, news_pk): news = News.objects.get(id=int(news_pk)) title = news.title author = news.author_name add_time = news.add_time content = news.content category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) return render(request, 'news_detail.html', { 'title': title, 'author': author, 'add_time': add_time, 'content': content, 'tags': tags, 'category': category, 'all_comments': all_comments }) def post(self, request, news_pk): comment_form = CommentForm(request.POST) if comment_form.is_valid(): comments = comment_form.cleaned_data.get("comment") comment = NewsComments(user=request.user,comments=comments,news=News.objects.get(id=news_pk)) comment.save() comment_form = CommentForm return render(request, "news_detail.html", { 'comment_form': comment_form }) Here is the CommentForm: def words_validator(comment): if len(comment) < 5: raise ValidationError("您输入的评论字数太短,请重新输入至少5个字符") class CommentForm(forms.Form): comment = forms.CharField(widget=forms.Textarea(), validators=[words_validator]) And here is my news_detail.html: <form method="post" action="news_detail.html"> <div class="form-group"> <label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5></label> <textarea id="js-pl-textarea" class="form-control" rows="4" placeholder="我就想说..."></textarea> {% if request.user.is_authenticated %} <div class="text-center mt-3"> <button type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button"> 发表评论 </button> {% endif %} </div> </div> {% csrf_token %} </form> Acturaly after I add some comments in admin,I can render the comments in the html successfully.But when I try to submit the … -
Django retrieve data from two tables
i have the following model: class Purchases(models.Model): p_id = models.IntegerField(primary_key=True, default=0) date = models.DateField(default=datetime.now) def __str__(self): return self.date.strftime('%Y-%m-%d') class Meta: verbose_name_plural = "Purchases" class Purchased_Items(models.Model): p_id = models.ForeignKey(Purchases, on_delete=models.CASCADE) item = models.CharField(max_length=80) size = models.IntegerField(max_length=2) quantity = models.IntegerField(max_length=3) price = models.IntegerField(max_length=4) total = models.IntegerField(default=0) def __str__(self): return self.item class Meta: verbose_name_plural = "Purchased Items" I am trying to retrieve using inner join: pur = Purchased_Items.objects.all().select_related() But i am not getting the required result. Basically I want the following sql: select * from finance_purchases as fp inner join finance_purchased_items pi ON (fp.p_id = pi.p_id_id); another question is although the foreign key in Purchased_Items is p_id but in the column in sql table is p_id_id! why? What is the logic behind it? Thanks -
Implementing Private Messaging In Django
So I decided to create my own private messaging app for my project. I couldn't find any good examples or tutorials in Django that had something like this implemented so I'm not sure if this is the "proper" approach. Right now I created a view that is responsible for getting the messages organized the way I wanted as well as listening for post requests to update the model. def get_message(request,matched_username): ##Do All The Message Queries And Get Back A DICT Of Messages if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): match = Message Object post = form.save(commit=False) post.reciever = matched_username post.successmatch = match post.save() else: form = PostForm() return render(request, 'messages.html', {'form': form,'all_messages':all_messages}) So when a user submits the message it goes into the Database with no issue, but now I realized that I'm going to have to refresh the page, so, all in all, I'm going to have to use Jquery/Ajax to request the updated message database. I'm also going to have to set up a jquery request on timed intervals to check for messages in general so I feel like there's going to be a whole lot of jquery requests sent to the database checking for new … -
How can I change django timeuntil format?
If it remains 8days until May 2, then timeuntil format is 1 week, 1 day. I want to change this "1 week, 1 day" to "8 day". How can I change it? -
Why do I get function undefined error from html doc?
I have written a small chat app. At first, all the code was contained in the one HTML document, and worked ok. After seperating the CSS, HTML, and JS into seperate files. The function, register_popup, invoked from within the HTML doc, now gererates; "ReferenceError: register_popup is not defined" I can see that the script is loading and from the developer tools I see no issues, all 200's and 302's. THE HTML <div class="sidebar-name"> <a href="#" onclick="register_popup('user4', 'USER4');"> <img width="30" height="30" src="" /> <span>user4</span> </a> script can be seen loading... Am using, <script> var url = "static/js/chatpop.js"; $.getScript(url); </script> Have alos tried changing the HTML: <div class="sidebar-name"> <a href="javascript:register_popup('user3', 'USER3');"> <img width="30" height="30" src="" /> <span>user3</span> </a> </div> but that does not work either. As mentioned, I get a 200 on loading the script, and when contained in the same page everything worked. Only after separating the code into respective files does the error happen, The following can also be seen loading ok. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3 /jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> Any help welcome ... -
Django : query a many to many relation
I'm stuck with manytomany relations in Django. Here are my models : class Actors(models.Model): name = models.CharField(verbose_name="Actor's name", max_length=128) # other stuff class Meta: verbose_name = "Actor" ordering = ["name"] def __str__(self): return self.name class Movies(models.Model): title = models.CharField(verbose_name="Movie's title", max_length=128) casting = models.ManyToManyField("models.Actors", verbose_name="Actors") # other stuff class Meta: verbose_name = "Movie" ordering = ["title"] def __str__(self): return self.title I'm looking to print all the movies played by one actor. So in my actor's views I got : def actor(request, id): actor = get_object_or_404(Actors, id=id) # Trying to get the movies played by the actor # -> goal : filter the casting field and compare # the actors_id in movies_movies_actors to # the id parameter movies = Movies.casting.filter(actors_id=id) return render(request, 'actors/actor.html.twig', {'actor': actor, 'movies': movies}) I don't find the right way to access the casting field and get all the rows where 'id' appears. Can you help me ? Thx -
Chart.js with JQuery not woking offline in django
I'm new to django and jinja. I've been trying to make all CDNs work offline by downloading them and putting them in static folder of my app. Here is a snippet... {% load static %} <script src="{% static 'Chart/Chart.bundle.js'%}"></script> <script src="{% static 'Chart/Chart.bundle.min.js' %}"></script> <script src="{% static 'Chart/Chart.js' %}"></script> <script src="{% static 'Chart/Chart/Chart.min.js'%}"></script> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" type="text/css"> <script src="{% static '/jquery/3.3.1/jquery.slim.min.js' %}"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> The same code with the jquery line replaced to <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script> works pefectly fine. The app loads a graph dynamically. I use Chart.js and bootstrap. I used django's development server. When I go to the source html code generated and click on the static link generated for jquery, it displays the same code that the official cdn link does!!! How do I make this work? -
Url with two pk augments returning error "Reverse for 'post_detail' with arguments '(<Story: Story 1>, '')' not found. 1 pattern(s) tried:
Sorry if this is basic but I am very new at this. I'm trying to create a link with two arguments in it, the second argument seems to be working, but the first returns this error: Reverse for 'post_detail' with arguments '(<Story: Story 1>, '')' not found. 1 pattern(s) tried: ['story\\/(?P<work>[0-9]+)\\/post\\/(?P<pk>[0-9]+)\\/$'] from django.urls import path from . import views urlpatterns = [ path('', views.StoryListView.as_view(), name='home'), path('story/<int:pk>/', views.PostListView.as_view(), name='story_overview'), path('story/<int:work>/post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), ] This is the template. This displays all of the posts in a story, and the link should take you to another page that shows a single post. The work argument is the id of the sotry from the Story table (which is also present in the Post table) {% extends 'base.html' %} {% block content %} {% for posts in object_list %} <h2><a href="{% url 'post_detail' work post.pk %}">{{ posts.title }}</a></h2> <p>{{ posts.body }}</p> {% endfor %} {% endblock content %} These are my views: from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView from . models import Post, Story class StoryListView(ListView): model = Story template_name = 'home.html' class PostListView(ListView): template_name = 'story_overview.html' def get_queryset(self): self.work=get_object_or_404(Story, pk=self.kwargs['pk']) return Post.objects.filter(work_id=self.work) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['work'] = self.work …