Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker compose error while creating multiple postgres database
I'm facing some issue while connectng multiple database in a container. on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? So here I'm connecting my 2 webservers(container's) to a single container by separating databases. Here my web_1 container is working fine, But I'm facing issue with cloud_1. web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table web_1 | return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in cursor web_1 | return self._cursor() web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 236, in _cursor web_1 | self.ensure_connection() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection web_1 | self.connect() web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 197, in connect web_1 | self.connection = self.get_new_connection(conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner web_1 | return func(*args, **kwargs) web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection web_1 | connection = Database.connect(**conn_params) web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 126, … -
Get data on basis of Categories django
I have model of Articles like class Articles(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True) articlename = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Categories, on_delete=models.CASCADE , blank=True, null=True) Now I want to get data in a form like "Every Category will have all articles in form of objects from database" for example I have 2 articles , 1 is "article1 having cat1" and 2nd "article2 having cat2" Now I want to get data like this data:[ cat1:[{article1},{}] , cat2:[{article2}] ] is there any group by categories like thing in django ?? till now I have tried this code order_article = OrderArticle.objects.filter(order__order_number=id ,order__restaurant=restid) samearticle=[] for order_obj in order_article: if : #will check if article having cat already been created category={} category[order_obj.article.category.name]=order_obj samearticle.append(order_obj.article.category.name) else: samearticle[order_obj.article.category.name].append(order_obj) -
Difficulty passing a maptile as context directly into a Leaflet map tilelayer in Django
I have a web-page that has an embedded Leaflet map. I've managed to create a drop-down for the user to select different maptile types from Maptiler.com. This worked fine with the maptile address being passed as context from the view which was then specified in my template as follows:- L.tileLayer('{{ context.maptileaddress }}', {attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>',}).addTo(map); I then decided that I might like to use other maptile providers such as Stamen and that would require me to pass the whole tilelayer argument as follows:- L.tileLayer('{{ context.maptilefullkey }}).addTo(map); where a valid 'maptilefullkey' is:- 'https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', { attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: 'abcd', minZoom: 1, maxZoom: 18, ext: 'png' } When I embed this text literally into the tileLayer method, the maptile displays just fine - see my print. The maptile works fine when it is hardcoded into the the tileLayer() method You can also see that I have successfully passed {{ context.maptilefullkey }} to the template and it has printed at the bottom of the webpage successfully. It apparently matches the valid key exactly. But when I pass it as a variable L.tileLayer('{{ … -
Deploying Django project to Linode server - Images not uploading
My profile pictures aren't saving properly or to the right place or something.. when i try to open the image in a new tab it goes to URL my.ip.address:8000/media/default.jpg but it returns a page saying Not Found The requested resource was not found on this server. settings.py is as follows: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' this is in my urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) can someone help?? -
django-rest-auth multiple registration endpoints
I am new to Django. I also use django-rest-framework with django-rest-auth. django-rest-auth gives me registration endpoint which I call with all the user's data. I have a new use case and I need to figure out how to solve it. I need to create a new endpoint that will get token and a password as an input. Using this token I need to fetch user details and along with the password register a new user (this flow is in addition to the regular registration flow). How should I face the task? Should I use multiple serializers in django-rest-auth? Should I implement all this is the frontend? I would appreciate any advice. -
Django pagination -- maintaining filter and order by
I've a small Django project basic-pagination. There is one model, one form and two views (list view, form view). User submits data in the form view, then the data is displayed in the list view. Pagination is enabled to only display 5 posts at a time. What I've implemented is a form with a GET response to get the data I want to display (e.g. name, date). See code below class FormListView(ListView): model = models.ToDoList paginate_by = 5 # if pagination is desired template_name = 'pagination/listview.html' context_object_name = 'forms' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'Form List View' context['filter_form'] = forms.FilterListView(self.request.GET) return context def get_queryset(self): queryset = models.ToDoList.objects.all().order_by('-id') name = self.request.GET.get('name') if name: queryset = queryset.filter(name=name) order_by = self.request.GET.get('order_by') if order_by: queryset = queryset.order_by(order_by) print(queryset) return queryset The problem is that the class based view ListView calls the method get_queryset if you are moving from page 1 to page 2 and thus losing the filtered queryset I wanted. How can I maintain the filtering throughout the pagination process? -
How to use django-meta module(or any easier way) to render html meta tags
I've tried to follow the Django-meta documentation to the best of my ability. Added it to my list of applications in the settings file INSTALLED_APPS = [ ... 'meta', ] my model looks like from django.db import models from meta.models import ModelMeta class Article(ModelMeta, models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.ImageField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) content = models.TextField(null=True, blank=True) _metadata = { 'title': 'title', 'description': 'content', } My views.py looks like def article_detail_view(request, slug): obj = get_object_or_404(Article, slug=slug) template_name = ['snmov/home.html'] context = {} context['object'] = obj context['meta'] = obj.as_meta() return render(request, template_name, context) The path to this view looks like path('<str:slug>/', article_detail_view, name='article_detail'), The home.html extends a base.html whose head tag has {% include "meta/meta.html" %} meta.html has {{meta}} My Problem: I want it to render the 'title' and 'content' of the article in the meta tag, but it renders the meta tag as <meta.views.Meta object at ******> on the body of the page. Questions: How can I make it render in the head of the document? What am I missing in order to make the meta tag render like it's supposed to? Any help would be really appreciated. I can provide … -
Mime Type Issue Loading CSS With Django App
Simple issue--I have a Django app hosted on Heroku, and my stylesheet isn't loading. Now I've taken the time to read the other questions on this issue, but I believe each situation is unique. Now the error is as follows: Refused to apply style from 'https://mazzodjangoapp.herokuapp.com/static/blog/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The static directory is defined in my setttings.py file as: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' In my base.html file, my link tag looks like this: <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> Works locally. Why is not loading up in the Heroku environment? Thanks, Ironman -
How would I implement login for the lockscreen in django
I have a lock screen page which only consist of a password field(INPUT) and just a username image above the password field. Keep in mind that lock screen is different from a login page. Note that:- Login form requires Username and the Password while the Lock screen form does only require the password since the user did not actually logged out but its held somewhere to my knowledge. Here's the simple login function view.py def lockscreen(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('core:dashboard') else: messages.info(request, 'Username OR Password is incorrect!') context = {} return render(request, 'accounts/lockscreen.html', context) html <div class="auth-form-transparent text-left p-5 text-center"> <img src="{% static 'images/faces/face15.jpg' %}" class="lock-profile-img" alt="img"> <form class="pt-5" method="POST"> {% csrf_token %} <div class="form-group"> <label for="examplePassword1">Password to unlock</label> <input type="password" name="password" class="form-control text-center" id="exampleInputPassword" placeholder="Password"> </div> <div class="mt-5"> <button type="submit" value="Login" class="btn btn-block btn-gradient-primary btn-lg font-weight-medium auth-form-btn" >Unlock</button> </div> <div class="mt-3 text-center"> <a href="{% url 'login' %}" class="auth-link">Sign in using a different account</a> </div> </form> </div> forms.py class CreateUserForm(UserCreationForm): username = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'User Name ...'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Password ...'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Confirm Password … -
Django3.x - Heroku - raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
I need your help colleagues. I am trying to deploy my Django Project on Heroku but I am getting a seemingly simple error but I have struggled to debug it for days. I would appreciate detailed help, I am a newbie. Thanking you in advance. Background I have hidden foldername because it is also a domainname I want to register. I have python 3.6.8 and django2.1.1 on a windows10 machine and Heroku PaaS. Project works perfectly on local/development server i.e python manage runserver works . The secret key is set SECRET_KEY = os.environ.get('SECRET'), I have also tried hard coding SECRET_KEY = 'my-secret-key' it but no difference. I have os.environ.setdefault('DJANGO_SETTINGS_MODULE', '*foldername.settings.testing') correctly set in wsgi.py & manage.py Other Settings My Procfile for Heroku has web: gunicorn *foldername.wsgi:application --log-file -. I have a requirements and a runtime.txt files. Error Running python manage.py migrate on ⬢ thawing-thicket-02648... up, run.2948 (Free) Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % … -
I can not access my images on media folder, Django project
1) project. In my media folder I have some images, usually I could acces them as /images/image1.jpg. but now it is now working and the browser is showing me this error: "You don't have permission to access /media/image1.jpg on this server.". This are the perrmissions for the media folder: drwxrwxr-x 3 admin www-data 4096 Jan 29 11:36 media And here are my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' FILE_UPLOAD_PERMISSIONS = 0o775 What I am doing wrong? -
Link in template for routers of rest_framework
I set rest_framework and have the page named api from . import views from rest_framework import routers from django.conf.urls import url from django.conf.urls import include router = routers.DefaultRouter() router.register(r'genres', GenreViewSet) router.register(r'blogs',BlogViewSet) urlpatterns = [ url(r'^api/',include(router.urls), name='api') #name is here??? ] but in template , I can not access the page <a href="{% url 'api' %}">api</a> It shows the error , I think I am basically somehow wrong though... django.urls.exceptions.NoReverseMatch: Reverse for 'api' not found. 'api' is not a valid view function or pattern name. -
how to specifiy this url in django 127.0.0.1:8000/?uid=Mjg&token=5dj-ddf5e0d6cf0d6f03dfc1
path('<str:uid>/<str:token>/', views.activate,name="activate") path('login/', LoginView.as_view(template_name='blog/login.html'), name='login'), path('logout/', LogoutView.as_view(template_name='blog/logout.html'), name='logout'), path('signup/', views.signup,name="blog-home"), path('<str:uid>/<str:token>/', views.activate,name="activate") This path is not matching. When I click 127.0.0.1:8000/?uid=Mjg&token=5dj-ddf5e0d6cf0d6f03dfc1 it shows debug page. How to write url path for this? -
Handling absolute URL of form instance
I have a helper function which is sometimes freezing up the site so I am trying to clean up the code to remove possible issues. This helper function creates a thumbnail for videos when they are uploaded if the user does not upload a thumbnail. helper.py: def create_thumbnail(input_path, output_path): """ Save first frame of video for use as video thumbnail. :param input_path: video input path :param output_path: image output path :return: None """ cap = cv2.VideoCapture(input_path) ret, frame = cap.read() if ret: cv2.imwrite(output_path, frame) else: pass views.py: def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES, company=self.request.tenant) form.instance.sender = self.request.user if form.is_valid(): form.save() groups = form.cleaned_data['receiver'] try: if form.instance.thumbnail == 'Logo.jpg': video_name = form.instance.title.replace(" ", "") in_path = str(settings.MEDIA_ROOT) + "/" + str(form.instance.video_file) # CLEAN THIS UP out_path = str(settings.MEDIA_ROOT) + "/" + video_name + ".png" create_thumbnail(in_path, out_path) path = video_name + ".png" form.instance.thumbnail = path except: pass Few questions: How would I go about using get_absolute_url() instead of str(settings.MEDIA_ROOT) + "/" + video_name + ".png" since it is a form instance? Being that this is a form instance I assume I am not able to make this helper function into a model method, is that correct? Can model methods … -
unable to upload image in django
I'm having difficulty uploading the following model with model form. I can upload fine in the admin but that's not all that useful for a project that limits admin access. #Models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) cover = models.ImageField(upload_to='images/',default="#") #views.py def post_edit(request,pk ): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = PostForm(request.POST, request.FILES,instance=post) if form.is_valid(): post = form.save(commit=False) post.author= request.user post.save() return redirect('post_detail',pk=post.pk) else: form = PostForm(request.POST or None,instance=post) return render(request, 'blog/post_edit.html', {'form': form}) #post_edit.html <form enctype="multipart/form-data" method="post">{% csrf_token %} <tr><td>{{ form.as_p }}</td></tr> <tr><td><button type="submit" class="btn">Submit</button></td></tr> </form> Note: All the other data in the form saves perfectly well, the photo does not upload at all. Thank you for your help! -
unhashable type : 'list'
I am porting application from django 1.8 and python 2.7 to django 2.2 AND PYTHON 3.6 this was in python 2.7 def get_absolute_url(self): return ('threads_reply', [self.id]) get_absolute_url = models.permalink(get_absolute_url) i changed it too def get_absolute_url(self): return django.urls.resolve('threads_reply', [self.id]) And its now crashing at this @login_required def inbox(request, template_name='django_messages/inbox.html'): """ Displays a list of received messages for the current user. Optional Arguments: ``template_name``: name of the template to use. """ thread_list = Thread.objects.inbox_for(request.user) return render(request, template_name, { 'thread_list': thread_list, }) -
Can I specify graphene object types as arguments for a graphene mutations?
I'm mapping Django models to GraphQL API with graphene_django. The models reference each other with one-to-many and many-to-many relations. For "create" GraphQL mutations which shall create instances of models without relation references you simply use the model field as mutation arguments. However for "create" GraphQL mutations which shall create instances for models which have "child" models (model instances which are referenced via a relationship) it would be advanterous to beeing able to pass the one/several "child" model/s as corresponding Graphene object types (classes which inherit from DjangoObjectType) as mutation arguments. I've not found any tutorial/design guide which shows how to do that yet. How could I achieve this? -
How to override queryset used by Django admin/form for a Foreign Key
I've tried everything I can find on the internet here, and nothing seems to work, so wondering if lots of the previous answers are for old versions. I'm on Django 2.2.9. #models.py class ParentModel(models.Model): title = models.CharField() class ChildModel(models.Model): parent = models.ForeignKey( ParentModel, on_delete=models.CASCADE, related_name='parent' ) # admin.py @admin.register(ParentModel) class ParentModelAdmin(admin.ModelAdmin): model = ParentModel def get_queryset(self, request): return ParentModel.objects.get_complete_queryset() @admin.register(ChildModel) class ChildModelAdmin(admin.ModelAdmin): model = ChildModel def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = ParentModel.objects.get_complete_queryset() return super().formfield_for_foreignkey(db_field, request, **kwargs) I have a manager query called get_complete_queryset on ParentModel that returns a broader set of Parents than the default queryset. The setup above allows me to go to my ChildModelAdmin and select the 'hidden' Parents from the dropdown, but when I try and save it gives me this error: parent instance with id 2 does not exist. There must be some queryset the form is using to save the model that isn't overridden, but I can't find what it is. -
pop up window after clicking button with Django
I'm trying to pop up an alert window after users click the sign up/sign in button, demonstrating success or failure. if("signup_btn" in request.GET): user = request.GET.get("user_name", None); pwd = request.GET.get("user_password", None); err = checkValidility(user, pwd); # signup success if(err == 0): connect = sqlite3.connect("user.db"); c = connect.cursor(); c.execute(''' INSERT INTO USER (USER, PASSWD) VALUES({}, {}) '''.format(user, pwd) ); connect.close(); # insert user information into database # pop-up window messages.debug(request, "Sign up success."); # try to use messages # signup failure else: messages.debug(request, signup_err[err]); # just error message html = get_template("login.html").render(); return HttpResponse(html); And my HTML looks like <!-- pop up window --> {% if messages %} <script> {% for msg in messages %} alert('{{ msg.message }}'); {% endfor %} </script> {% endif %} But nothing happens, could someone tell me how to do it? -
How can i send a variable value in same views. django python?
I'd like to make a OAUTH login with NAVER. How can i send a variable(below code: state) value in same view(def naver_login to def naver_callback) with django python? def rand_str(): return "".join([random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(7)]) def naver_login(request): client_id = os.environ.get("N_CLIENT_ID") redirect_uri = "http://127.0.0.1:8000/users/login/naver/callback" state = rand_str() return redirect( f"https://nid.naver.com/oauth2.0/authorize?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}&state={state}" ) def naver_callback(request): state = request.session.get("state") print(dir(request)) callback_state = request.GET.get("state") print(callback_state) ... print result is NULL and some random char like : SAG3ra4 -
HOW TO FILL A FORM WITH A VARIABLE WHICH IS A LIST OF SOME RECORDS OF A TABLE (DJANGO)
My Table has 4 fields(Index1 , Index2 , Index3, Index4) the records are {(Alpha1, Alpha2, Alpha3, Alpha4) , (Bravo1, Bravo2, Bravo3, Bravo4), (Charlie1, Charlie2, Charlie3, Charlie4), (Delta1, Delta2, Delta3, Delta4)} my variable is {(Alpha1, Alpha2, Alpha3, Alpha4) , (Charlie1, Charlie2, Charlie3, Charlie4)} my Form has only two fields of my table ({Index1 , Index4}) how to show (index1 and index4) of my variable ?? in a form way in html and not with a table tag ?? Thank You -
Django: How to switch back to local docker development after deployment on heroku
Hi I just finished deploying a project with Django, Docker and Heroku based on the https://djangoforprofessionals.com/ tutorial. However, I don't know how to switch back to local development after having deployed the app. If i go to 127.0.0.1:8000 in my browser i get a ERR_TIMED_OUT message. Here is the official source code, which corresponds 1:1 to my code: https://github.com/wsvincent/djangoforprofessionals/tree/master/ch18-deployment In the tutorial there are two docker-compose files, a docker-compose.yml for local development and a docker-compose-prod.yml for deployment. My idea was to run docker-compose down and docker-compose -f docker-compose.yml up -d --build after deployment to continue working locally, but it did not work out. Any help would be much appreciated! -
NameError at "" name 'pk__in' is not defined
In django I'm trying to retrieve articles data, by checking id (which is pk) from list like this: result = dbmodels.Articles.objects.filter(pk__in[123,124,125]) When I run this function I'm getting error name 'pk__in' is not defined What am I doing wrong? -
Validation error message doesn't shown - Crispy form(Django)
Using crispy forms, validation error message doesn't shown in UI. For example, I tried a functionality to validate file size, if it exceeds the size it should not upload. In my case, it validates the large file and doesn't upload but it silently fails the validation without error message. Note: Framework : Django (Python) Template form package : crispy form Expected solution: System needs to notify the error message whenever validation fails. -
How to access Many-to-Many field data from a different model?
I have the following models: class Work_Music(MPTTModel, Work): name = models.CharField(max_length=10, null=True, blank=True) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) class WorkCast(models.Model): work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True) order = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True) class Cast(models.Model): name = models.CharField(max_length=100, null=True, blank=True) In view.py, I send the following in template context: work = Work_Music.objects.get(work=self.kwargs['pk']) How do I access WorkCast via the Work_Music object? How do I display in the template, Cast #1, Cast #2, Cast #3, Cast #4 How to I grab all of the cast members? Is it? work.workcast.cast.all() doesn't yield any output. How do I display it as a list with commas in between?