Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django models table with foreign key
I want to give access to Messages with another table to the Message table, many users can access message. I am confused on how to declare the foreign keys class Message(models.Model): ID = models.CharField(_("ID"), max_length=140) body = models.TextField(_("Body")) permission=models.ForeignKey(Permission,on_delete=models.CASCADE,verbose_name= _("permission"),null=True,black=True) Second Table : class Permission(models.Model): #multiple users have to access to Message Users = models.ForeignKey(AUTH_USER_MODEL, related_name='access', verbose_name=_("UserWithAccess"), on_delete=models.PROTECT) -
How do i get an include template to display content from one app in another app in a django project that has several apps?
A little help please. I am working on a Django project that has different apps in it. I built an image gallery app and want to include it on the side bar of my blog article but when I use the include tag to include the html file in the blog list view page nothing shows. But the it the gallery app the image gallery shows just fine. How do I solve this issue please. This is the view.py code for the gallery app class PhotoListView(ListView): model = Photo context_object_name = 'photo_list' template_name = 'gallery/photo_list.html' class PhotoDetailView(DetailView): model = Photo context_object_name = 'photo' template_name = 'gallery/photo_detail.html' And this is the views.py code for the articles blog app class ArticleListView(ListView): paginate_by = 4 model = Article context_object_name = 'article_list' template_name = 'articles/article_list.html' class ArticleDetailView(DetailView): model = Article context_object_name = 'article' template_name = 'articles/article_detail.html'` In the articles app where the articles are displayed, I use the include tag: {% include 'includes/photo_list.html' %} But nothing shows. How do I resolve this so that I can include the image gallery in the sidebar of other apps as well? Thank you. -
CSRF verification failed. Request aborted. I kept the ta tag {% csrf_token %} still iam getting this
i have an issue on csrf token incorrect or invalid . i write the {% csrf_token %} above my form still I am getting that issue . can anyone help me in this ?? my HTML file code. <h4>register page</h4> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" name="Create User"> </form> my view.py code from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from .models import * from .forms import OrderForm from .filters import OrderFilter def registerPage(request): form = UserCreationForm if request.method=='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context={'form':form} return render(request, 'accounts/register.html', context) def loginPage(request): context={} return render(request, 'accounts/login.html', context) def home(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers= customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders,'customers':customers, 'total_customers': total_customers, 'total_orders':total_orders,'delivered':delivered,'pending':pending } return render(request, 'accounts/index.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customers(request, pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() orders_count =orders.count() myFilter= OrderFilter(request.GET, queryset=orders) orders = myFilter.qs context={'customer': customer, 'orders': orders, 'orders_count':orders_count,'myFilter':myFilter} return render(request, 'accounts/customers.html', context) def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 ) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) #form = OrderForm(initial={'customer':customer}) if request.method == 'POST': #print('Printing POST:', … -
Image is not being accessed through port 8000(under development)
My image path is working but Idk why it's not able to display it, any help is appreciated models.py class movies(models.Model): Image = models.ImageField(blank=True, null=True) urls.py urlpatterns = [ path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = 'media' home.html {% for m in movies %} <img src="{{ m.Image.url }}" width="200px", height="300px"> {% endfor %} -
Passing initial values into a form field from previous detail view
I have a detail view that shows various objects from my Word model, e.g. word in foreign language, word in English, etc. On this detail page, I want to link to a form of a different app where you can create a flashcard, but I want the values for the question and answer of the flashcard to be the values of the previous detail view, instead of the user having the fill it out from scratch. The answer to this question seems to be exactly what I need (especially te Update part of the question, since I already have the object data): Passing an initial value into a form field from previous detail view. However, it doesn't seem to work and I'm getting errors. I'm lost, I've been going in circles for days, and it seems like this should be someting that is fairly simple to do. On my detail html I have e.g.: <h1> <strong>{{object.target_word}}</strong></h1> <br> <h4>Meaning: {{object.source_word}}</h4> <br> <h4>Example sentence: {{object.example_sentence}}</h4> <br> <h4>Category: {{object.category}}</h4> <br> ... ... <div class="form"> <a id="button" href="{% url 'flash:add-card' %}" class="btn btn-primary btn-lg"> Add to Deck </a></div> And everything works fine for the detail view. I then tried to change the url above … -
Can't deploy Django + Heroku
can't run Django on Heroku. Here is my requirements.txt: antiorm==1.2.1 asgiref==3.2.7 beautifulsoup4==4.9.0 bootstrap4==0.1.0 db==0.1.1 db-sqlite3==0.0.1 Django==3.0.5 django-bootstrap4==1.1.1 django-cleanup==4.0.0 gunicorn==20.0.4 python-dateutil==2.8.1 pytz==2020.1 six==1.14.0 soupsieve==2.0 sqlparse==0.3.1 whitenoise==5.0.1 This is the Procfile: web: gunicorn --pythonpath home.wsgi And then the settings.py: ALLOWED_HOSTS = ['https://deniseandrade.herokuapp.com/', '127.0.0.1'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( STATIC_DIR, ) MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # My settings LOGIN_URL = 'login' # Heroku settings. import django_heroku django_heroku.settings(locals()) How my files are organized: Error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command -
Методы GET и POST и пересохранение данных в БД
Задача, научится редактировать базу данных в Django. проблема в том что не получается данные отправлять на сохранение, вместо этого создаются новые записи. def post_edit(request, username, post_id): author = get_object_or_404(User, username=username) post = get_object_or_404(Post, id=post_id) if request.user.username == post.author.username: form = PostForm( instance=post) if request.method == 'GET': if form.is_valid(): post = form.save(commit=False) post.author = request.author.objects.get(id=post_id) post.save() success_url = reverse_lazy('post_view') return redirect(success_url) # else: # form = PostForm(instance=post) else: return redirect("") return render(request, "new-post.html", {'form':form}) буду признателен за помощь -
Django N+1 select issue with django-filter
I have a model (SpecimenRecord) with a large number of fields, and I use django-filter to create a custom filter for my template. However, SpecimenRecord has numerous foreign key relationships, and I'm running into Django's N+1 select issue. As I continue adding objects to the database, the pageload becomes longer. I understand that using select_related can solve this issue, but because I'm using django-filter, I'm not sure how to incorporate these solutions into my filters.py file. Any help would be appreciated. Below is my (heavily abbreviated) filters.py file: from .models import SpecimenRecord from django import forms import django_filters class SpecimenRecordFilter(django_filters.FilterSet): locality = django_filters.CharFilter( field_name='locality__locality_name', lookup_expr='icontains', label='Locality' ) collector = django_filters.ModelMultipleChoiceFilter( queryset=Collector.objects.all(), """ Note: using 'SpecimenRecord.objects.prefetch_related('collector').all()' instead of what I have above does not yield the appropriate results in my template; I get a list of specimen record ids instead of the actual collectors' names """ widget=forms.CheckboxSelectMultiple ) # 15 other fields with foreign key relationships were removed for the sake of brevity class Meta: model = SpecimenRecord fields = ['locality', 'collector'] -
django model data serialization failed
I have tried to serialize django model data but returns bad results chars are encoded and are not in utf-8 format how it is possible to handle it i have tried different ways but failed: for example the following code data = serializers.serialize("json", Users.objects.all(), use_natural_keys=True) returns that but not normal utf all data are saved normally in database have checked using Django QueryDict, hope for your help [self_description": "\u041f\u0440\u0438\u0432\u0456\u0442 bbbbbbbbbbb grgregr gerger greger gbbbbbbbbbbbbbb\u0432\u0441\u0456\u043cGGG\u043f\u043c\u0432\u043c\u043a\u0443\u043f\u0443\u043agrgrgregebbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"] -
Numpy: cannot import name 'WinDLL' from 'ctypes'
I am developing a website by Pycharm and Django on Window and then I put it on Raspberry Pi. Everything is okay after I install pandas into my project. I put it on my Pi and it has an error like this -
Many-to-many relation and form with extra field
I am struggling with Many-to-Many model and form. What is the best way to show extra level field when creating a new Person with skill. I am going also to edit it later. I am trying to achieve an effect in forms like that: [input text] name [select] skill name (there are choices in the model) [input text] level of the skill Later on, I would like also to give the user a chance to add multiple sets of skill+level, maybe it is worth to think about it in advance? My models and form: class PersonSkill(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE) skill = models.ForeignKey('Skill', on_delete=models.CASCADE) level = models.CharField(max_length=50, choices=[(1, 'working'), (2, 'advanced'), (3, 'champion')], null=True, blank=True) class Skill(models.Model): name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=30, null=True, blank=True) skill = models.ManyToManyField('Skill', through='PersonSkill', blank=True) def __str__(self): return self.name class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name',) -
Within a Django template, dynamically select a QuerySet object using a JavaScript Event Listener
I'm new to Django, so forgive me if this is an obvious question. I'm trying to dynamically select an object from a QuerySet using a JavaScript Event Listener within a template. Is this possible? For context, see below. I'm using a Movie model where each row represents one movie. Each movie has its own poster URL. class Movie(models.Model): movie_title = models.CharField(max_length=250) poster_url = models.CharField(max_length=250) Here is the view associated with the template. I'm passing in the entire Movie QuerySet to the template. def index(request): all_movies = Movie.objects.all() context = {'all_movies': all_movies} return render(request, 'movie_rec/index.html', context) Within the template, I have an image for one movie. Upon clicking the image, I would like to replace the image src with a new URL according to some logic manipulating the movie id (for simplicity, I am only incrementing the id by one in this example). The idea is to continuously change the movie poster if I keep clicking on the image. However, I'm having trouble with dynamically generating a template tag (see comment in code) to update the image src. Any help would be much appreciated! <body> <img src="{{ all_movies.0.poster }}" alt="" id="poster" data-movieid="{{ all_movies.0.id }}"> <script type="text/javascript"> var poster = document.querySelector('#poster'); var … -
Form only edited on refresh - Django
The user enters data and receives the following error: "'function' object has no attribute 'id.'" Yet, when they refresh the page, the page that the form modifies has been successfully updated. Here is the section of views.py that the error is attached to. The line in question is return redirect('learning_logs:topic', topic_id=topic.id) def edit_entry(request, entry_id): """Edit an existing entry.""" entry = Entry.objects.get(id=entry_id) if request.method != 'POST': # Initial request; pre-fill form with the current entry. form = EntryForm(instance=entry) else: #POST data submitted; process data. form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topic', topic_id=topic.id) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'learning_logs/edit_entry.html', context) Here is the error: Django version 2.2.12, using settings 'learning_log.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /edit_entry/6/ Traceback (most recent call last): File "C:\Users\14254\Desktop\Programming\Projects\(Mathes) Learning Log\learning_log\ll_env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\14254\Desktop\Programming\Projects\(Mathes) Learning Log\learning_log\ll_env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\14254\Desktop\Programming\Projects\(Mathes) Learning Log\learning_log\ll_env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\14254\Desktop\Programming\Projects\(Mathes) Learning Log\learning_log\learning_logs\views.py", line 74, in edit_entry return redirect('learning_logs:topic', topic_id=topic.id) AttributeError: 'function' object has no attribute 'id' [16/May/2020 18:29:37] "POST /edit_entry/6/ HTTP/1.1" 500 68121 -
Different responses when trying to connect social accounts using rest-auth
So I'm using django-rest-auth and allauth for social logins on our server and app, and we're having some issues with the API responses on our app. Whenever a user tries to connect a social account without being logged in, we're getting different responses: WEBSITE: An account already exists with this e-mail address. Please sign in to that account first, then connect your %s account. (Comes from allauth — CORRECT response) APP: A user is already registered with this e-mail address. (Comes from rest_auth — UNWANTED response). This is causing some frustration for our app users since they don't understand what the error is. Can anybody shed any light on why this is happening? Thanks in advance. -
Solr I need to update index for every new data added
Every time a new data added , I run search and I don't see anything. Unless I have to do python3 manage.py rebuild_index or update_index. How can I automatically add newly added data by user ? I don't want a cronjob solution every 1 minute running update or rebuild index. -
Django - Form inside a Detail View not saving input?
Ive been working through function-based views which make sense, but Ive been having some difficulty with class-based views. I have a Detail View which goes to pages based on a template called city.html. Each page gives information about a city and has a comment section at the bottom which stores comments about that city. All the comments are stored in one Comment model. Now I'm trying to add a form to each page so that I dont have to add comments manually through the admin page, but so that users can type them on each page directly. Based on a previous StackOverflow question, I have written a custom get_context_data() method within my detail view. This correctly displays the form on each of the pages. However, when I press the submit button I get a 405 error: Method Not Allowed (POST). How can I go about fixing this so that the comment is saved to 'content' in the Comment model? Here is the relevant code: views.py from django.shortcuts import render from django.views.generic import DetailView from .models import City from .forms import CommentForm def home(request): return render(request, 'blog/home.html', {'title':'TIP Home'}) class CityDetailView(DetailView): model = City template_name = 'blog/city.html' context_object_name = 'cities' def … -
Jquery not functioning in Django html page
I am trying to use some Jquery to highlight some rows in a table. My project is built using Django. When I navigate to the page that has the table I can see in my logs.. [16/May/2020 18:12:43] "GET /media/row.js HTTP/1.1" 304 0 So I know the JS is getting loaded correctly. I can also look at my source and see that it is linked properly. My table is: <table class="table table-hover" id="myTable" style="table-layout: fixed; width: 100%"> <thead> <tr class="clickable-row"> <th scope="col">Property</th> <th scope="col">Expected Value</th> <th scope="col">Actual Value</th> </tr> </thead> <tbody> <tr class="clickable-row"> {% for lis in json %} <tr class="clickable-row"> {% for i in lis %} <td style="word-wrap: break-word">{{i}}</td> {% endfor %} </tr> {% endfor %} </tr> </tbody> </table> And the Jquery is: $(document).ready(function() { $('#myTable').on('click', '.clickable-row', function(event) { $(this).toggleClass('active'); }); }); I have tested that the Jquery actually works outside of my project in a Codepen. I have tried adding the Jquery directly in my page that requires it. My inspect page looks like: </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="/media/row.js"></script> </body> </html> -
Django Rest Framework JWT user register/login concept
I'm creating a Login/Register API with Django Rest Framework which is consumed by my frontend, using JWT to authenticate and there are some basic things I can't seem to understand and maybe someone can help me out. I created an endpoint to register a user (a POST to /users/). At first I was getting a "Authentication credentials were not provided." if I tried sending a request using Postman (on Django API GUI it would work normally I guess because they already send the correct authentication). However, when I think about it, it comes to me that he doesn't have the credentials yet since he's not registered and logged in, so its JWT wasn't created, so I added permission_classes = (AllowAny, ) to my APIView. But then it allows anyone to use the API, therefore anyone would be able to send a PATCH request to update some info without sending the JWT in the request. Anyone have any idea on how to handle that? I think somehow I'm lacking some kind of concept about authentication. Maybe I need one exclusively for communicating my backend and frontend that will be used to register a user and the users JWT will be used … -
How to use Django-Filter together with Django-Taggit (to filter posts by tags)?
I would like to filter my posts by tags. How could I use it together with Django filter? My current situation: #forms.py class PostForm(ModelForm): class Meta: model = Post fields = '__all__' #views.py def index(request): posts = Post.objects.all() tags = Tag.objects.all() myFilter = PostFilter(request.GET, queryset=posts) posts = myFilter.qs context = {'posts':posts, 'myFilter':myFilter, 'tags':tags} return render(request, 'posts/index.html', context) Is there a way to include tags to the forms.py? -
How to connect files in django framework?
I already finished a my graduation project in HTML,CSS and Bootstrap. And I just figured out that I have to connect it all in django project to make a registration and data forms. Now all hrefs are not working and I dont know how to connect all buttons to each other so any help about this or if there another way to link just database files to my project?? -
integer field in extended django user model not getting increment instead setting back to default value
I am new to django i am making a movie recommendation website the problem i am facing is with the integer fields named after movie genre inside django user extended model, i want them to increment if a user give a review on particular genre movie, each time i try to increment them in views.py funtion its set back the all integers fields to default and only increment to the current genre integer filed, and if user giving the review on same movie genre again then it increment it without problem but if its a different genre then again all previous genre got reset to default and only increment to new genre movie integer field, i am using signals in project models.py class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) image=models.ImageField(default='default.jpg',upload_to='profile_pics') genre_drama = models.IntegerField(default=0) genre_animation = models.IntegerField(default=0) genre_thriller = models.IntegerField(default=0) genre_documentary = models.IntegerField(default=0) genre_comedy = models.IntegerField(default=0) genre_adventure = models.IntegerField(default=0) genre_romance = models.IntegerField(default=0) genre_action = models.IntegerField(default=0) def __str__(self): return f'{self.user.username} Profile' views.py def handleReview(request): movies = movie.objects.all() if request.method == 'POST': username = request.POST['username'] pass1 = request.POST['pass1'] id_m=request.POST.get('dropdown1') print(id_m) #getting the movie id to add it in genere id = movie.objects.filter(movie_name__istartswith=id_m).values_list('id', flat=True).first() print(id) matchingMovid = movie.objects.get(movie_name=id_m) print(matchingMovid) genre=matchingMovid.genre print(genre) review_m = request.POST['review'] user = authenticate(request, username=username, … -
How can I show/hide a HTML <form> with a python (django) function?
I'm trying to develop a web Todo list using python (3.8.2) with django (3.0.6); I want to hide/show a HTML using python (it is inside a with other forms), but I really don't know how to do it. Can someone help me? <form action = 'show_hide/' method = 'POST'>{% csrf_token %} <input type="text" name = 'content_2' class="form-control" placeholder="Task" style = 'box-shadow: none; border-color: transparent;' autofocus wrap required> <button type="submit" class="btn btn-dark mt-2 mb-2" name = 'edit' onclick = 'edit_task()'>Edit Task</button> </form> -
Is it possible to avoid parent reference on a child object in one_to_many relationship? SQLAlchemy
Consider two tables: User and Calculation. Calculation's structure: {“id”: <primary_key>, “array”: <array of numbers>, “calculations”: <array of all calculations for given array of numbers>} User creates those calculations. My task is to implement a solution which will return all User's calculations. Problem is, I don't know how to do it without changing Calculation's structure by making a one to many relation between User and Calculation. I was thinking about defining Calculation as a JSON field on User table, but one of task's requirements is also to implement Admin user which will be able to see all calculations. So this approach seems bad to me. Is this possible, and if it is, how? -
REST framework basename missing in reversing action url
I have this viewset with a custom action added @permission_classes([IsStaffUser]) class MacroViewSet(viewsets.ModelViewSet): queryset = Macro.objects.all() serializer_class = MacroSerializer http_method_names = ['get', 'post', 'patch', 'head', 'delete'] @action(methods=['post'], detail=True, url_name='add-student') def add_student(self, request, pk=None): pass Registered in urls.py as # application namespace app_name = 'appname' router = routers.DefaultRouter() router.register(r'users', UserViewSet, basename='user') router.register(r'students', StudentViewSet) router.register(r'macro', MacroViewSet, basename='macro') urlpatterns = [ re_path('^', include(router.urls)), ] Now, I'm trying to test my custom action. Of course I need its url. Following the drf guide, I've kwnow of the existence of reverse_action method. In my test case, I use that method as following self.url = MacroViewSet().reverse_action('add-student', args=['1']) Unfortunately, I keep getting this error > self.url = MacroViewSet().reverse_action('add-student', args=['1']) E AttributeError: 'MacroViewSet' object has no attribute 'basename' -
How can I solve a conflict between to js/jquery files?
I am building a little website with Django and Bootstrap3 CSS. So far, everything is fine and I have some menus which use data-toggle for a dropdown, which can also collapse on the second click. In my base.html I have this code at the end: <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script> <!--<script>window.jQuery || document.write('<script src="../../../boot/js/jquery.min.js"><\/script>')</script>--> <script>window.jQuery || document.write('<script src="{% static "boot/js/jquery.min.js" %}"><\/script>')</script> <script src="{% static 'boot/js/bootstrap.min.js' %}"></script> This works for me, even as I am not experienced with js or jquery. Now I wanted a little widget to add datepicker plus for one of my forms. And there comes the conflict. According to https://pypi.org/project/django-bootstrap-datepicker-plus/ I have to add {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full'%} {{ my-form.media }} to my template. When I do this the bootstrap_css breaks my page design. When I disable that line everything looks fine at first glance. And the datepicker widget works. However, the dropdown menus do not work anymore. I guess that the multiple script includes are responsible for that, but I do not know enough about it, how to solve this. I …