Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value from choices in Django?
How to get a value from choices and display it on a form in Django? In this case (as in the picture), so that English is displayed, not en Picture of form In the template I print the form as a variable {{ form }}. I also tried to output by one field {{ form.language.get_lang_display }}, but in this case the language field is not displayed at all. File models.py class AvailableLanguage(models.Model): LANGUAGES = ( ('en', 'English'), ('ru', 'Russian'), ) lang = models.CharField(max_length=50, unique=True, choices=LANGUAGES) lang_code = models.CharField(max_length=5, unique=True) slug = models.SlugField() class Question(models.Model): title = models.CharField(max_length=250) language = models.ForeignKey(AvailableLanguage, on_delete=models.CASCADE, default='') body = models.TextField() ... -
Hit django API present on centos6 using postman on windows
I have my django project on centos6 machine which i run using putty with help of ssh key and i have postman on my windows. I want to configure django project so that when i run 'python manage.py runserver` on centos6, postman on windows should be able to send data to django server. let's say my centos6 machine ip is 10.12.13.130 then should i use http://10.12.13.130:22 as an address in postman to send data or what changes should i need to make in my django project settings.py file. what should i do? -
deny page to refresh if the text box is not empty
check text box if its not empty else refresh the page i tried to check if the id of the textbox is == null then the page will refresh each 5 second if its != null or not empty the page doesn't refresh. <script type="text/javascript"> if($('#opinion').val() == null ){ window.setTimeout(function () { location.href = " "; }, 5000); } </script> if the textbox with id opinion has an input from the user that mean is not empty so the page will not refresh. otherwise if its empty the page must refresh each 5 second -
Django admin add more option oneToMany relationship
I have a situation where I have a question and question have multiple test_cases and outputs. I want add more option like + to have many test_cases and outputs for a single question. Here is my Model: from django.db import models from questions.models import Question class Testcase(models.Model): question = models.ForeignKey(Question, on_delete=models.DO_NOTHING) standard_input = models.CharField(max_length=200, blank=True) standard_output = models.CharField(max_length=200, blank=True) def __str__(self): return self.standard_input And here is my admin.py: from .models import Question from .models import Testcase class TestcaseInline(admin.TabularInline): model = Testcase extra = 1 class TestcaseAdmin(admin.ModelAdmin): pass list_display = ('question', 'standard_input', 'standard_output') inlines = [ TestcaseInline, ] search_fields = ('question', 'st_input') list_display_links = ('question',) list_per_page = 20 admin.site.register(Testcase, TestcaseAdmin) I am getting this error: ": (admin.E202) 'testcases.Testcase' has no ForeignKey to 'testcases.Testcase'." What wrong I am doing? -
Django admin.site.urls only accessible to superuser (The admin login page only accessible to superuser)
What i want is to limit access to the django admin login page to only the superuser. Meaning if you are not the superuser, and try to access http://127.0.0.1:8000/admin - you should be redirected to 404 page , something like that.The means or the custom view to perform this authentication is the challenge. Please somebody assist me with a hint on how to do it? urlpatterns = [ path('admin/', my_custom_function,name="check_if_superuser"), # when somebody hits this url pattern , he/she should be taken to the # function above for checking if superuser befor being redirected to # django admin login page ] and in my views.py i have the following function that does the authentication def my_custom_function(request): if request.user.is_superuser(): #... redirect to django admin login page else: # return render(404_page) yeah something like that. -
django form not getting saved in database
I am working on a django application that contains two forms. The first form is displayed through which an image can be uploaded. Once the image is uploaded an image classifier classifies the image and auto-fills parts of the second form. The second form is displayed once the classification process is completed. This is my code so far upload_image.html template {% block content %} <center><h2>Upload Image</h2></center> <div class="jumbotron"> <div class="row justify-content-center"> <div class="col-6"> <center> <div class="upload-btn-wrapper"> <form action="{{ request.build_absolute_uri }}image_classification/" method="POST" enctype="multipart/form-data" class='first_form'> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile" /> <label for="file" class="btn btn-outline-dark btn-lg btn-block select">Choose a file</label> <input class='btn btn-primary btn-lg btn-block' type="submit" value="Upload image" /> </form> </div> </center> </div> </div> </div> {% endblock content %} upload_item.html template {% block content %} <div class="row justify-content-center"> <div class="col-6"> <center><h2>Item description</h2></center> <div class="card mb-5 mt-3"> <div class="card-body"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form_des|crispy}} <button type="submit" class='btn btn-primary save_btn'>Save item</button> </form> </div> </div> </div> </div> {% endblock content %} views.py def upload_image(request): return render(request, 'upload_image.html') def upload_item(request): if request.method == 'POST': form_des = ItemForm(request.POST, request.FILES) if form_des.is_valid(): try: form_des.save() return redirect('item_list') except: return redirect('item_list') else: form_des = ItemForm() return render(request, 'upload_item.html', {'form_des': form_des}) def handle_uploaded_file(file, filename): if not … -
Django - How to access filtered queryset in the dispatch method?
I have the following code: class MyViewSet(ModelViewSet): ... filter_backends = (...) def dispatch(self, request, *args, **kwargs): response = super(MyViewSet, self).dispatch( request, *args, **kwargs ) ... # do something with the response return response Inside the dispatch method, I can retrieve the filtered data with response.data, so I assume the custom filter backend is working properly. However, I also want to do something with the queryset as well (e.g. calling count()), after the filter has been applied to it. The problem is that self.queryset and self.get_queryset() return the whole, non-filtered queryset. So how do get the version of queryset to which the filter has been applied in the dispatch method? -
How to add postgis extension to postgresql database in gitlab-ci.yml
I'm setting up test stage in gitlab-ci.yml file and I have error, when config postgis extension for postgresql databse. My latest version of gitlab-ci.yml: image: python:3.6 services: - mdillon/postgis - postgres:latest variables: POSTGRES_DB: python-test-app POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres DATABASE_URL: "postgres://postgres:postgres@mdillon-postgis/python-test-app" stages: - test - build test: stage: test image: mdillon/postgis before_script: - apt-get update -qy - export PGPASSWORD=$POSTGRES_PASSWORD - psql -d $POSTGRES_DB -c "CREATE EXTENSION postgis;" - pip3 install pipenv - pipenv install --dev - export DATABASE_URL=$DATABASE_URL script: - pipenv run test I want to have DATABASE_URL for my django env Gitlab Pipeline error response: Running with gitlab-runner 11.5.0 (3afdaba6) on docker-auto-scale fa6cab46 Using Docker executor with image mdillon/postgis ... Starting service mdillon/postgis:latest ... Pulling docker image mdillon/postgis:latest ... $ export PGPASSWORD=$POSTGRES_PASSWORD $ psql -d $POSTGRES_DB -c "CREATE EXTENSION postgis;" psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? ERROR: Job failed: exit code 1 -
What precautions should be taken in advance to create community site in wordpress that may be migrated to django in future?
I am planning to create a community site. I know both wordpress and django. It's concept testing phase. I want to launch product just to test if concept works, how people respond, what changes or customization they need etc. There will be user uploaded data. From what I've researched I've following information: Option 1. Wordpress: pros: It's too easy to create forum or community in wordpress using plugins like bbpress and buddypress, compared to django. Wordpress saves the time required to develop beautiful frontend that'll fit in UI/UX criteria. Any decent paid wp theme compatible with above plugins, can do the job. I find it easier to host wordpress site and get it running. Not much loss if product does not work. cons: I find it difficult to customize wordpress site compared to Django site. This matters in sites where you don't know what kind of customization or feature you may need in future. wordpress is bloat of many third party plugins which only provide full functionality if paid, adding to hidden costs for running the site. Lot of third party plugins MAY hamper performance and data security or user privacy. Option 2-Django: pros: Better control over site and data … -
Ignore file once in git
I'm very much dumb and new in this topic.. I've searched for a clear answer but I didn't find so far. And i'm afraid to ruin my prod server files. So.. I have a server (written in pyhton & Django). I have one file that changes according to the environment (settings.py). I've 3 Boolean variables for 3 environment When running on local computer i'm changing this file accordingly, as well as development server and prod server (which both hosted in Heorku). I'm using sourcetree for managing my git. When i want to test my code in the development server i'm pushing my code from my bitbucket repo 'dev' branch to my heroku git DevServer. but then my settings.py is being pushed as well so i need to configure it back to dev server configuration. And then back to local development and then to dev server again and then to prod server - allot of single file pushes that seems to me that i can avoid. When i'm doing merge from development to master, again this settings.py file will be changed and i need to update it again to match the production environment. Make long story short, I would like to … -
Query with many to many field value of a table
I have this model class Tag(models.Model): tag = models.CharField(max_length=100,unique=True) class Image(models.Model): image_name=models.CharField(max_length=40,unique=False) image=models.ImageField(upload_to='photos/') tags = models.ManyToManyField(Tag) The view is like this: class ImagePostAPIView(mixins.CreateModelMixin,generics.ListAPIView): queryset = Image.objects.all() query = Tag.objects.all() serializer_class = imagesSerializer def get_queryset(self): tag_value = self.request.query_params.get('tags', None) if tag_value is not None: try: queryset=Image.objects.filter(tags=tag_value) except: pass return queryset I am able filter the data using the tag_id but i want to filter using the tag value. My url look like this: GET /images/?tags=banner How to achieve this in Django ? -
How to write this raw SQL query using django querysets?
I have 2 models in defferent apps: app1/model.py class BookRatings(models.Model): book = models.ForeignKey('app2.Book', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=User) rating = models.PositiveSmallIntegerField(default=0, help_text='Book Rating out of 10') app2/model.py class Book(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=50) description = models.TextField(max_length=500) I wanted to get the average ratings of each book in descending order with all the details of the book and also be able to access the methods in Book models like get_absolute_url(), so I started with trying to use the below code BookRatings.objects.values('book').annotate(rating_avg=Avg('rating')).order_by('-rating_avg') This indeed gave me the right values (book id and rating_avg) but it was hard to get all the fields of the foreign key model book. Like book title or description. I searched a little and found out that I could just add more columns in values and made it like BookRatings.objects.values('book','book__title','book__description').annotate(rating_avg=Avg('rating')).order_by('-rating_avg'). But still this would not let me access the methods in the book model like get_absolute_url. I tried book__get_absolute_url in values and it gave an error that it is not a field of book. Since I already knew SQL directly I successfully created a raw sql statement that gets everything that I need. Book.objects.raw('select rb.*,(select avg(rating) from app1_bookratings as ab where ab.book_id=rb.id group by … -
Checkbox Value of Array in Django
I am passing array into my view using checkbox input field. How can i get that array accesses[value][value] in my view with value="1" or "0". I am also using request.POST.getlist('accesses') in my view but it is giving me value then how can i get array. Example - accesses[3][25] values. Template.html <input type="checkbox" name="accesses[3][25]" value="1" checked autocomplete="off"> <input type="checkbox" name="accesses[2][15]" value="1" autocomplete="off"> <input type="checkbox" name="accesses[4][95]" value="1" autocomplete="off"> <input type="checkbox" name="accesses[5][10]" value="1" checked autocomplete="off"> View.py def AclView(request): accesses = request.POST.getlist('accesses') -
Django get multiple inputs with one Charfield
I have a list created in my Django views ,i am iterating on that list in my edit_files.html and putting A CharField near every item of a list and showing in HTML page. So when When want to get texts inputted in fields i click submit and only get the input of the fields . My question is how to get all inputs in a list ? edit_files.html so in {{ each_var }} {{ form.as_p }} i have the name of list item with the CharField {% block content %} <form action="." method="POST" enctype="multipart/form-data">{% csrf_token %} {% if variables %} {% for each_variable in variables %} {% for each_var in each_variable %} {{ each_var }} <br/>{{ form.as_p }} {% endfor %} {% endfor %} {% endif %} <input type="submit" value="Save" class="btn btn-primary"/> </form> {% endblock %} views.py You can look only on 2nd part of views def edit_files(request, file_id): instance = get_object_or_404(DocFile, id=file_id) exact_file = Document(instance.document) variables = [] for paragraph in exact_file.paragraphs: match = re.findall(r"\{(.*?)\}", paragraph.text) variables.append(match) for table in exact_file.tables: for row in table.rows: for cell in row.cells: match = re.findall(r"\{(.*?)\}", cell.text) variables.append(match) exact_file.save('green.pdf') # print(variables) my_form = RawProductionForm() if request.method== "POST": my_form = RawProductionForm(request.POST) if my_form.is_valid(): print(my_form.cleaned_data['title_forms']) … -
How to upgrade add_to_builtins function to django 1.9 and later
I need to upgrade an old project to django 1.11, and I found that the function add_to_builtins is removed in django 1.9. I wonder how can I achieve the same functionality. The package is django-coffin and it seems like it hasn't been maintained for a while. Here (https://github.com/cdleary/coffin/blob/master/coffin/common.py) in line 114, it loads the django default templates as class instances and process it in line 70 here (https://github.com/cdleary/coffin/blob/master/coffin/template/library.py). After I removed the add_to_builtins function by adding them directly in to the settings.py file as follows: TEMPLATES = ( { 'BACKEND': 'some backend', }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.core.context_processors.request', 'django.contrib.auth.context_processors.auth', ], 'builtins': [ 'coffin.template.defaulttags', 'coffin.template.defaultfilters', 'coffin.templatetags.static', ], } }, ) I can get the default builtins as follows: from django.template.engine import Engine django_builtins = Engine.default_builtins for lib in django_builtins: _load_lib(lib) The problem is that the django_builtins return a list of strings, which cannot be called as an instance and get the tags in the line 70 described above. I wonder if there is a way to fix this, any advice is much appreciated!! -
django how to get context item by name
I am rendering a few tables which I add to the context in the view from .models import MyModel from .tables import MyModelTable def index(request): context = dict(all_tables=[]) template = 'mypage/index.html' for x in some_list: if some_condition(x): context[x] = MyModelTable(get_some_data(x)) context['all_tables'].append(x) context['all_tables'] = sort_my_way(context['all_tables']) return render(request, template, context) And then I try to iterate over the list and create the tables on by one. However, I can't figure out how to get the table from the context using the string name. index.html {% load django_tables2 %} {% load render_table from django_tables2 %} <!doctype html> <html> <link rel="stylesheet" href="{% static 'css/my.css' %}" /> <body> {% for t in all_tables %} {% if t %} <H3>{{ t }}</H3> {% render_table t %} <--- How can I get the table with name t from context <br/> {% endif %} {% endfor %} </body> -
Need help on how to develop a website where people can login and read books?
I want to develop a website where people can login and read a book which were posted by a publisher. So, can you guys suggest what technologies to use . I want to use python Django for backend but feel free to suggest any other way to develop this project. -
getting the uploaded image name using ImageField in Django and how to give autogenerated name to resized image before storing
1.GETTING THE NAME OF UPLOADED IMAGE USING ImageField: I am using ImageField to store the image getting from post request in a particular path. it is returning the image path instead of the image name This is my model: image_ref is the global variable class IMGResize(models.Model): image = models.ImageField(upload_to='ImgResize', blank=True) class Meta: db_table = 'imgresize' def __str__(self): return self.image def save(self,force_insert=False, force_update=False, using=None): if not self.image: return super(IMGResize, self).save() global image_ref image_ref = self.image super(IMGResize, self).save() here it is generating some default name for the image,how can i get the name of the image 2. how to autogenerate the name to the resized image: Here in my previous model i am getting some image which i am trying to resize and store in some other path using some other model in the same models.py file this is my model: from .resize_code import image_resize class Profile(models.Model): image = models.ForeignKey(IMGResize, related_name='profiles', on_delete=models.CASCADE) name=models.CharField(max_length=10) image_width=models.PositiveIntegerField(null=True, blank=False) image_height=models.PositiveIntegerField(null=True, blank=False) class Meta: db_table = 'profiles' unique_together=('name','image') def __str__(self): return self.name def save(self,force_insert=False, force_update=False, using=None): global image_ref super(Profile, self).save() image_resize(self,image_ref) super(Profile, self).save() here is my resize_code.py file: def image_resize(self,image,force_insert=False, force_update=False, using=None): if not image: return img = Image.open(os.path.abspath(str(image)), 'r') img = resize_contain(img, [self.image_width, self.image_height]) path='resized_images/contain.jpeg' img.save(path, … -
factory_boy creation test fail when running together, but success when running alone
I used django for my project to create something like management system. So I created a table for address and want to seed the data using factory_boy. Here's a snippet: # Some snippet.... class StateFactory(factory.django.DjangoModelFactory): class Meta: model = State name = factory.Faker('state') short_code = factory.Faker('state_abbr') country = factory.Iterator(Country.objects.all()) class CityFactory(factory.django.DjangoModelFactory): class Meta: model = City name = factory.Faker('country') state = factory.Iterator(State.objects.all()) # end snippet.. So I tried to make a test for this factory, here's the test_factories snippet: # Some snippet... class StateFactoryTest(TestCase): def setUp(self): factories.CountryFactory.create() def test_create_many_states(self): total_states = 10 factories.StateFactory.create_batch(total_states) self.assertEqual(models.State.objects.all().count(), total_states) class CityFactoryTest(TestCase): def setUp(self): factories.CountryFactory.create() factories.StateFactory.create_batch(2) def test_create_many_cities(self): total_cities = 10 factories.CityFactory.create_batch(total_cities) self.assertEqual(models.City.objects.all().count(), total_cities) # end snippet... If I run test for each Testcase, it would run succcesfully. But if I run all tests as one, it would fail with error messages (similar for every test classes) like this: ====================================================================== ERROR: test_create_many_cities (abadfasdf.tests.apps.locations.test_factories.CityFactoryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/abcd/miniconda3/envs/abadfasdf/lib/python3.7/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.IntegrityError: insert or update on table "locations_state" violates foreign key constraint "locations_state_country_id_25677d21_fk_locations_country_id" DETAIL: Key (country_id)=(1) is not present in table "locations_country". There's no migration/database error. I think the problem is with how TestCase rollbacks the data each test. … -
How to resolve Undefined variable models error, in Python-Django Framework
Following is the code in views.py class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('name','description') model = Group class SingleGroup(generic.DetailView): model = Group class ListGroups(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse("groups:single",kwargs={"slug": self.kwargs.get("slug")}) def get(self, request, *args, **kwargs): group = get_object_or_404(Group,slug=self.kwargs.get("slug")) try: GroupMember.objects.create(user=self.request.user,group=group) except IntegrityError: messages.warning(self.request,("Warning, already a member of {}".format(group.name))) else: messages.success(self.request,"You are now a member of the {} group.".format(group.name)) return super().get(request, *args, **kwargs) class LeaveGroup(LoginRequiredMixin, generic.RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse("groups:single",kwargs={"slug": self.kwargs.get("slug")}) def get(self, request, *args, **kwargs): try: membership = models.GroupMember.objects.filter( user=self.request.user, group__slug=self.kwargs.get("slug") ).get() except models.GroupMember.ObjectDoesNotExist: messages.warning(self.request, "You can't leave this group because you aren't in it." ) else: membership.delete() messages.success( self.request, "You have successfully left this group." ) return super().get(request, *args, **kwargs) I am developing a social media clone site using Django. I had created the views for implying Groups and Group Members, and their membership. It gives the error as: Undefined variable 'models' 'GroupMember' has no 'objects' member -
Trying to make my navbar-brand a link to home page
It's not working I keep getting #top page any suggestions <nav class="navbar navbar-expand-lg navbar-dark fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="{%url'home'%}">Bootstrap</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav text-uppercase ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="{% url 'home' %}">Home</a> </li> -
Using Django to Dynamically Create New URLs/Pages
I am working on a program that allows users to create pages to monitor and manage tournaments that may be going on at their high schools and colleges, specifically MUN and Forensics tournaments. Whenever the user logs in, he or she has the option to create a new tournament, which should create a new URL and base web page for them, where they can edit the tournament to their liking. For instance, if a user created a tournament named "Hello World," then I want to be able to make them a page they can visit at example.com/helloworld. Are there any built in Django functions that can help with something like this? -
How do I properly use of a large JSON file
I have an 80mb JSON file that contains nearly all of the data my site will work with. I'm unsure of how to proceed with this data. Is it possible (recommended?) to simply host the JSON file alongside my web app and access it whenever I need data? I have experience with Django and have been planning on parsing the JSON into Django models and storing it within a database and using Django-Rest-Framework to communicate between the front-end (Vue.js2) and back-end, but I am curious what others out there recommend. -
Django - cannot retrieve username in admin after form submission
I have a form to when a user makes a form submission I need the current logged in user to automatically populate in the django admin. I would like the current user's username to populate in the column where it says User in the django admin. Screenshot attached. How do I execute that correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'get_username'] list_filter = ['name', 'zip_code', 'created', 'updated',] def get_username(self, obj): if obj.user is not None: return obj.user.username return '-' get_username.short_description = 'User' admin.site.register(Listing, UserProfileAdmin) #user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): # user … -
How to implement chat between users in a Django blog website ?
Currently I'm working on a small project (for a course in University) that is building a blog website and I decided to use Django framework version 2.1.4, my python version is 3.7.1. One of the required feature for this blog website is: User can add others as friends, and he can see the list of his friends who are online and choose 1 of them to chat with. I'm getting stuck to find an efficient way to implement that feature, can anyone suggest a proper solution ? Thanks so much.