Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Table not creating for django-background-tasks
I am new to django and i am trying to use background-tasks for sending mail notifications. But I am getting error as django.db.utils.OperationalError: no such table: background_task I have added background_task inside INSTALLED_APPS and gone through other related questions asked and so tried python manage.py makemigrations background_task But I am still getting same error. I am using Django==3.0.7 django-background-tasks==1.2.5 django-compat==1.0.15 Will appreciate any help -
A Django Issue when testing my website with a dropdown
I am following the tutorial at Django Tutorials. The goal is to get a dropdown list to display a logout when I click on it. Here is my settings.py where the static files are held: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] LOGOUT_REDIRECT_URL = 'home' I am getting a HTTP 404 error because of this. It's saying GET HTTP/1.1 404 1683 when I run it. Because of the error, when I click on the arrow, it won't show me the dropdown list. Can anyone show me how to fix this and what this error means? -
Django: Redirect to another page after download triggered
i want to Redirect to another page after download triggered my code is: animated_gif = BytesIO() frames[0].save(animated_gif, format='gif', save_all=True, append_images=frames[1:], ) animated_gif.seek(0) response = HttpResponse(content_type="image/gif") response['Content-Disposition'] = "attachment; filename=%s.gif" % "new" response.write(animated_gif.getvalue()) return response -
Unresolved error when importing app in urls.py file
I created 2 apps in my project. The first app works correctly. I followed the same method for the second app. When I try to import that apps view file, it gives me an error. from users import views it gives me an unresolved error(it is not recognizing users) I also added that app in settings.py file of the blog project. users.apps.UsersConfig is also added in setting.py file -
How to change list number in Django templates loop?
So basically I have a list of 10 items from my database that I'm looping into one of my templates. How could I dynamically change the number of the list item as well? Here is what my loop looks like {% for list in lists %} <div class='collection-item avatar cart-row'> <div> <h5 class="center container left card-title">{{ list.value }}</h5> </div> </div> {% endfor %} The current result is "Shirt", "Shoes", "Pants", etc. What I want to achieve is "1. Shirt", "2. Shoes", "3. Pants", etc. My question is how could I do that? Thank you. -
uwsgi/nginx doesn't respond until subprocess is done
I have server with nginx the passes http trafic to uwsgi runnig my django app. the django view I'm calling is creating a subprocess that runs the following test.sh bash script: #!/bin/sh echo hello sleep 10 echo morning for some reason I am not getting the 200 response from the view until the bash is done, i.e. "morning" is printed, although subprocess supposed to create a thread that run in parallel. While trying to debug this issue I noticed that if I cURL locally from server while running django directly with python manage.py runserver or when running uwsgi with http=127.0.0.1:8000 I get the 200 response before the "morning" print as expected. Any ideas why with socket=127.0.0.1:8000 and nginx it behaves different? my nginx is configured to pass http trafic to django: upstream django { server 127.0.0.1:8000; # for a web port socket (we'll use this first) } server { listen 80; location /api/ { uwsgi_pass django; include /path_to/uwsgi_params; # the uwsgi_params file you installed } } my uwsgi ini: [uwsgi] socket=127.0.0.1:8000 module=my_module.wsgi:application chdir=/project_dir master=true vacuum=true logger=file:/log_path stats=/tmp/uwsgi_stats.socket single interpreter=true and my view.py is: from subprocess import Popen from rest_framework import views from rest_framework.response import Response class TestApi(views.APIView): def post(self, request, … -
Bootstrap4 multi-slide carousel with Django
I'm trying to build a dynamic multi-slide carousel with Django and Bootstrap. Following the instructions laid out here, I've built the following but there is a problem with the html as the data from the model is not rendered on screen. (I am certain that it is a problem with the below as I have another similar carousel on the page which works fine). template.html: <div class="container"> <div id="modelCarousel" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for modelInstance in modelData %} {% if forloop.first %} <li data-target="#modelCarousel" data-slide-to="0" class="active"></li> <li data-target="#modelCarousel" data-slide-to="1"></li> <li data-target="#modelCarousel" data-slide-to="2"></li> {% endif %} </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <img data-src="{{ model.image }}"> </div> </div> {% endfor %} <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="icon-prev" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="icon-next" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Thanks! -
Perform long functions on Django web app hosted on Heroku
I am working on creating a web app with django. It involves data handling, and some of the functions take a long time to perform. This is fine on localhost, but when I put it on heroku, I get timeout errors. Right now, I am using forms to submit requests for handling data. Is there an alternative to using POST/GET requests that won't cause timeout errors? Thanks in advance. -
fill a form field in Django views
I am trying fill in a value to one of my form fields. The form has the following fields: Username referral Email Password confirm-password I want to automatically fill the referral field from the views.py but can't get it right. any Ideas? Views.py def consultant_register(request): field_name = 'referral' obj = ReferralResponse.objects.last() referral_code = getattr(obj, field_name) form = ConsultantSignUpForm(request.POST, initial={'field':referral_code}) if form.is_valid(): my_model = form.save(commit=False) my_model.referral_code = referral_code my_model.save() login(request,user) return redirect('/') return render(request, 'accounts/consultant_register.html', {'form': form}) -
Django Multi User Login in a Django Project
I have Implemented a Django Application but it's still in Testing. So I'm using it in local host.So when i login using a form.It authenticates me and im logged in .But If im open it in another tag.Now it actually logs me in as the previous user.So when i Log it out ,i'm totally logged out from both tabs.My question is if say I host this website.And two different people tries to log in at the same time,will the website work properly and log them in???(provided both are using different computers) -
I am trying t create a login/logout functionality in django but am getting follow error
Hi i am trying to create a login/logout functionality in django ,i have been trying for some time now but am getting the following error please help me out i am new to all Django.I have done everything as taught in the course but am still getting this error,i think error is in url file but i don't really know. Using the URLconf defined in TheResources.urls, Django tried these URL patterns, in this order: ^$ [name='index'] admin/ ^FirstApp/ ^user_login/$ [name='user_login'] login/ [name='login'] logout/ [name='logout'] password_change/ [name='password_change'] password_change/done/ [name='password_change_done'] password_reset/ [name='password_reset'] password_reset/done/ [name='password_reset_done'] reset/<uidb64>/<token>/ [name='password_reset_confirm'] reset/done/ [name='password_reset_complete'] ^logout/$ [name='logout'] The current path, FirstApp/user_login/{url 'FirstApp::user_login'}, didn't match any of these. URL.py project urlpatterns = [ url(r'^$',views.index,name='index'), path('admin/', admin.site.urls), url(r'^FirstApp/',include('FirstApp.url')), path('', include("django.contrib.auth.urls")), url(r'^logout/$',views.user_logout,name='logout'), Url .py application file url(r'^Registration/$',views.RegistrationView,name='Registration'), url(r'^user_login/$',views.user_login,name='user_login'), Views.py file def user_login(request): if request.method=='POST': username=request.POST.get('username') password=request.POST.get('password') user=authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("account is not active") else: print("Someone else tried to login and failed") return HttpResponse("Invalid credentials") else: return render (request,'FirstApp/Base.html',{}) Temlplate Base.html {%if user.is_authenticated%} <a href="{%url 'logout'%}">Logout</a> {%else%} <a href="{%url 'FirstApp:user_login'%}">login</a> {%endif%} Login.html file <form action="{url 'FirstApp::user_login'}" method='POST'> {%csrf_token%} <label for="username">Username</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password</label> <input type="Password" name="password" placeholder="Enter Password"> <input type="Submit" value="Login"> </form> -
PostGIS geography does not support the "~=" function/operator
I am trying to save point field in the database via update_or_create method but it is giving me this error. My function to save data: for city in cities_data: obj, created = models.City.objects.update_or_create( name = city["name"], country = city["country"], state = city["state"], point = Point( float(city["longitude"]), float(city["latitude"]) ), radius = city["radius"], is_curated = city["is_curated"], is_metro_city = city["is_metro_city"] ) obj.save() Model: class City(models.Model): name = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) point = gis_models.PointField(geography=True, null=True) is_metro_city = models.BooleanField(default=False) is_curated = models.BooleanField(default=False) radius = models.IntegerField(null=True) when I try to run this I get this error: ValueError: PostGIS geography does not support the "~=" function/operator. I want to know why I am getting this error, I did not find any useful information related to this. Thanks in Advance. -
How to save the position of draggable elements?
Hello, I am making a web application in django, what it allows you to do is drag elements on the page, what I want to do is save the position of these elements so that when the page is reloaded the elements remain in the same position in which they left, is there any way to save the position? This is my javascript to drag elements. <script src="http://threedubmedia.com/inc/js/jquery-1.7.2.js"></script> <script src="http://threedubmedia.com/inc/js/jquery.event.drag-2.2.js"></script> <script type="text/javascript"> jQuery(function ($) { $('.drag') .click(function () { $(this).toggleClass("selected"); }) .drag("init", function () { if ($(this).is('.selected')) return $('.selected'); }) .drag(function (ev, dd) { $(this).css({ top: dd.offsetY, left: dd.offsetX }); }); }); And this is the element or elements that are dragged, the number of elements is variable since it is conditioned by a database. <div class="drag"> <span class="dot" title="{{ device.device_name }}" style="background-color: #197f32"><br/><b><p style="color: #ce3830;"> {{ device.device_name }}</p></b></span> </div> -
how can i show query id from div to an other div whene click add to cart, in same page with ajax and django?
Hi, I would like to finish a university project, but I found a big problem, how to query the same page using ajax without reloading the page** like this website: https://cairogourmet.com/menu model.py class Plat_a_manger(models.Model): user_plat = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, max_length=200, on_delete=models.CASCADE) title_plat = models.CharField('العنوان', max_length=9500) price = models.DecimalField(max_digits=200, decimal_places=3, default=0.00) image_plat = models.ImageField('صورة مناسبة', upload_to = 'Images_Plat') def __str__(self): return self.title_plat views.py from django.shortcuts import render from andalous.models import Category, Plat_a_manger def product_list(request): cat = Category.objects.all().order_by('id') plat = Plat_a_manger.objects.all().order_by('id') ctx = { 'cat': cat, 'plat': plat, } return render(request, 'home/menu.html', ctx) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from django.contrib.auth import views as auth_views from .import views app_name="andalous" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'menu/$', views.product_list, name="product_list"), ] -
ModuleNotFoundError: No module named 'apps.news'; 'apps' is not a package
I have a Django project with the following structure: project apps news models.py hose tasks.py Within tasks.py, I have this import from apps.news.models import Company When I try to run tasks.py, I get the following error: ModuleNotFoundError: No module named 'apps.news'; 'apps' is not a package How do I fix this error? I don't understand why this import does not work. -
Python. Poll the my REST service until a response is received
I'am writing restful service with its own database. I have an endpoint (/generate) the answer to which is very long in time. The client cannot wait long for a response from this rest. The following idea came up: Upon request for endpoint '/generate' the client receives a unique key With this key, the client polls the service until the data is ready Аs soon as the data is ready, the client can request it using the same key What framework and how can this be implemented? I hope I've made my point clear -
ValueError: Cannot assign "<User: username>": "MessageModel.user_name" must be a "Room" instance
I have ita MessageModel which have a field user_name which is a instance of Room model. i want to save all the messages of current user inline but when i try to save username which is instance of Room model...an error occured like--> ValueError: Cannot assign "<User: username>": "MessageModel.user_name" must be a "Room" instance. I have a another model DateTimeField which has the following field datecreated and date_modified. models.py--> class Room(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='owner', null=True) def __str__(self): return str(self.user.username) class MessageModel(DateTimeModel): user_name = models.ForeignKey(Room, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name = 'sender', on_delete=models.CASCADE, null=True) message = models.TextField('body') recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='recipients') class Meta: ordering = ['-id'] forms.py--> class MessageModelInline(admin.TabularInline): model = MessageModel class RoomAdmin(admin.ModelAdmin): inlines = [MessageModelInline] admin.site.register(Room, RoomAdmin) @database_sync_to_async def save_message_to_db(self,username, message): user_name = self.user_name print(type(user_name)) # <class 'django.contrib.auth.models.User'> return MessageModel.objects.create(user_name=user_name, user=username, message=message) any solution will be highly appreciated. ThankYou -
ManyToManyField is showing error while migrate in django
While I was doing the coding I changed one field to "ManyToManyField". When I try to migrate it is showing the following error. Models.py class Department(models.Model): Dept_No = models.CharField(primary_key=True, max_length=6) Dept_Name = models.CharField(unique=True, max_length=20) Dept_Manager = models.OneToOneField('Employee_Detail', models.DO_NOTHING, limit_choices_to={'Position': 'Manager'}) def __str__(self): return self.Dept_No class Employee_Detail(models.Model): Employee_ID = models.CharField(primary_key=True, max_length=6) Employee_Name = models.CharField(unique=True, max_length=30) Primary_Phone = models.IntegerField(unique=True, max_length=10) Secondary_Phone = models.IntegerField(unique=True, max_length=10) p = ( ("Manager","Manager"),("Supervisor","Supervisor"),("Employee","Employee") ) Position = models.CharField(max_length=15, choices= p, default="Employee") Address = models.TextField(max_length=500) Email = models.EmailField(max_length=50, unique=True) def __str__(self): return str(self.Employee_Name) class Leave(models.Model): Employee_Name = models.ManyToManyField(Employee_Detail,default=" ") Dept_Name = models.ForeignKey('Department', models.DO_NOTHING) l = ( ("Paid","Paid"),("Non-Paid","Non-Paid") ) Leave_Type = models.CharField(max_length=10, choices= l, default="Non-Paid") Start_Date = models.DateField() End_Date = models.DateField(null=True, blank = True) Reason = models.CharField(max_length=200) s = ( ("Accepted","Accepted"),("Pending","Pending"),("Canceled","Canceled") ) Status = models.CharField(max_length=10, choices= s, default="Pending") def __str__(self): return str(self.Employee_Name) Admin.py class LeaveAdmin(admin.ModelAdmin): list_display = ["Employee_Name","Dept_Name","Leave_Type","Start_Date","End_Date","Reason","Status"] search_fields = ["Employee_Name__Employee_Name","Dept_Name__Dept_Name","Leave_Type"] list_filter = ["Employee_Name","Dept_Name","Status"] admin.site.register(Leave, LeaveAdmin) How to prevent this error and how to create ManyToManyField without error? -
Adding Data to Request in Django REST Framework in Authentication Class
Suppose I have the following Authentication class in DRF. If the request is authenticated, then I need some additional data in the request object. Say, REQUIRED_DATA is that variable. class MyAuthClass(BaseAuthentication): def authenticate(self, request): # suppose is_authenticated_request and authenticated_user are methods # which return the responses as described by their name if is_authenticated_request(request): user = authenticated_user(request) request.REQUIRED_DATA = some_variable_of_any_type return (user, None) raise exception.AuthenticationFailed(_('Authentication failed.')) Here is how I used it in the viewset. class MyViewSet(viewsets.GenericViewSet): authentication_classes = [MyAuthClass] permission_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): ############# # ......... # request.REQUIRED_DATA # using variable # ......... # ############# Am I going right? I need this variable after the request is authenticated. Is their a better way to do this? Middleware is one but Middleware runs for each request, I need for this viewset only. -
Git Heroku Django - Git pull heroku master not pulling rolled back version?
Within the Heroku admin portal I rolled back to a previous version of my application. I would like this rolled back version to be my heroku master. However when I do git pull heroku master it pulls the last release I did git push heroku master from on my local machine, not the rolled back version. How can I update my rolled back version to be the heroku master in heroku? -
How to unittest Django Rest Framework endpoint with XML?
I've got an endpoint which I built with Django Rest Framework. It works great when I test it with something like Postman, but my unit tests fail. When I test my json endpoints I always post Python dicts instead of json strings, like this: response = self.client.post('/json-endpoint/', {'a': 1}, format='json') When I test the xml endpoint I tried to post a raw xml string like this: response = self.client.post('/xml-endpoint/', '<?xml version="1.0" encoding="UTF-8" ?><myDataStructure></myDataStructure>', format='xml') But this doesn't work. In my Viewset I override the create() method, and in there, my xml somehow seems to be "packaged" into another xml. If I print out request.body in the create() method I see this: b'<?xml version="1.0" encoding="utf-8"?>\n<root>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;\n&lt;myDataStructure&gt;\n etc.. As you can see my xml is somehow encoded and then packed into another <?xml version="1.0" encoding="utf-8"?>\n<root>. Does anybody know how I can properly provide the xml when I write unit tests for the xml endpoint? All tips are welcome! -
django modelmanager queryset not returning page
I've been following the guidance in Two Scoops of Django and applying this to a re-write of my own apps. I have a model called Bookings with a ModelManager which filters to select only future dated bookings. An extract is below but the relevant field is start_date. guest_status = models.IntegerField('Guest status', choices=GuestStatus.choices, default=0) ack_date = models.DateField(verbose_name='Date acknowledged') start_date = models.DateField(verbose_name='Start date') end_date = models.DateField(verbose_name='End date') dep_recd = models.DateField(null=True, blank=True, verbose_name='Deposit received') bal_amount = models.IntegerField('Balance due', default=0) dep_amount = models.IntegerField('Deposit amount', default=0) sec_recd = models.IntegerField('Security deposit', choices=SecurityStatus.choices, default=0) bal_recd = models.DateField(null=True, blank=True, verbose_name='Balance received') keys_sent = models.DateField(null=True, blank=True, verbose_name='Date keys sent') sec_retn = models.DateField(null=True, blank=True, verbose_name='Security deposit returned') booking_status = models.IntegerField('Status', choices=BookingStatus.choices, default=0) booking_notes = models.TextField(blank=True, verbose_name='Notes') bkd_child = models.IntegerField('Children', default=0) bkd_adult = models.IntegerField('Adults', default=2) guest_one = models.CharField(blank=True, verbose_name='Guest 1', max_length=30) guest_two = models.CharField(blank=True, verbose_name='Guest 2', max_length=30) guest_three = models.CharField(blank=True, verbose_name='Guest 3', max_length=30) guest_three = models.CharField(blank=True, verbose_name='Guest 3', max_length=30) slug = AutoSlugField(unique=True, populate_from=get_populate_from) num_nights = models.IntegerField('Nights', default=0) objects = FutureBookings() The ModelManager appears before the Bookings model: class FutureBookings(models.Manager): def booked(self): return self.filter(start_date__gte=pendulum.now()) When I test this in shell_plus it works as it should do. When I run the site however I get a 404: Request Method: GET Request URL: http://127.0.0.1:8000/bookings/current/ … -
map widgets page not load in live server it is work in local server
Django-map-widgets page-load in the local server my local server but it is not working in live server my live server here my HTML file {% extends "base.html" %} <HTML> <head> <title>Shop</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% load static %} {% block extrahead %} {{ form.media }} <script type="text/javascript"> $(document).on("google_point_map_widget:marker_create", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // created marker coordinates console.log(mapWrapID); // map widget wrapper element ID }); $(document).on("google_point_map_widget:marker_change", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // changed marker coordinates console.log(mapWrapID); // map widget wrapper element ID }); $(document).on("google_point_map_widget:marker_delete", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // deleted marker coordinates console.log(mapWrapID); // map widget wrapper element ID }) </script> {% endblock extrahead %} </head><body> {% block content %} {% include 'CustomerNavbar.html' %} <br> <form method="POST" action="" enctype="multipart/form-data" > {% csrf_token %} {{form.as_p}} <input class="btn btn-primary" type="submit" name="Update Information"> </form> {% endblock content %} </body></html> when I find inspect on live server I see (index):1 Refused to apply style from 'https://vishalbusiness.com/static/css/bootstrap-theme.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, … -
how use setUp in selenium webdriver remote?
I want to use setUp instead of setUpClass in my selenium tests. This code works fine and is able to get the correct host when using setUpClass: @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' @classmethod def setUpClass(cls): super().setUpClass() cls.host = socket.gethostbyname(socket.gethostname()) cls.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) cls.selenium.implicitly_wait(15) How should I do it if I'm gonna use setUp? @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' def setUp(self) -> None: super(BaseTestCase, self).setUp() self.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) self.host = socket.gethostbyname(socket.gethostname()) self.selenium.implicitly_wait(15) -
Documentation tool - Search into HTML files from django templates
I am working on a website using django. I have a documentation section with plain HTML files (i.e. not related to the django databases, just text). Those files have been converted from LaTeX to HTML. I would like to add a search bar into my documentation so the user can search a word to get some kind of help, for example by: highlighting the word in the text, returning a list of urls of the pages where the word occur, telling me how many times this word occur in each section of the table of content, ... I've been searching on the web for a while be could not find anything on how I could do this. I would appreciate any help/tips. Thanks in advance.