Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_tables2 is not a register tag library error
I am trying to install django_tables2 but when I used it in the templates, it gives me this error: 'django_tables2' is not a register tag library. Any idea as to what is wrong. Installed app: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', options: 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', view.py: from .get_data import get_data from .tables import SummaryTable def get_variables(request): data = get_data() table = SummaryTable(data) context = {'table': table} response = render(request, 'index.html', context) return response templates: {% extends 'base_template.html' %} {% load django_tables2 %} {% load static %} <!-- HEAD --> {% block head %} {% endblock %} <!-- END HEAD --> {% block page_content %} {% render_table table %} {% endblock %} {% block scripts %} {% endblock %} -
how to inherit alternative constructor
hi stack overflow community. i am trying to inherit alternative constructor from my parent class and add one more argument in my alternative constructor in anthoer clss but i can't figure out how to do it. # Python Object Oriented Programming import datetime class Employee: num_of_emps = 0 # Class Variable raise_amount = 1.02 # Class Variable def __init__(self, FirstName, LastName, salary): self.FirstName = FirstName self.LastName = LastName self.salary = int(salary) self.email = FirstName + "." + LastName + "@email.com" Employee.num_of_emps += 1 # Class Variable def FullName(self): return "{} {}".format(self.FirstName, self.LastName) def apply_raise(self): self.salary = int(self.salary * self.raise_amount) @classmethod def set_raise_amount(cls, amount): cls.raise_amount = amount @classmethod def from_string(cls, emp_str): first, last, salary = emp_str.split("-") return cls(first, last, salary) @staticmethod def is_workday(day): if day.weekday() == 5 or day.weekday() == 6: return False else: return True class Developer(Employee): def __init__(self, FirstName, LastName, salary, prog_lang): super().__init__(FirstName, LastName, salary) self.prog_lang = prog_lang @classmethod def from_string(cls, dev_str): first, last, salary, prog_lang = dev_str.split("-") return cls(first, last, salary, prog_lang) -
passing Java script variable to Django
i wanna pass js var (tasks) to my django view as follow but out put is NONE. I've also tried tasks=request.POST('a[]') but it says that 'QueryDict' object is not callable. this is my html code: <head> <title> JavaScript | Set the value of an input field. </title> set value {% csrf_token %} click to set </p> <script> var a= ["Saab", "Volvo", "BMW"]; function gfg_Run() { var tasks = 2; $.ajax({ type: 'POST', url: 'main/momentconnections/bfp', data: {'tasks[]': tasks}, }); } </script> and this is my view: def testdel(request): if request.method == 'POST': tasks = request.POST('tasks[ ]') print("hello") print("count status ", tasks) print (type(tasks)) else: print('shit') return render(request, 'testdel.html') but out put for tasks is NONE. can anyone help me with this issue? -
How to assign ForeignKey value to the logged in user name in django?
I have two models NotesModel that has two fields userFromModel which is a one to one field to the django built in User model from django.contrib.auth.models , and a name field which is just a CharField and a Notes model that has several fields related to my notes app like title,matter etc, it also has a notesOf field that has ForeignKey relation with the NotesModel. when a user register/logins this Note app and try to add new note, i was expecting the notesof foreignkey field to have the value of registered/signed in username or say when person john sign in and create a new note,the i was able to create a new note object of Notes model,but the notesof field of the Notes model is not having the loggedin or say the person who created that note,i was expecting the forgienkey to have the person who is saving the note. views.py def newNotePage(request): form = NewNote user = request.user if request.method == 'POST': form = NewNote(request.POST) if form.is_valid(): obj = NotesModel.objects.get(userFromModel_id=user.id) #i tried this below code to create notesof field to the user obj.notes_set.create(notesOf=user) #but the result was empty see the attachment image form.save() return redirect('welcome') context={'form':form} return render(request,'todoapp/new_note.html',context) models.py … -
Python Django Admin not showing CSS
I was working with Django latest version by watching a tutorial on YT, but for some reason, my admin page isn't coming how it has to. It does not have a style or CSS. -
Django login button turned to be logout after user logged in
I want to create a button which can switch between login/out The button part on home.html: <li class="nav-item text-white"> {% if request.user.is_authenticated %} <a class="nav-link text-black font-weight-bold" href="{% url 'home' %}">Logout</a> {% else %} <a class="nav-link text-black font-weight-bold" href="{% url 'home' %}">Login</a> {% endif %} </li> But I have no idea how to set with my views.py as it only show logout on home.html def login_views(request): next = request.GET.get('next') form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) if next: return redirect(next) return redirect('/') context = { 'form': form, } return render(request, "login.html", context) def home(request): return render(request, 'home.html') -
How to return data from databse in Django?
BACKGROUND INFO Currently I am making a project in Django (Online system for students and teachers), I have finished frontend, but I have run into a problem with backend. So when I try to export data from one of the models, it returned none. CODE Relevant part of the models.py: from django.db import models class Ustanova(models.Model): skola = models.CharField(max_length = 10) programu = models.CharField(max_length = 50) slika = models.CharField(max_length = 1000) def __str__(self): return self.skola + '-' + self.program_u class Razred(models.Model): ustanova = models.ForeignKey(Ustanova, on_delete = models.CASCADE) programr = models.CharField(max_length = 50) razredr = models.CharField(max_length = 10) is_take = models.BooleanField(default = False) def __str__(self): return self.razred_r + '-' + self.program_r Relevant part of views,py: def _class_chooser(request, name): ustanova = get_object_or_404(Ustanova, skola = name) razred = Razred.objects.filter(razredr__startswith = name).all() context ={ "ustanova" : ustanova, "razred": razred, } url is in format: path('<str:name>/', views._class_chooser, name ="class_chooser"), So www.example.hr/students/XVG/ is page for students of XVG (class chooser page). And let's say that data is html file is represented with ul/li: <ul> {% for i in ustanova.razred_set.all %} <li><a href ="{% url 'students:class_menu' razred.razredr %}"> {{ razred.razredr}} - {{ razred.programr }}</a></li> {% endfor %} </ul> ISSUE Now we are coming to the issue, in … -
Django: Book name and image is not displayed
Base.html file. The could was properly working before bootstrap theme {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static '/books/style.css' %}" > <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'books:index' %}">The Bookstore</a> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Books </a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="{% url 'books:book-add' %}"> <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add Book </a> </li> <li class=""> <a href="{% url 'books:index' %}"> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout </a> </li> </ul> </div> </div> </nav> {% block body %} {% endblock %} </body> </html> This is a index html file used to display book name and the name of the book is not displayed instead it displays {{book.name}} and not displaying book_image as well. The database is created and stored than too it is not displaying. index.html {% extends 'books/base.html' %} {% block body %} <link rel="stylesheet" href="books/style.css"> <div class=" col-md-12 jumbotron"> <h1>The Bookstore</h1> <p>Collection of all popular books</p> </div> <div class=" col-md-10 jumbotron jumbotron-special" name="fig"> <div class="col-md-12 span-2"> <h2>Popular Books</h2> </div> </div> <ul> {% for book in object_list … -
get updated object with ajax
get updated object with Ajax i get objects with Ajax but i need to update Objects before send zoomEstate = [] for foo in estate: if foo.lat >= lat - 0.1 and foo.lat <= lat + 0.1: if foo.long >= lng - 0.1 and foo.long <= lng + 0.1: username = {"username": foo.user.username} for i in username: setattr(foo, i, username[i]) foo.save() zoomEstate.append(foo) print(zoomEstate[0].username) estate_json = serializers.serialize('json', zoomEstate) estate_list = json.loads(estate_json) return HttpResponse(json.dumps(estate_list)) i can get updated object with print in view but after send i don't see username in template console -
Django ManyToManyField query equalivent to a list
I have a list of objects and a model includes ManyToManyField of this object. I'd like to get objects who have the same list of objects in this field. that's means __in won't work because he will do OR between the objects in the list and not AND. I was trying using the AND Q Lookup, but it didn't work (after checking the .query text, it seems that he doing the AND inside the field object, instead of the object itself, so obviously the field object id don't have two different ids..) here's the interceptor I played with results_query_set[0] <Results: Results object (2)> results_query_set[0].users.all() <QuerySet [<User: test_user>, <User: test_user_2>]> users [<User: test_user>, <User: test_user_2>] users_q <Q: (AND: ('users', <User: test_user>), ('users', <User: test_user_2>))> results_query_set.filter(users=users[0]) <QuerySet [<Results: Results object (2)>]> results_query_set.filter(users=users[1]) <QuerySet [<Results: Results object (2)>]> results_query_set.filter(users_q) <QuerySet []> results_query_set.filter(Q(users=users[0]) & Q(users=users[1])) <QuerySet []> and the result results_query_set.filter(users_q).query.__str__() reproduce is 'SELECT "results_table"."id", "results_table"."date", "results_table"."lookup", "results_table"."value" FROM "results_table" INNER JOIN "results_table_users" ON ("results_table"."id" = "results_table_users"."widgetresults_id") WHERE ("results_table_users"."user_id" = 1 AND "results_table_users"."user_id" = 2) I can chain .filter for each user, but of course, I'd like to make one query instead of queries by the numbers of my input. -
How to use video in django?
can anyone suggest me how to use video in django application? I tried different ways but didn't work. <source src="/home/sahil/Desktop/LearnHtmlCss/MyLearnHtml/media/DanceMonkey.mp4"type="video/mp4"> </video>``` even i used ```{% media 'DanceMonkey.mp4' %}``` I have setup my media files in seetings.py ```Media_Dir = os.path.join(BASE_DIR,'media') MEDIA_ROOT = [Media_Dir,] MEDIA_URL = '/media/'``` under my urls.py ```+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)``` -
Django Form ClassBasedView
I want to give context to template without form fill(if user only check a page).How can i make this views.py def ContactView(FormView): template_name = 'decision/residentialInteriors.html' form_class = EmailForm success_url = 'decision/residentialInteriors.html' success_message = "Письмо успешно отправлено" def form_valid(self, form, rmslg, stslg): email = form.cleaned_data['email'] send_mail('Caparol_Center_Spb', 'Теперь вы будете получать лучшие предложения шоу-рума', email, [email, ], fail_silently=False,) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self.request, success_message) Customer.objects.create(email=email, room=rmslg, style=stslg) all_rooms = Room.objects.all() selected_room = Room.objects.get(slug=rmslg) styles = selected_room.styles.all() style = Style.objects.get(slug=stslg) return redirect(reverse('decision/residentialInteriors.html', {"style": style, "all_rooms": all_rooms, "styles": styles, "selected_room": selected_room})) urls.py app_name = 'decision' urlpatterns = [ path('livingrooms///', ContactView.as_view(), name='style'), ] -
Django's Generic Relationship VS Django REST
In order to keep two of my Apps decoupled I'm wondering which one would be best approach. In one hand, I could try to implement this using Django's Generic Relationships or using Django REST and thus creating an API for each of those Apps. I'm really trying to grasp points positives and negatives for each aproach. Could someone contribute with thoughts? -
Associating user with List View Django Rest Framework
Making an app that displays tax deductions for logged in users. How do I display a list for deductions that specific user has created? This is what I've come up with so far but it only is a detail view. Can't seem to find any methods that allow this for class based views, so I'm assuming that this must be done with function based views. Please correct me if I am mistaken. views.py @api_view(['GET']) def api_list_deduction_view(request): account = request.user deduction = Deduction(author=account) if request.method == "GET": serializer = DeductionSerializer(deduction, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Deduction(models.Model): title = models.CharField(max_length=50, null=False, blank=False) description = models.TextField(max_length=5000, null=False, blank=False) amount = models.IntegerField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, upload_to=deduction_image_file_path) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
How to setup celery as daemon
I am faced with necessity to setup celery as daemon for my django project on Ubuntu 16.04 server while doing it I met several misunderstandings which I will describe in my question. I know that by the rules of Stack asked should should ask only one clear question but I will ask several in one question because first question come from second etc. For tune celery as daemon I decide to use SystemD. In documentation Demonization celery provide a guide but it isn't so clear as I want maybe it's because I am beginner. My first question is: should I setup separately celery and celerybeat? Here is documentation provided example of configuration [Unit] Description=Celery Service After=network.target [Service] Type=forking User=celery Group=celery EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/opt/celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target All my misunderstandings relate to this piece of code and next question is: What user and group I should specify in Service part of configuration? in documentation example above celery specified for user and group but when I checked users … -
What's the difference between RabbitMQ and Pusher?
I'm building a django webapp where i need to stream some stock market trades on a webpage in real time. In order to do that, i'm searching for various approaches, and i found about Pusher and RabbitMQ. With RabbitMQ i would just send the message to RMQ and consume them from Django, in order to get them on the web page. While looking for other solutions, i've also found about Pusher. What it's not clear, to me, is the difference between the two, technically. I don't understand where would i use Rabbit and where would i use Pusher, can someone explain to me how are they different? Thanks in advance! -
Delete user when profile and Company has deleted
I have the following model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bedrijf = models.ForeignKey(Bedrijf, on_delete=models.CASCADE) class Bedrijf(models.Model): bedrijfsnaam = models.CharField(max_length=30, null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: n = Bedrijf.objects.create(bedrijfsnaam="Gaarne_bedrijfsnaam_instellen") n.save() Profile.objects.create(user=instance, bedrijf=n) I want to delete the User when Bedrijf has been deleted. With this config the profile will be deleted but not the User. What is the solution? -
Aggregate by max of another field
Hey I have a model named Visit. With fields date, person, id. I want to get all persons who do not have visits in last three months. Can you help me, please? What I have so far. Results are not what I wanted to see. visits_anotated = Visit \ .objects \ .only('id', 'date', 'person') \ .values('id', 'date', 'person') \ .annotate(latest_visit=Max('date')) \ .filter(latest_visit__lte=datetime.datetime.now() - datetime.timedelta(weeks=14)) -
how to check whether a user is logged in in django?
I know about request.user.is_authenticated() but i created a custom user(model) and created login page for it now how can we know if the user is logged in? -
Django recaptcha on localhost loading forever
I'm trying to user recaptcha https://github.com/praekelt/django-recaptcha in my django project while in development. I have added 'localhost' to my domains and I think my settings are correct but the page just loads forever. Here's my code sofar: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #Core authentication framework and its default models. 'django.contrib.contenttypes', #Django content type system (allows permissions to be associated with models). 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'tinymce', 'crispy_forms', 'captcha', 'main', ] RECAPTCHA_PUBLIC_KEY = '...' RECAPTCHA_PRIVATE_KEY = '...' RECAPTCHA_DOMAIN = 'www.recaptcha.net' forms.py from captcha.fields import ReCaptchaField class CreateDealerForm(forms.ModelForm): captcha = ReCaptchaField() class Meta: model = Dealer featured_image = ImageField(widget=PictureWidget) fields = ('name', 'phone','website', 'address', 'featured_image',) widgets = { 'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}), 'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}), 'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}), 'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}), } template <div class="container"> <div class="card"> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form|crispy }} <img href="{{dealer.featured_image.url}}"> {{ form.errors }} <br> <button type="submit" class="btn submit-btn mt-3 mr-2"><i class="fa fa-share"></i> Submit</button> </form> </div> </div> -
Accessing document.cookie returns empty string even though cookies are listed in developer tools with httpOnly flag set to false
Sometimes*, when accessing document.cookie in the login page I get an empty string even though: cookies are listed in the Chrome and Firefox developer tools, httpOnly flag of cookie I'm interested in is set to false, path of cookie I'm interested in is set to '/'. Desired behaviour My React single page application (SPA) has a login page which contains a <form /> element for sending login credentials to the backend. When the response from the backend is received and the authentication was successful, I check whether the authentication cookie has been set, properly. If that's the case a redirect will be triggered that shows the content for logged in users. Actual behaviour Unfortunately, in like 85% of the login attempts, document.cookie returns an empty string which prevents the redirection and keeps the user on the login page. Pressing F5 doesn't do the trick but when manually replacing a subdirectory within the url after a successful login request (e.g. updating 'www.website.tld/login' to 'www.website.tld/data') the user gets forwarded to the desired page for logged in users. I'm not able to reproduce the error manually. It just seems to happen randomly. But when it occurs and I have a look into the … -
Follow button on profile page toggle issue Django
The button follows the user properly however when the button toggles to unfollow it toggles on all user profiles. Does not follow them all but the button toggles. I need to change to JsonResponse/Ajax return also. FULL PROJECT HERE: https://github.com/forafekt/save-live-set Models: from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver # from django.http import request from config.settings import base User = base.AUTH_USER_MODEL class ProfileManager(models.Manager): def toggle_follow(self, request_user, username_to_toggle): profile_ = Profile.objects.get(user__username__iexact=username_to_toggle) user = request_user is_following = False if user in profile_.followers.all(): profile_.followers.remove(user) print("REMOVE FOLLOW") # testing else: profile_.followers.add(user) is_following = True print("ADD FOLLOW") # testing return profile_, is_following class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followers = models.ManyToManyField(User, related_name="is_following", blank=True) activated = models.BooleanField(default=False) objects = ProfileManager() def __str__(self): return str(self.user.username) @receiver(post_save, sender=User) def make_user_profile(sender, **kwargs): if 'created' not in kwargs or not kwargs['created']: return # Assumes that the `OneToOneField(User)` field in "Profile" is named "user". profile = Profile(user=kwargs["instance"]) # Set anything else you need to in the profile, then... profile.save()` Views: from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404, HttpResponseRedirect from django.shortcuts import redirect, get_object_or_404 from django.views.generic import DetailView from django.views.generic.base import View from config.settings import base from src.profiles.models import Profile User = base.AUTH_USER_MODEL class ProfileFollowToggle(LoginRequiredMixin, View): def … -
How to read InMemoryUploadedFile using pyreadstat
I am using Django to read a file that was passed in the POST request. However, when I do pyreadstat.read_sav(file), I get TypeError: Argument 'filename_path' has incorrect type (expected str, got InMemoryUploadedFile) -
Django override default admin register form
I know how to override UserCreationForm but it works only on users, not on admin registration. Here is my case... I have modified the default user model and it has now the field user_company which cannot be Null: class User(AbstractUser): user_company = models.ForeignKey("UserCompany", on_delete=models.CASCADE) I have overriden the UserCreationForm: from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = get_user_model() def save(self, commit=True): user_company = UserCompany() ## create a new company and assign it to the new user user_company.save() user = super(UserRegisterForm, self).save(commit=False) user.user_company_id = user_company.pk if commit: user.save() return user All this works fine for normal users. But when I try to python manage.py createsuperuser in the console, after entering the admins username and password, I get an error that the field user_company cannot be Null -
Save a file created in views.py in mongodb
Im looking for a way to save a JSON file that i create in my views.py into my database but i cant see a proper way to do this. I only found posts for saving an uploaded file to the database but i dont want that.. My question may be silly but im really new to django and python. My code below... forms.py class LanModelForm(forms.ModelForm): helper = FormHelper() # helper.form_show_labels = False class Meta: model = UserProject fields = ['project_name', 'subnet', ] models.py class UserProject(models.Model): project_name = models.CharField(max_length=15) subnet = models.CharField(max_length=30) file = models.FileField() def __str__(self): return self.project_name views.py def post(self, request): form = self.form_class(request.POST) if form.is_valid(): _target = form.cleaned_data['subnet'] project_name = form.cleaned_data['project_name'] form.save() base_dictionary = { 'Project-details': [ { 'project_name': project_name, 'subnet_used': _target } ], 'Host-scan': [ ], 'Arp-scan': [ ] } # A custom function that creates my JSON file # It works and the json file is generated. makeJsonFile(base_dictionary) request.session['subnet'] = _target request.session['project_name'] = project_name return redirect('/passive_scanning.html') return render(request, self.template_name, context={})