Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object of objects JSON response from Django backend to React-Redux frontend
This is the response from Django when making axios api call in the frontend (array of objects). [ { "id": 1, "title": "How to create a django-react app", "body": "You should first do this stuff and that" }, { "id": 2, "title": "How to connect django with react", "body": "Get this and that stuff" } ] But this is the response that I want (object of objects). { 1: { "id": 1, "title": "How to create a django-react app", "body": "You should first do this stuff and that" }, 5: { "id": 5, "title": "How to connect django with react", "body": "Get this and that stuff" } } serializers.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' views.py class ArticleViewSet(ViewSet): queryset = Article.objects.all() def list(self, request): serializer = ArticleSerializer(ArticleViewSet.queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): article = get_object_or_404(ArticleViewSet.queryset, pk=pk) serializer = ArticleSerializer(article, many=False) return Response(serializer.data) -
Using same models for different webpages
So I have a Topic. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) owner = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete = models.CASCADE) text = models.TextField(blank = True, null = True) date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = 'entries' def __str__(self): The topic is retrieved and displayed based on the date it was created. def topics(request): """Show all topics """ topics = Topic.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html', context) What I would like to do is to have the Topic somehow distinguished based on which web page it was created from. And then I want the same topic to be displayed on the same webpage. As you can see here, below. The same topic is displayed on topic.html and f_topic.html because the same topic_id is used. I want to have it so that if the topic was created on topic.html then it is displayed on topic.html. If it is created on f_topic.html then it is displayed on f_topic.html. def topic(request, topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set.order_by('-date_added') images = Image.objects.filter(imgtopic__in = entries) context = {'topic': topic, 'entries': entries, 'images': images} return … -
How to connect to user specified Postgres database on Django and Heroku?
I have a web app in Django that uses a Postgres database for everything in the app. Everything is working great with this connection as expected and the app is working totally fine. A feature of the app is to allow users to connect to and query data from their own Postgres database. The requirement is for the user to provide their credentials and for the app to connect and query certain data. This feature is working as expected locally using psycopg2 as the Postgres driver and has been tested with multiple external Postgres databases (i.e. databases other than the one the app is using). The resulting query is returned within 1-5 seconds. However, when deployed on Heroku and tested with the same databases, the connection never gets established and the request times out. I tried using Celery and background processes but the connection still never gets established. What is needed to create this connection and query databases? Are there any other libraries that I need to install on Heroku other than psycopg2. The code that creates the connection is as follows, and again works totally fine locally: cnx = psycopg2.connect(host=request_body['hostname'], database=request_body['dbname'], user=request_body['username'], password=request_body['password'], port=request_body['port']) Please advise. Thanks! -
Graphene and Django about relationships
I'm very new to Graphene and testing it to see if i could use it for a Django project with complex queries. To test it, i'm trying to create an Ecommerce with the following models class Sku(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductSku(models.Model): sku = models.ForeignKey(Sku, related_name='product_sku', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='product_sku', on_delete=models.CASCADE) price = models.IntegerField() As you can see here Product and Sku have a many to many relationship using the model ProductSku Using the documentation from Graphene i created the following Schema class SkuNode(DjangoObjectType): class Meta: model = Sku class ProductNode(DjangoObjectType): class Meta: model = Product class ProductSkuNode(DjangoObjectType): class Meta: model = ProductSku class Query(graphene.ObjectType): all_products = graphene.List(ProductNode, name=graphene.String()) product = graphene.Field(ProductNode, id=graphene.Int()) def resolve_all_products(self, info, **args): name = args.get('name') if name is not None: return Product.objects.filter(name__icontains=name) return Product.objects.all() def resolve_product(self, info, **args): id = args.get('id') if id is not None: return Product.objects.filter(pk=id).first() Right now my frontend app could get the price of a given product for a given sku by doing a query that asks for query{ allProducts{ id, name, productSku{ price, sku{ id, name } } } } But what i want to do is a query that asks for the price … -
SQL query generated by django F expression
Does anyone know the actual query generated by django when you use F expression? What will the generated query be for the example mentioned in the doc: https://docs.djangoproject.com/en/2.1/ref/models/expressions/#f-expressions from django.db.models import F reporter = Reporters.objects.get(name='Tintin') reporter.stories_filed = F('stories_filed') + 1 reporter.save() I tried viewing the query generated using: from django.db import connection logging.info('[----- DEBUG -----] Query -1: %s', connection.queries[-1]) logging.info('[----- DEBUG -----] Query -2: %s', connection.queries[-2]) logging.info('[----- DEBUG -----] Query -3: %s', connection.queries[-3]) but I don't see any query on the my model/table. Anyone know how to figure this out? -
How do i setup elasticcache redis for channel layer in django?
currently i have 2 servers both of them have redis address in common and the code i have is as below.and i am using AWS ElasticCache service CHANNEL_LAYERS = { 'default': { 'BACKEND': 'asgi_redis.RedisChannelLayer', 'CONFIG': { 'hosts': ['redis://location:6379'], }, 'ROUTING': 'app.routing.channel_routing', } } issue is one connects and another server throws 502 error -
How to make a table in report lab pdf to print on the next page when it reaches the end of page size
I have a table in report lab in django that i want it to continue printing its values on the next page when it reaches the end of A4 page. Is their any way to keep track on the current position when printing? And what does t.wrapOn and t.drawOn mean? My Django code: buffer = io.BytesIO() p = canvas.Canvas(buffer) width, height = A4 data = [ ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ['20', '21', '22', '23', '24'], ['30', '31', '32', '33', '34'], ['00', '01', '02', '03', '04'], ['10', '11', '12', '13', '14'], ] t = Table(data, style=[ # ('GRID', (0, 0), (-1, -1), 0.5, colors.black), ('LINEABOVE', (0, 1), (-1, 1), 1, colors.blue), # ('VALIGN', (3, 0), (3, 0), 'BOTTOM'), # ('ALIGN', (3, 1), (3, 1), 'CENTER'), # ('ALIGN', (3, 2), (3, … -
A bug while inserting a serializer in the raw data section, Django REST Framework
Showing below is a product (with id 65) containing two categories (with id 1 and id 66), the bug is that I didn't add the category of id 1 when creating the product I only added the category of id 66 ( in the 'Raw Data' section) , so each time I add a new product with a category inside , the category of id 1 gets added automatically to the list of categories. That's the bug ! { "id": 65, "product_code": "kdhjkfh", "name": "klfjkj", "quantity": 12, "price": 12, "categories": [ { "id": 1, "name": "ksjdf", "products": [ 65 ], "categories": [ 4 ] }, { "id": 66, "name": "dkllj", "products": [ 65 ], "categories": [] } ] } the serializers.py part of the product class ProductSerializer(serializers.ModelSerializer): categories = CategorySerializer(many=True, required=False) class Meta: model = Product fields = ('id', "product_code", "name", "quantity", "price", 'categories') def create(self, validated_data): category_data = validated_data.pop('categories') product = Product.objects.create(**validated_data) dicti={} for items in category_data: for key, value in items.items() : dicti[key] = value if 'id' in dicti: x= product.categories.get_or_create(id = dicti['id']) product.categories.set(x) return product Does anybody has any idea why the category of id 1 gets added automatically ? -
how to solve sidebar is messed up in mobile view django app
I have a website, which contains navigation bar and side bar. Navigation bar is automatically translate into mobile view , but sidebar is messed up. what can i do with this? what solutions do I have? looks like this PC view sidebar went to the background here in mobile view -
General Django Rest Question on Serializers
Quick concept question for you. I am working through a Django tutorial that involves building an api backend via django(using v 2.1). I have the following serializer for handling Comment objects from my Comment model in my articles app. class CommentSerializer(serializers.ModelSerializer): author = ProfileSerializer(required=False) createdAt = serializers.SerializerMethodField(method_name='get_created_at') updatedAt = serializers.SerializerMethodField(method_name='get_updated_at') class Meta: model = Comment fields = ( 'id', 'author', 'body', 'createdAt', 'updatedAt', ) def create(self, validated_data): article = self.context['article'] author = self.context['author'] return Comment.objects.create( author=author, article=article, **validated_data ) I want better understand this section of code: def create(self, validated_data): article = self.context['article'] author = self.context['author'] Specifically where is 'context' coming from? I have enough of an understanding of what exactly is going on here, I am more or less just curious of the mechanics behind what's going on here. For instance we didn't state context as an argument variable in the create function. Is context coming from my model? Is there some django magic taking place in the rest_framework that is assigning (maybe the entire instance) the context variable? Thanks everyone! -
How to link two objects saved in different places in Django
I am trying to achieve something similar to what Facebook is doing: in a blog post, when we you post a link to an article, it automatically fetches the tag to get the image, title and description, and render it on the page. When drafting the post, I use a websocket thanks to Django Channels to send the link from the front to the backend to retrieve the different elements via Beautiful Soup. And then I send them back to the front to display them. The issue arises when I want to save the post along with the shared url elements. To manage the post creation, I use a CBV PostCreate. I can save the shared url elements in the consumer. But the two objects are not linked and I don't know how to get the SharedArticle object id and save it with the post. I have two models: Post and SharedArticle. Here is my consumer.py class UrlConsumer(AsyncConsumer): async def websocket_connect(self, event): chat_room = "shared_url" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("receive", event) page = urlopen(event['text']) soup = BeautifulSoup(page, "html.parser") title = soup.find('meta', property='og:title') img = soup.find('meta', property='og:image') description … -
Redirect to post details from new_post doesn't work
I have a section named forum in my project where users can post and discuss. During creating a new post, when I try to save my new post as a user (pic)this error occurs. Also, I am trying to save the username as well to show further which user creates the post. Actually problem shows when I try to save this file I tried in following way: models.py: class Post(models.Model): user_id = models.ForeignKey(User, on_delete =models.CASCADE) title = models.CharField(max_length = 500, blank = False) description = models.TextField() def __str__(self): return self.title views.py: class PostCreate(CreateView): model = Post fields=['title','description'] template_name = 'post_form.html' def self(self, request): mdoel.user_id = request.user.id return redirect('website:details',{'post': model}) urls.py from django.conf.urls import url from .views import UserFormView , index , user_login,Forum,Details,PostCreate app_name = 'website' urlpatterns = [ url(r'^$',index,name = 'index'), url(r'^register/$',UserFormView.as_view(),name = 'register'), url(r'^login/$', user_login, name= 'login'), url(r'^forum/$',Forum, name = 'Forum'), url(r'details/(?P<post_id>[0-9]+)/$',Details,name= 'details'), url(r'add/$',PostCreate.as_view(),name = 'newPost') ] -
Is models in my django applications correctly defined?
I'm learning Django and created a University application in django project. Now I want to know whether the relationships defined in my models.py is correct or not? from django.db import models class University(models.Model): name = models.CharField(max_length=100) courses = models.CharField(max_length=500) def __str__(self): return self.name class Student(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) name = models.CharField(max_length=200) roll_number = models.IntegerField(max_length=10) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) university = models.ForeignKey(University, primary_key=True) classes = models.ManyToManyField(Classes, blank=True, related_name="classes") def __str__(self): return self.name class Classes(models.Model): name = models.CharField(max_length=100) attendee = models.CharField(max_length=100) student = models.ManyToManyField(Student, blank=True, related_name="students") def __str__(self): return self.name -
How to only render bundles that exist in django webpack
I am using django webpack loader to enable angular webpage hosting. The issue I am running into is including the render bundles {% load render_bundle from webpack_loader %} {% load static %} <!doctype html> <html lang="en"> <head> <base href="/"> <title>Angular/TypeScript Hello World Project</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Angular Hello World Starter"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <link rel="stylesheet" type="text/css" href="{% static 'angular/assets/styles/styles.css' %}"> </head> <body> <main class="container"> <app-root> Loading... </app-root> <br /><br /> </main> {% render_bundle 'runtime' %} {% render_bundle 'polyfills' %} {% render_bundle 'styles' %} {% render_bundle 'vendor' %} {% render_bundle 'main' %} </html> When I run the above code it works, however when I run angular build in prod. I get the error Cannot resolve bundle vendor. So I need to only render the bundles if they exist. How do I do this? Also, it would be nice if I had a loop through all bundles to include them how do I do this? -
Pass Django SECRET_KEY in Environment Variable to Dockerized gunicorn
Some Background Recently I had a problem where my Django Application was using the base settings file despite DJANGO_SETTINGS_MODULE being set to a different one. It turned out the problem was that gunicorn wasn't inheriting the environment variable and the solution was to add -e DJANGO_SETTINGS_MODULE=sasite.settings.production to my Dockerfile CMD entry where I call gunicorn. The Problem I'm having trouble with how I should handle the SECRET_KEY in my application. I am setting it in an environment variable though I previously had it stored in a JSON file but this seemed less secure (correct me if I'm wrong please). The other part of the problem is that when using gunicorn it doesn't inherit the environment variables that are set on the container normally. As I stated above I ran into this problem with DJANGO_SETTINGS_MODULE. I imagine that gunicorn would have an issue with SECRET_KEY as well. What would be the way around this? My Current Approach I set the SECRET_KEY in an environment variable and load it in the django settings file. I set the value in a file "app-env" which contains export SECRET_KEY=<secretkey>, the Dockerfile contains RUN source app-env in order to set the environment variable in the container. … -
Django form not submitting upon click
I don't know why my code is not submitting, i search on the internet and cannot find any solution, please someone should help me go through this code {% extends 'root/base.html' %} {% block title %}{{title}}{% endblock %} {% block body %} <div class="container"> <div class="row"> <div class="col-md-6"> <form method="post" action="{% url 'shopapp:signup' %}"> {% csrf_token %} {% for field in form %} {{field.label}} <p>{{field}}</p> {% endfor %} <p><input type="submit" value="Signup" class="btn btn-danger"></p> </form> </div> </div> {% endblock %} -
Retrieve selected choices from Django form ChoiceField
I'm attempting to make a search functionality on my Django web app. The idea is that users will go to the front page and be able to select from a drop down list of properties (ie. the OS, compiler, etc) and then submit their search which should return a list of matching builds. I have the ChoiceField form set up and I know the code I need to run to get the proper build in my next view. What I don't know is how to pass the values the user selected when they hit submit to the next view so I can filter based on those choices. Any help? forms.py from .models import * class BuildForm(forms.Form): build_OPTIONS = Builds.objects.values().distinct() ... Build_type = forms.ChoiceField(widget=forms.Select(), choices=build_OPTIONS) views.py from .forms import BuildForm def index(request): builds = BuildForm() return render(request, 'ReportGenerator/index.html', {"builds":builds}) templates/App/index.html {% if builds %} <h2>Pick a Build</h2> <form method="POST" class="build-form">{% csrf_token %} {{ builds.as_p }} </form> {% else %} <p>No reports are available.</p> {% endif %} -
Django template language syntax
I'm learning django and i'm blocked on a template syntax error. I have this function in my views.py : def AccountUpdateView(request): template_name='portal/accountupdate.html' context = {"forms":UserForm} return render(request,template_name,context) There is my template : <form action="/account/update/" method="POST"> <ul> {% csrf_token %} {% for form in forms %} <li>{{form.label}} <input type="text" name="{{form.name}}" maxlength="32" required="" id="id_{{form.name}}" value="{{PLEASE HELP ME !!!}}"> </li> {%endfor%} </ul> <input type="submit" value="Metre a jour" /> </form> Well, i'm trying to get in the "value" of each form on my template by the current registered user known in django by the call {{user}} And i would to auto place the values of each forms. I think a solution is to use the form.name (for the example of the case 'username') and in the value call a thing like this : user.form.username It doesn't work and i know that i was dream to hope this exotic call don't work... If any have a solution :) Thank's you ! -
can't pre-populate a django database
so I've been following this guide from Django 1.1 but I'm actually using Django 2 for how to pre-populate Django database I'm using SQLite database and this is my code with Faker library but it just won't run when I want to run it in the CMD. Please help me if you can: This is my first file which is the script for populating the database: (populate_first_app.py) import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POPULATION SCRIPT: import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker # Creating a fake generator: fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # GET THE TOPIC FOR THE ENTRY: top = add_topic() # Create the fake data for that entry: fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry: webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.get_or_create(name = webpg, date = fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(20) print("Populating Complete!") And finally, this is my models.py file of the only app … -
social-auth-app-django 'social' is not a registered namespace
Python(3.6.7) and Django(2.1), trying to integrate social-auth-app-django. Unlike this post, I've declared SOCIAL_AUTH_URL_NAMESPACE but it doesn't work. Configuration : settings.py : 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__))) # Application definition INSTALLED_APPS = [ "Microlly", "social_django", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.github.GithubOAuth2', 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] 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", "social_django.middleware.SocialAuthExceptionMiddleware" ] ROOT_URLCONF = "microblogging.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", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "social_django.context_processors.backends", "social_django.context_processors.login_redirect", ] }, } ] WSGI_APPLICATION = "microblogging.wsgi.application" SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY="SECRET" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET="SECRET" SOCIAL_AUTH__KEY="ID" SOCIAL_AUTH__SECRET="SECRET" # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] STATIC_ROOT = os.path.join(BASE_DIR, "static") LOGIN_REDIRECT_URL = "/accounts/" EMAIL_BACKEND = ( "django.core.mail.backends.console.EmailBackend" ) # During development only urls.py : from django.conf.urls import url from django.contrib.auth import views as auth_views from django.urls import include, path, reverse_lazy from Microlly import views app_name = "Microlly" urlpatterns = [ path("", views.index, name="index"), path("accounts/", include("django.contrib.auth.urls")), url('^api/v1/', include("social_django.urls", namespace='social')) ] login.html <a href="{% url "social:begin" "google-oauth2" %}">Google+</a> And the returned error is : NoReverseMatch at /accounts/login/ 'social' is not a registered … -
How to get data from relationship many-many in django?
How to get all product in every oders in templates django Table sql Model.py templates My browser -
Django, python 2.7 : insert multiple records into two related tables
New to Django orm and i need guidance: i want to insert 5 records in a table say 'Table1' with PK 'table1Primary' then insert same number of records into another table 'Table2' with table 1 PK 'table1Primary' as foreign key example:Table1 primary key pk1 pk2 pk3 pk4 Table 2 foreign keys pk1 pk2 pk3 pk4 [i would rather use for loop or any other optimized way rather than writing separate insert statements] code that doesn't work, i am assuming because of this line eft_fulfillment_uid=ef , i end up with 5*5 inserts in second for i in range(5): ef = Fulfillment.objects.create( fullfillment_uid=generateid(), ... ... ) ef.save() for i in range(5): por = OutReq.objects.create( out_req_uid=random.randint(500, 1000000000), eft_fulfillment_uid=ef, ... ... ) por.save() -
Persist PostgreSQL Data with Docker Named Volumes
I've been trying to set up my dockerized Django application so that the database persists. Currently, each time the site is deployed I have to recreate the database and enter all the data. What I would like to achieve is to have the database data persist so that I can deploy it with the default data already set up and entered. So the requirements are as follows: Persist the default database data that should be the starting data for every deployment of the site. A method to backup database data after users have interacted with the site so that it can be recovered in the event of an outage or loss. The updated database data is stored so that it can be recovered, but doesn't overwrite the initial default data that should be in the database each fresh deployment. I understand there are generally two methods for persisting database data. Mapping the volume to a host directory or using an external container. In my compose file I define the volume database_volume as a named volume, however I didn't set external: true. I'm confused as to where to go from here with this setup. How do I configure where exactly it … -
How to run Django project on apache?
I have a Django project and I will have to deploy it to apache server pretty soon but before that I want to test it on my local machine (Windows OS). And what I want to know is how to configure my Apache server on my local machine to make it work with Django projects. -
Template password_reset_form.html does not overwrite the django admin template
Template password_reset_form.html does not overwrite the django admin template my template is in: registration/password_reset_form.html