Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrating for Django-Oscar-Accounts gives an error message
I followed the instructions given in the documentation for Django oscar accounts found here and installed Django Oscar accounts using pip install django-oscar-accounts, then I added oscar_accounts to my INSTALLED_APPS. then I ran the command ./manage.py migrate oscar_accounts, after this I get the error: ModuleNotFoundError: No module named 'oscar_accounts' so in my settings.py file I changed oscar_accounts to accounts, then when I run the same manage.py command I get the error: File "/project_path/env/lib/python3.6/site-packages/accounts/abstract_models.py", line 5, in <module> from django.core.urlresolvers import reverse ModuleNotFoundError: No module named 'django.core.urlresolvers' How do I solve this? I am using Django-oscar 1.6.1 and python 3.6 -
Django + Angular6 + Jenkins + Docker + AWS Deployment
Versions Angular 6 Django version 2.1.2 Python 2.7.12 Angular CLI 6.1.0 OS: linux x64 Docker version 18.06.1-ce docker-compose version 1.21.2 Dockerfile FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ docker-compose.yml version: '3' services: db: image: postgres web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db Above are the versions and Docker files, we are using in our project. We deployed our project using Angular-6 with Django framework with the help of Jenkins and Docker in AWS server. We created a dist file of the Angular-6 project using (ng build) and then pasted that dist file inside our Django project.We used template to display the frontend structure. We have given the static path like this: STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(file)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) Are we are going in the right track or not please help if there are any other possible ways. Thank you.. Github link - https://github.com/p1212/Angular6_Django_Jenkins_Docker_AWS -
customize django admin page to add a drop down list
How can I customize a django admin page where when I click on a button it should show a drop down list where I can select values? -
Accessing view that rendered the template from the template in django
I was wondering if it is possible to determine which view rendered a specific template in Django (or get a boolean result). For example: {% if this_view %} some code {% else %} some other code {% endif %} I'm probably way off but I was wondering how we could create similar conditional statement within the template. Any help would be much appreciated! -
Django class based view to query database from form and display results
So I am completely new to Django, I want to have a user enter a keyword into an HTML form then have each row from the database where an attribute matches that keyword displayed on the page. I've tried various ways of doing this and am not sure what I am doing wrong. Any help would be appreciated. search.html <div class="container"> <form method="GET" action="{% url 'search' %}"> <div class="form-group"> <input type="text" name="make" placeholder="Car Make" /> <label> <button type="submit" class="btn btn-danger"> Go </button> </label> </div> </form> {% if results %} <table> <tr> <th scope="col"></th> <th scope="col">Car Make</th> <th scope="col">Car Model</th> <th scope="col">Car Type</th> <th scope="col">Number of Seats</th> <th scope="col">Price</th> </tr> {% for item in results%} <tr> <td>{{item.makename}}</td> <td>{{item.model}}</td> <td>{{item.seriesname}}</td> <td>{{item.seatingcapacity}}</td> <td>{{item.pricenew}}</td> </tr> {% endfor %} </table> {% endif %} </div> views.py class SearchView(TemplateView): template_name = 'carproject/search.html' model = Vehicles def get(self, request): form = AdvancedSearch() return render(request, self.template_name, {'form': form}) def search(self, request): makequery = self.request.GET.get['make'] if makequery: results = self.Vehicles.objects.filter(makename__icontains(makequery)) return render(request, self.template_name, {'results': results}) Models.py class Vehicles(models.Model): carid = models.IntegerField(db_column='CarID', primary_key=True) makename = models.CharField(db_column='MakeName', max_length=45) model = models.CharField(db_column='Model', max_length=45) seriesname = models.CharField(db_column='SeriesName', max_length=45) seriesyear = models.TextField(db_column='SeriesYear') pricenew = models.IntegerField(db_column='PriceNew') fuelsystem = models.CharField(db_column='FuelSystem', max_length=45) enginesize = models.CharField(db_column='EngineSize', max_length=10) tankcapacity = … -
Django admin export issue
admin.site.register(RegistrationOTP) class RegistrationOTPResource(resources.ModelResource): class Meta: model = RegistrationOTP export_order = ('country','phone_number','otp','created_date','is_verified') class RegistrationOTPAdmin(ImportExportModelAdmin): resource_class = RegistrationOTPResource here is models.py class RegistrationOTP(models.Model): country = models.ForeignKey(Country,on_delete=models.CASCADE, related_name='otp_country', default=1) phone_number = models.CharField(max_length=13)#, unique=True, validators=[phone_regex], otp = models.PositiveIntegerField() created_date = models.DateTimeField(auto_now=True) is_verified = models.CharField(choices=YES_OR_NO, default='no', max_length=10) def __unicode__(self): return '%s : %s'% (self.phone_number, self.otp) Here i am doing as per documentation but it is not showing export csv option in admin -
Group by status type and count entries
I want to group my items by the status. I have 5 status types but I'm only interest in the following: good, moderate, bad The output of the query should be like this: (good, moderate) = 10 bad = 5 My current query looks like this but it's not working: Product.objects.values('status').annotate( Count('status', filter=Q( status__in=('good', 'moderate') )), Count('status', filter=(Q(status='bad'))), ).order_by('status') -
How can I do more things in the API View?
I have a ServiceCreateAPIView: class ServiceCreateAPIView(CreateAPIView): serializer_class = ServiceSerializer permission_classes = [IsSuperAdmin] queryset = Service.objects.all() and in it, I want to do another thing after I created it. how can I realize it? -
Connect Mongodb with Django
I am trying to connect mongodb with django, but i am getting this error ImproperlyConfigured: 'djongo' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3' I have read posts but they are all old and not helping me. I have created mongodb database using studio 3T, name of database is NewDataBase user is gsc-30310 port is 27017 host is localhost versions i am using python 3 Django==2.1.1 mongoengine==0.15.3 pymongo==3.7.1 Here is my settings.py file, please tell me how to setup for new version of django and python 3. thanks """ Django settings for RestUserAPI project. Generated by 'django-admin startproject' using Django 2.1.2. 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 import mongoengine # 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 = '3==2yxbjdvt+hkqm#*%s7cs4g(_+cus9pdup%bxd*uk03g^&w%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
How to show page items count in django pagination for CBV?
everyone! I'm trying to figure out how to show something like "Showing 1-10 of 52" using django pagination in my templates. I am using CBV for my application. This is what I have done In my views.py: class viewbloglistview(LoginRequiredMixin,ListView): model = Blog paginate_by = 6 And in my template: {% if is_paginated %} <ul class="pagination"> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">Previous</a></li> {% else %} <li class="disabled"><span>Previous</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">Next</a></li> {% else %} <li class="disabled"><span>Next</span></li> {% endif %} </ul> {% endif %} Any ideas anyone how this can be accomplished in django? Thank you -
How to solve this error `ValueError: Value must be a list` in Django
Product.objects.filter(id=4).update(feature={'top_selling':False}) when i try this code am getting error like ValueError: Value must be a list -
How to share database across 2 django projects
I have a school management application written in django and has a postgres database, I want to create another application that supports the school app. This new django project will have to do support operations like deleting marks, reversing transactions etc. this new app is for internal purpose, But it will need to be able to access all the data that school app produces and also have its own database to record what employees interally do. What is the best way to do this? -
How do i get the post_detail page to work? Any help is greatly appreciated
Following is my urls.py file: from django.urls import path, re_path, include from . import views app_name = 'blog' urlpatterns = [ path('', views.post_list, name='list'), path('<slug>/', views.post_detail, name='detail'), ] My views.py file: from django.shortcuts import render from .models import Post # Create your views here. def post_list(request): posts = Post.objects.all().order_by('date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, slug): post_det = Post.objects.get(slug=slug) return render(request, 'blog/post_detail.html', {'singlepost': post_det}) And my post_detail.html page: {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="row"> {% for post in posts %} <div class="post col-md-10 shadow mx-auto"> <!-- post-thumbnail --> <div class="post-thumbnail"> <img src="{{singlepost.thumb.url}}"> </div> <!-- /post-thumbnail --> <h2 class="post-title bg-dark text-light pad1 text-center">{{ singlepost.title }}</h2> <p class="post-content">{{ singlepost.body }}</p> <p class="post-info grey border pad1">{{ singlepost.date }}</p> </div> {% endfor %} </div> </div> {% endblock content %} Screenshot from the error page: Django - Page Not Found Error What appears to be the problem here? Keep in mind that i'm new to django, however, this is the first time i come across an url such as the one noted in the error report. -
Imgkit running with headless server
I am trying to generate image from HTML with imgkit. Everything is working fine on my local machine but its giving some error on server. Below are the error from the server: Error - wkhtmltoimage exited with non-zero code -6. error: QXcbConnection: Could not connect to display This is my code: def img_work(request): #some work......... mail_Buyer_image = render_to_string('mailer/event_buyer_image.html',{'specificType': specificType, 'transaction': checkLink,'venue': event.venue, }) img_name = str('img.jpg') img_path = os.path.join(os.path.abspath(os.path.dirname("__file__")), "temp/" + img_name) imgkit.from_string(mail_Buyer_image, img_path) img = Image.open(img_path) img_temp = img.crop((330, 20, 690, 645)) img_temp.save(img_path) I have searched for the error and somewhere I found to use xvfb to solve the issue. But i failed to resolve it. The official site of imgkit is here Imgkit site -
Combining contains and in for django queryset.
I have the following code products = ["alpha.0.1.1", "alpha.1.1.7", "beta.0.0.1", "delta.2.4.1"] for j in products: queryset = Items.objects.filter(product_name__contains=i) Can I combine __contains and __in for django queryset ? -
How to get data connected by ForeignKey?
I'm new in Django. I'm trying to retrieve all the Tags associated with a Question. I have two classes on models.py. class Questions(models.Model): title = models.CharField(max_length=500) description = models.TextField(blank=True) class Tag(models.Model): name = models.CharField(max_length=50) tag_on = models.ForeignKey(Questions, on_delete=models.CASCADE) My views.py. class QuestionListView(ListView): model = Questions #assign model to display template_name = 'index.html' class TagListView(ListView): model = Tag template_name = 'index.html' context_object_name = 'tag_list' queryset = ? I have added this to my index.html. {% for val in object_list %} {{ val.id }} <br> {{ val.title }} <br> {% endfor %} {% for tag in tag_list %} {{ tag }} {% endfor %} I have tried few queryset like this but none of them worked. queryset = Tag.objects.all().get(Tag.id=Questions.id) queryset = Tag.objects.select_related('tag_on__id').get() How do I define queryset properly to address this problem? -
ImportError: cannot import name 'Page'
I have written a game in an Otree Project, but every time i want to clean my database or start the server, this message appears. It only happens with my game, but not when an example game is using that command. -
Rabbitmq does not recognize celery queue, exchange
I have an Django application using Rabbitmq as message broker. I defined some queues and exchanges and they worked well locally but not in stagging. Rabbitmq does not change/create new queue/changes as I should. What's problem with my rabbimq. Big thanks for any helps -
AJAX request from Django Admin templates with JSON response that's populated in change_form's fieldset
I have two models that are giving me issues: Cart and Entry. This is a foreign key relationship naturally and I have it set up in my models.py accordingly. Currently, I'm overriding my Django Admin so when I click on the save and continue button inside the change_form.html (this is inside submit_line.html) the total price--which is part of my cart, and is a helper method to my Cart ModelAdmin class, not an actual field--it will update asynchronously. The problem is, is after I edit a quantity to factor a subtotal for an Entry---ultimately totaling every entry's subtotal up to give me the total price of those---the total price doesn't reflect on the browser right away, and likewise, isn't reflected as saving to my database UNTIL I refresh. Not sure why I'm getting this inconsistent behavior (check out part1 of my thread here for more context please: Totaling inside a cart model the subtotal of each TabularInline entry in Django Admin So I've searched all day to use JS to refresh the browser using the Media class in my CartAdmin to call as JS file. Everything I tried either didn't work, or was a dirty solution. For example, when I reload … -
How to draw a table in Reportlab using pdfgen with canvas
My table is printing from bottom to top and as the number of items is greater, the rows grow up, I understand that the canvas draws in an absolute position but in this case I can not understand why it is printing in that way, not I know it's wrong in im code. def nota_pedido_report(request,id): master = NotaPedido.objects.get(id=id) detail = master.notapedidodetalle_set.all() cant_elementos = len(detail) response = HttpResponse(content_type = 'application/pdf') #pdf_name = "nota_pedido.pdf" #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name elements = [] buffer = BytesIO() #doc = getDoc(buff,'nota de pedido') c = canvas.Canvas(buffer, pagesize=A4) y = 600 #Header c.setTitle("Nota Pedido") c.setLineWidth(.3) c.setFont("Times-Bold", 12) titulo1 = c.drawString(220,790,'NOTA DE PEDIDO') c.drawString(250, 770,'Nº') nro = c.drawString(270, 770, str(master.nroPedido)) print(settings.STATIC_ROOT) archivo_imagen = settings.STATIC_ROOT+'/app/images/logo.png' #imagen = Image(archivo_imagen, width=50, height=50,hAlign='LEFT') c.drawString(400, 780, master.fecha.strftime('%d-%m-%Y')) c.drawImage(archivo_imagen, 80, 770, width=70, height=45) #Table Header styles = getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 12 parrafoStyle = ParagraphStyle('parrafos',alignment = TA_JUSTIFY,fontSize = 8,fontName="Times-Roman") headings = ('Cantidad', 'Unidad de Medida', 'Descripción') results = [(d.cantidad, d.unidadMedida, d.articulo.descripcion) for d in detail] c.setFont("Times-Bold", 12) c.drawString(80, 740, "Para: ") c.drawString(270, 740, "De: ") c.setFont("Times-Roman", 12) c.drawString(110, 740, str(master.departamentoDestino)) c.drawString(295, 740, str(master.departamentoOrigen)) c.drawString(80, 720, "Solicitamos nos provean de los siguientes: ") elements.append(headings) elements.append(results) c.setFont("Times-Roman", 6) #Detalle … -
How to retrieve id's and names of all fields of a particular type from html to Django views
I have a html form with a list of input fields with id's, names and values. Is there a way I can get these values in Django views by only mentioning the input type. For example : get the id's and values of all input elements with type text. -
How to disallow change of a Django field after creation?
I have a model like this: THRESHOLD_CLASSES = { MinimumThreshold.name: MinimumThreshold, MaximumThreshold.name: MaximumThreshold } class Threshold(models.Model): thingie = models.ForeignKey(Thingie, models.CASCADE) threshold_types = THRESHOLD_CLASSES.keys() type = models.TextField(choices=zip(threshold_types, threshold_types)) threshold = models.DecimalField() With these related classes: import abc import operator class Threshold(abc.ABC): @abc.abstractmethod def __init__(self): pass class MinimumThreshold(Threshold): name = 'minimum' operator = operator.lt operator_name = 'lower than' def __init__(self): self.other_class = MaximumThreshold class MaximumThreshold(Threshold): name = 'maximum' operator = operator.gt operator_name = 'greater than' def __init__(self): self.other_class = MinimumThreshold In my serializer I have to verify that the minimum threshold for a thingie is less than its maximum: def validate(self, instance): instance_type = instance['type'] instance_threshold_class = models.THRESHOLD_CLASSES[instance_type] other_threshold_class = instance_threshold_class().other_class other = models \ .AlarmParameterThreshold \ .objects \ .filter(thingie=instance['thingie'], type=other_threshold_class.name) \ .first() if other: if other_threshold_class.operator(instance['threshold'], other.threshold): message = "The {} threshold cannot be {} the {} threshold of {}".format( instance_type, other_threshold_class.operator_name, other_threshold_class.name, other.threshold ) raise serializers.ValidationError({'threshold': message}) This is already complicated, and I want to ensure that the complexity doesn't explode. One currently unhandled case if when the user changes the type of an existing Threshold - I would end up comparing it against an instance which is about to be replaced, and so I would have to make sure … -
Save a list of images using Django Admin
I'm working with a legacy database and the Django Admin. The legacy database stores image filenames in a database field in a list format like this ['image_one', 'image_two']. The images are stored in S3. I want to use the Django Admin to manage the images. My plan was to have a Django ImageField upload the image to S3 and then I'd use the filename of the image to append to something like a CharField that would be mapped to the image list. I can't use the ImageField for this because it has to be a string. I can accomplish the above however Django Admin wants me to have the ImageField mapped to a db field which forces me to create an extra db field which is an undesirable solution. I haven't found a way to avoid this at present. I've tried doing all of the above with the ImageField by changing the filename to a string with a list self.image_field.name = "[{0}]".format(self.image_field.name) however this throws a 'str' object has no attribute 'seek' error. Any ideas? -
How can I pass the user object from a template to a model method?
This is all theoretical (not tested) at this point, but I have a model that looks like this: class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) response_format = models.IntegerField(choices=choices.RESPONSE_FORMATS) text = models.TextField() options = ArrayField(models.CharField(max_length=48), blank=True) @property def get_answer_model_class(self): ct = ContentType.objects.get(app_label="Survey", model=choices.MODEL_STRINGS[self.response_format]) return ct.model_class() def get_user_response(self, user): respondent = Respondent.objects.get(user=user) return self.get_answer_model_class().objects.filter(question=self.id, respondent=respondent).first().response I want to use the get_user_response method in the template, but I need to somehow pass the user object to it. Is there a way to do just this from the template or do I need to unpack all of the Question objects in the view? Here's a bit of my template to illustrate where I am trying to go with this: {% for question in view.questions %} {% if question.response_format == 1 %} <div class="form-group"> <textarea class="form-control" id="{{ question.id }}" rows="5">{% {{ question.get_user_response }} user %}</textarea> </div> {% elif question.response_format == 2 %} <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" {% if question.get_user_response is True %}checked="checked"{% endif %} value="true"> <label class="form-check-label" for="inlineRadio1">Yes</label> </div> <div class="form-check form-check-inline"> <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="false" {% if question.get_user_response is False %}checked="checked"{% endif %}> <label class="form-check-label" for="inlineRadio2">No</label> </div> {% endif %} -
Is it required to attach request.application in django-oauth-toolkit?
I have a separate resource and auth service and am trying to override the OAuth2Validator in django-oauth-toolkit to work with this setup. In the original impl, OAuth2Validator.validate_bearer_token sets the request.client to the OAuth2 application - is this something internally required for the rest of the oauth-toolkit to function, or am I safe to not implement this if my service won't use Application? In my case I'm just validating the scopes/expiry/user of the token, and since Application is not stored on my resource, it is an extra request to retrieve it.