Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django questionnaire with several score categories per answer
I am very new to Django (and definitely rusty with HTML) and basically went through the official tutorial a couple of times. I am planning on creating a simple questionnaire with a list of questions, these questions can have several answers and each answer has a specific score for various categories. In the end the points for each category are added and depending on the score a message is displayed. I am a bit stuck on how to display the answers for each question in a template however. I am also unsure how to calculate the final score: should I create a new class in my models to store the score? Or should I just do it in views.py (I would prefer this solution for now, I don't need to store the score in the DB and I don't need to login a user)? Here is what I have so far: models.py from django.db import models class Questionnaire(models.Model): questionnaire_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.questionnaire_text class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete = models.CASCADE) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length=200) C1 … -
Problem with the presentation of data from the database on the html page in Django
I have a problem creating something like this in the html file, of course based on the data from the database and using loop: Cycle_title1 post_title1 post_title2 post_title3 Cycle_title2 post_title1 post_title2 post_title3 where post_title are post titles which was added to subsequent cycles I tried do it in this way, but it return only one set of titles: #views cycles = Cycle.objects.filter(author=user) for cycle in cycles: c_post = Post.objects.filter(cycle__title__startswith=cycle.title) context = { 'posts': posts, 'user': user, 'u_form': u_form, 'p_form': p_form, 'cycles': cycles, 'c_post': c_post, } print(c_post) return render(request, 'users/profile.html', context) #html {% for cycle in cycles %} <h4>{{cycle.title}}</h4> {% for c in c_post %} <h5>{{ c.title }}</h5> {% endfor %} {% endfor %} #my_models: class Post(models.Model): title = models.CharField(max_length=50, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Cycle(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ManyToManyField(Post) -
Django Azure ad AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application
I am trying to authenticate a user using azure active directory but I am getting `AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application I am using django-microsoft-auth library. I have referred to multiple StackOverflow question regarding this but none of them resolve my issue. None of them are Django specific settings.py """ Django settings for mywebapp project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wi31*5al3v=&or_p354489830j)w_zr-)1^a$m*=@yo1l62nni' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'microsoft_auth', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mywebapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Query on a model field? Is it possible in models.py?
I have a model called StudentProfile: class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class_advisor = models.CharField(max_length=50) year = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null=True) section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True) what I want to happen is, class_advisor to only return and accpet User with is_teacher = True. by the way here's my User model: class User(AbstractUser): email = models.EmailField( max_length=254, unique=True, verbose_name='Email Address', blank=True ) is_student = models.BooleanField(default=False, verbose_name='Student') is_superuser = models.BooleanField(default=False, verbose_name='Administrator') is_teacher = models.BooleanField(default=False, verbose_name='Teacher') is_staff = models.BooleanField(default=False, verbose_name='Staff') is_registrar = models.BooleanField(default=False, verbose_name='Registrar') -
Django nginx 502 bed get way
I am learing nginx for django, i am running the server in locally with docker. this is my django_nginix.conf file : server { listen 80; listen [::]:80 default_server; server_name musicaldd.com; client_max_body_size 90M; location /media/ { root /home/pyking/cpd/musicaldd_back/storage/; } location /static/ { root /home/pyking/cpd/musicaldd_back/storage/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://djangoapp:8000/; } } When I run the server creating docker images and hit the URLs, it returns me 502-bed getaway timeout | nginix Can anyone tell me why this errors occuse, how can I fix this error It may stupid question but this is very serious to me, coz, i am new on Nginx, it will really much be appreciated if you help me to fix this -
Modifying HTML Elements with Python Dictionary in Beautiful Soup
I am getting 'NoneType' object does not support item assignment, when trying to modify HTML elements using Beatiful Soup and a Python dictionary. This is for a program that will create a HTML file from a template. The values to change are received from the user in a form. Here is the code I have at the moment data = { 'banner-url': ['src', request.POST.get('banner_url')], 'banner-link': ['href', request.POST.get('banner_link')], 'title-text': ['text', request.POST.get('title-text')] } # Loop through the data dictionary and let Beautiful Soup find element with ID's that match the data[key] for key, value in data.items(): _temp = soup.find(id=key).value[0] = value[1] I would like to modify HTML elements using keys and values in a Python dictionary. When I run the program I get the NoneType error instead of the element being modified. The error is on the line _temp = soup... -
NOT NULL constraint failed: users_user.email
I just created a custom user Model and a custom user manager. I'm able to create superuser with manage.py createsuperuser, but when it comes to update, delete or even create a new user on the admin panel, I have this wierd error : NOT NULL constraint failed: users_user.email I have no idea how to fix it and I'm just stuck. Here is my model and my manager : class UserManager(BaseUserManager): #custom create_user method def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email) ) print(email) user.set_password(password) user.save(using=self._db) print(user) return user #Custom create_super_user method def create_superuser(self, email, password=None): user = self.create_user( email = email, password = password ) user.admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): #setting up Choices for interest, Must add other fields ... #interests = MultiSelectField( # max_length = 2, # choices = INTERESTS_CHOICES #) #Setting up a Ranking System email = models.EmailField( max_length=50, unique=True, blank=False, null=False ) username = models.CharField( max_length=25, unique=True, null=True, blank=True ) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=70) birth_date = models.DateField(null=True, blank=True) reputation = models.PositiveIntegerField(default=0) active = models.BooleanField(default=True) rank = models.CharField(choices=RANKING_CHOICES, max_length=5, default="basic") is_staff = … -
Localstorage arrays to be saved in Database using Django
I am having problems with a certain code. I'm still new to Django and Jquery. So I have a form, and all the fields are stored directly in the database using the views.py in and I'm using self.request.POST['var'] for each element that I'm saving in the back end. It works, but my problem is, how can I store multiple arrays from local storage. Since, I'm also working with a modal where I'll enter certain values. The values are stored in an itemlist and publishes a table row, for each time I click add, in the modal. I want to get all those items/elements and save it in the database. I've tried to use the self.request.POST but i keep on getting an error like MultipleInvalid entry. I'll send my code here, thanks -
Python-Django FieldError: Cannot resolve keyword 'XXX' into field
I am trying to create a small tracking app with a number of foreign key relations between models. After completing with the migrations, while trying to access the list page for teammembers model, I am getting the following error: "Cannot resolve keyword 'date_last_modified' into field. Choices are: assigned_lead, current_status, date_of_joining, designation, email, first_name, id, last_name, location, project_team_member, ts_project_team_member" However, I am able to add new teammember record using the admin panel and also able to access detail view of other models as well. Below sharing the models.py file I am using. I am fairly new to django, any help appreciated. Thanks in advance. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Project(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) primary_contact1 = models.CharField(max_length=100) primary_contact2 = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() current_status = models.CharField(max_length=100) code = models.CharField(max_length=10) type = models.CharField(max_length=50) new_VS_existing = models.CharField(max_length=50) source = models.CharField(max_length=50) engagement = models.CharField(max_length=50) owner = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) date_last_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Teammember(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) location = models.CharField(max_length=50) designation = models.CharField(max_length=50) date_of_joining = models.DateField() current_status = models.CharField(max_length=50) … -
Django factory boy pass fuzzy attribute to related factory
I'm trying to keep the line_weight and line_price values consistent across both factories so that Order.total == OrderLine.ext_price but that's not the case. It seems that they randomize again in RelatedFactory. How can the values be random each time InvoiceFactory is called but pass the same values to InvoiceLineFactory? class InvoiceFactory(factory.DjangoModelFactory): class Meta: model = Order exclude = ('line_price', 'line_weight') line_price = factory.fuzzy.FuzzyInteger(1, 100) line_weight = factory.fuzzy.FuzzyInteger(1, 100) total = factory.LazyAttribute(lambda _: _.line_price * _.line_weight) line = factory.RelatedFactory( 'order.factories.InvoiceLineFactory', 'order', price=line_price, weight=line_weight ) class InvoiceLineFactory(factory.DjangoModelFactory): class Meta: model = OrderLine ext_price = factory.LazyAttribute(lambda _: _.weight * _.price) -
Permission class in Django
I use Django group permissions, I can assign some permission for users. Here is my test scenario: I have a Company Model, User1.hasPerm -> view_company, change_company, add_company, delete_company Permissions.py: class HasPermissions(permissions.BasePermission): def has_permission(self, request, view): if request.user.has_perm('MYAPP.view_company'): return True else: return False if request.user.has_perm('MYAPP.change_company'): return True else: return False if request.user.has_perm('MYAPP.add_company'): return True else: return False if request.user.has_perm('MYAPP.delete_company'): return True else: return False return True CompanyView.py: class CompanyViewSet(ModelViewSet): queryset = Company.objects.all() filter_class = CompanyFilter serializer_class = CompanySerializer permission_classes = [IsAuthenticated, HasPermissions] def get_queryset(self): if self.request.user.is_authenticated and self.request.user.is_active: company = Company.objects.filter(companyUser__exact=self.request.user) return company else: return Company.objects.all() I wrote HasPermissions function to control user permissions, and this function works only CompanyView. I want to make global this function for I can control all view. HasPermissions function is like hard coding, I want to change the more usable version to control all views. How can ı do this? -
Jupyterlab for Flask or Django web development
I recently found out about Jupyterlab. I like the improvement over plain Notebooks. I was hoping we could actually use Jupyterlab as an online IDE for web development of Django, Flask or other projects. I don't like developing in a local environment. However I cannot find anything about using Jupyter for web development. Not in the Github repo or on Google. Opening normal .py the tab function to list all functions, classes etc don't work. This also doesn't work when importing a .py file in a .ipynb file. Using nbconvert and p2j to convert all files back and forth from .py to ipynb and vice versa isn't a really efficient. And besides this, another issue with this approach is that if you import nb 2 in nb 1 and you change something in nb 2 you have to restart the entire kernel of nb 1 in order to have the changes take effect. Only rerunning the import or importlib.reload(nb2) doesn't work. Is there a good approach to this? -
Postgresql query generated by django works too slow
I have a query like select id from x where is_valid=true and id in (select another_id from y where (other_id in (1, 2, 3, 4, 5, 6, 7, 8, 11, 16, 17, 18, 19, 20, 21, 22, 24, 26, 27, 28, 30, 31, 32, 34, 35, 36, 37, 38, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 63, 65, 67, 69, 72, 73, 76, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 98, 100, 101, 102, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 121, 127) and is_valid=true));. I have index on is_valid fields and also has index together on other_id and is_valid. X table has +900k and Y table has +15M entry in them. another_id and other_id fields are primary keys of Y table. This query takes place at least 30sec to perform and it is a problem for API to response. I am using PostgreSql 9.6 and Django 1.11 for development. Can you suggest a way to faster this operation? -
How to properly throw error to user from admin's save_formset method?
I have ModelAdmin with customized save_formset() method. It this method I call thirdparty API, do some loginc and accordingly do save instances. Sometimes this API returns error so I need to handle it and show user error telling that data in inline forms must be changed. I can't find the way to return the error properly. Django docs warns us that if we override ModelAdmin.save_model() or ModelAdmin.delete_model(), we must save the object in any ways. Does this rule also applies to ModelAdmin.save_formset() too? -
Remove perviously added values from template created using Formset
I'm able to save values in database using Formset but when I tried to create one more form then perviously added values are getting showed in the template. This is a strange issue but I want to know how to solve this issue. -
Editing Django Form Field
I am using django with AngularJS to create a form view, which takes details from user and stores it. Now I wish to edit those details by going to the detail view page for a particular entry. How do I do that, so that I can use already created templates? -
Using interactive shell with Dropwizard
So recently I started trying out Dropwizard since I wanted to learn how to build a REST service using Java. Btw I have worked with Django and python but have no experience with Java. Is there a way to use a interactive shell in Dropwizard like the one which Django provides using python manage.py shell -i ipython. I'm using Java 8. I know JShell has been integrated with Java 9 but Dropwizard uses JDK 8. -
How to recieve not all fields from related(ForeignKey) django model using 'select_related'
Env: python >= 3.6 Django >=2.1.0 Models example: class A(models.Model): id = models.AutoField(primary_key=True) a_field = models.CharField(max_length=256, default="example") class B(models.Model): id = models.AutoField(primary_key=True) b_field = models.CharField(max_length=256, default="example") a = models.ForeignKey(A, related_name="b", on_delete=models.CASCADE) Question: How I can fetch only required fields from related models using select_related() How it could be done with prefetch_related: from django.db.models import Prefetch prefetch_obj = Prefetch("a", queryset=A.objects.only("id", "a_field")) B.objects.only("id", "b_field", "a").prefetch_related(prefetch_obj) But it produces 2 request to DB due to prefetch_related using. SELECT `main_b`.`id`, `main_b`.`b_field`, `main_b`.`a_id` FROM `main_b` LIMIT 21; args=() SELECT `main_a`.`id`, `main_a`.`a_field` FROM `main_a` WHERE `main_a`.`id` IN (1); args=(1,) If I use select_related it makes 1 DB call, but fetches all fields from A model: models.B.objects.only("id", "b_field", "a").select_related("a") SELECT `main_b`.`id`, `main_b`.`b_field`, `main_b`.`a_id`, `main_a`.`id`, `main_a`.`a_field`, `main_a`.`a_not_required_field` FROM `main_b` INNER JOIN `main_a` ON (`main_b`.`a_id` = `main_a`.`id`) LIMIT 21; args=() -
How to create a variable from an url?
My URL takes a variable "payment_option" like this: path('payment/<payment_option>/', PaymentView.as_view(), name='payment') I want to show that variable in the template rendered out by PaymentView. The problem is that "payment_option" isn't a paramenter in my models (like pk or a slug) but his value is got from a form handled by another view. class CheckoutView(View): [...] def post(self, *args, **kwargs): form = CheckoutForm(self.request.POST or None) [...] payment_option = form.cleaned_data.get('payment_option') if payment_option == 'S': return redirect('core:payment', payment_option='stripe') elif payment_option == 'P': return redirect('core:payment', payment_option='paypal') Hope my explanation was as clear a possible, I'm new to Django so any hint or suggestion is really appreciated. -
Trying to pass request image from Django to Python script
Im creating a project where i'm sending a Request with an image to my Django local server. The image is received and saved which works fine. However, after receiving the image i am trying to pass the file to my python Script. There it should run the script with the image and return data back to the user. Im stuck as i can't seem to pass the image filename to the python script and therefore run the script with the image. Does anyone know how this can be done? The many (#):s are my attempts to do this. views.py class ImageViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): """ Upload image (Save and Run Script) """ parser_classes = (JSONParser, MultiPartParser, FormParser,) queryset = UploadImageTest.objects.all() serializer_class = ImageSerializer def output(self, request): imagename = request.FILES['image'] #imagename = request.data['image'] #imagename = models.ImageField #imagename = request.FILES['image'].name #imagename = UploadImageTest.image print(imagename) #self.request.FILES['image'] #inp = request.data['image'] inp = request.FILES.get(imagename) out = run([sys.executable,'//Users/macbookpro//LivlymapAPI//venv//Livlymap_Textcrawl.py',inp],shell=False,stdout=PIPE) print(out) return {"status": "Success", "output": str(out)} Serializer.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImageTest fields = ('id', 'name', 'description', 'image') models.py class UploadImageTest(models.Model): permission_classes = (IsAuthenticated,) name = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to="images/", null=True, blank=True) def __str__(self): return "{}".format(self.name) Python Script file_name = sys.argv[1] print(file_name) img = … -
Adapt wagtail tag filter to include an operator so multiple tags can be searched
I have a working search form on my Wagtail template that finds pages based on their tags but as there is no operator (AND or OR) only one tag can be searched at a time. Can someone advise me how I would adapt this code to allow for multiple tag searches? models.py tag_posts = PostsPage.objects.live().public().order_by('-first_published_at') if request.GET.get('tag', None): tags = request.GET.get('tag') tag_posts = tag_posts.filter(tags__slug__in=[tags]) # Paginate all posts by 2 per page paginator = Paginator(tag_posts, 2) # Try to get the ?page=x value page = request.GET.get("page") try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context["posts"] = tag_posts return context search_page.html <form role="search" method="get" class="form-search" action="posts" method="get"> <div class="input-group"> <input type="text" class="form-control search-query" name="tag" placeholder="What are you after?" title="Search for:" /> <span class="input-group-btn"> <button type="submit" class="btn btn-default" name="" id="searchsubmit" value=""> <span class="btn btn-default">GO</span> </button> </span> </div> </form> -
How to pass variable inside translation tag [duplicate]
This question already has an answer here: django translate variable content in template 8 answers Is there any way to pass app variable or any data from database inside {% trans %} tag ? I tried {%blocktrans%} but it doesn't work. views.py def index(request, *args, **kwargs): carousel = CarouselImage.objects.all() return render(request, 'home.html', {'carousel':carousel}) models.py class CarouselImage(models.Model): title = models.TextField() subtitle = models.TextField(default='') img = models.ImageField(upload_to='carousel_images') objects = models.Manager() home.html {% for slide in carousel %} <h2>{% trans 'Need object from slide here'%}</h2> {% endfor %} -
Remove object from list in Django
I'm developing tags system and I need to show similar objects by tags (ManyToMany relationship). How can I remove current opened object from QuerySet with similar objects? Main object page: similar objects - QuerySet [Checklist: Main object page, Checklist: Simple tasks, Checklist: nocat] How can I remove "Checklist: Main object page" from QuerySet? class ChecklistView(DetailView): model = Checklist template_name = 'checklistapp/page_checklist.html' def get_context_data(self, **kwargs): context = super(ChecklistView, self).get_context_data(**kwargs) context['tag_checklists'] = [] for tag in Tags.objects.filter(checklist=self.object): checklists = Checklist.objects.filter(tags=tag) context['tag_checklists'].append({ 'checklist': checklists }) return context -
Django: saving the Form does not work (The ModelForm Filters the ForeignKey choices by request.user)
I Managed to Filter the ForeignKey choices "Context.name" by "request.user" with the Code Below. First, I defined the Models. models.py class Extension(models.Model): username = models.CharField(primary_key=True, max_length=200, help_text='') callerid = models.CharField(max_length=200, help_text='') extension = models.CharField(max_length=3, help_text='') firstname = models.CharField(max_length=200, help_text='') lastname = models.CharField(max_length=200, help_text='') password = models.CharField(max_length=200, help_text='') context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True) def get_absolute_url(self): return reverse('extension-detail', args=[str(self.username)]) def my_get_absolute_url(self): return reverse('my-extension-detail', args=[str(self.username)]) def __str__(self): return self.username class Context(models.Model): name = models.CharField(primary_key=True, max_length=200, help_text='') countryprefix = models.CharField(max_length=200, help_text='') cityprefix = models.CharField(max_length=200, help_text='') number = models.CharField(max_length=200, help_text='') extensionsfrom = models.CharField(max_length=200, help_text='') extensionstill = models.CharField(max_length=200, help_text='') portscount = models.CharField(max_length=200, help_text='') def get_absolute_url(self): return reverse('context-detail', args=[str(self.name)]) def my_get_absolute_url(self): return reverse('my-context-detail', args=[str(self.name)]) def __str__(self): return self.name According to this model I created a ModelForm with an initial section init, in wich the username will be grabbed. The available contexts will then be filtered by the username. forms.py class MyExtensionCreateForm(forms.ModelForm): def __init__(self, context, *args, **kwargs): name = kwargs.pop('user') super(MyExtensionCreateForm, self).__init__(*args, **kwargs) self.fields['context'].queryset = Context.objects.filter(name=name) class Meta: model = Extension fields = '__all__' Than in the view i bassicly want to just save the to the database. The get_form_kwargs part of the view will pass the username to the ModelForm so we can filter the choices like … -
how to upload big file in django using temp folder
2 I know how to upload multiple files through django, but I have a problem when uploading a folder if there are subfolders in it. The django can't receive subfolders. I found the reason, because browser use '.' to represent a folder, but django can't parse it then stop parsing. Is there an elegant way to fix it?