Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why GIthub Folder Button broken?
I git pushed my projected to my Github page, but a few important folder didn't seem to work and can't see the content. And even when I download all folders in zip file, still nothings contained in it. I mean, the start folder should contain all of my files and activated. The original folder has full content, so I have no idea what to do. Noghing errors thrown while I push those to Github. -
elastic beanstalk not creating superuser, invalid syntax
I'm just trying to create a super user so that I can log into the admin section of my site. Everything else is working so far. Here is the relevant portion of my activity error log: [2019-12-22T05:02:06.721Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Test for Command 02_createsuperuser] : Starting activity... [2019-12-22T05:02:06.725Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Test for Command 02_createsuperuser] : Completed activity. Result: Completed successfully. [2019-12-22T05:02:06.726Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Command 02_createsuperuser] : Starting activity... [2019-12-22T05:02:07.074Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Command 02_createsuperuser] : Activity execution failed, because: Traceback (most recent call last): File "/opt/python/current/app/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 92, in handle exec(sys.stdin.read()) File "<string>", line 1 from users.models import UserProfile; UserProfile.objects.create_superuser(xxxxxxx@gmail.com', 'passxxxword') ^ SyntaxError: invalid syntax (ElasticBeanstalk::ExternalInvocationError)[2019-12-22T05:02:06.721Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Test for Command 02_createsuperuser] : Starting activity... [2019-12-22T05:02:06.725Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Test for Command 02_createsuperuser] : Completed activity. Result: Completed successfully. [2019-12-22T05:02:06.726Z] INFO [26175] - [Application update app-191222_070106@18/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_ss_app/Command 02_createsuperuser] : Starting activity... [2019-12-22T05:02:07.074Z] INFO [26175] - [Application update … -
Working with django and react application with webpack-dev-server (Hot-reloading). I am getting this error in console. But my page is loading fine
Failed to load resource: the server responded with a status of 404 (Not Found) main-8f0497ba1ebedd971dd2.js:6 [WDS] Disconnected! close @ main-8f0497ba1ebedd971dd2.js:6 (anonymous) @ main-8f0497ba1ebedd971dd2.js:1 r.dispatchEvent @ main-8f0497ba1ebedd971dd2.js:6 (anonymous) @ main-8f0497ba1ebedd971dd2.js:6 **webpack.config.js** var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: [ 'react-hot-loader/patch', 'webpack-dev-server/client?http://localhost:3000/', 'webpack/hot/only-dev-server', './react/index', ], output: { path: path.resolve('./project_fashion/static/bundle/'), filename: "[name]-[hash].js", publicPath: 'http://localhost:3000/static/bundle/', }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new BundleTracker({filename: './webpack-stats.json'}), ], module: { rules: [ { test: /\.js$/, use: 'babel-loader',exclude: /node_modules/, }, { test: /\.jsx$/, use: 'babel-loader',exclude: /node_modules/, }, { test: /\.css$/, use: ['style-loader', 'css-loader'],exclude: /node_modules/, }, { test: /\.(svg|png|jpg|jpeg|gif)$/, use: 'url-loader',exclude: /node_modules/, }, ] }, resolve: { extensions: ['*', '.js', '.jsx'] } }; **server.js** var webpack = require('webpack') var WebpackDevServer = require('webpack-dev-server') var config = require('./webpack.config') new WebpackDevServer(webpack(config), { publicPath: config.output.publicPath, hot: true, inline: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*', }, }).listen(3000, '0.0.0.0', function (err, result) { if (err) { console.log(err) } console.log('Listening at 0.0.0.0:3000') }) **Settings.py** """ Django settings for project_fashion project. Generated by 'django-admin startproject' using Django 3.0. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside … -
django-allauth accounts/signup gets [WinError 10061] No connection could be made because the target machine actively refused it
I know that there are a lot of answers to this issue say that I should probably try running my server on another port like so: python manage.py runserver 0.0.0.0:8080 I have tried that didn't fix it. I have turned off my windows Norton firewall: I have started PyCharm as administrator. The thing that make me think these solutions were not going to work for me was that other API endpoints work fine: http://localhost:8000/accounts/login/ works and http://localhost:8000/accounts/logout/ works too. But when I fill out the form and POST my data to http://localhost:8000/accounts/signup I get this error: OSError at /accounts/signup/ [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 2.2.7 Exception Type: OSError Exception Value: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions Can someone please tell me what I am missing here? -
Edit existing instance of a model
I have created a form to create an instance of my car dealer model. Now I want to be able to click on an edit icon and be taken to a page with a form that is prepopulated with the attributes of the model instance. I'm also wondering if I need to create a separate form, view and template for creating and editing or perhaps I can reuse them somehow? models.py class Dealer(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=50) website = models.CharField(max_length=100) address = models.CharField(max_length=100) featured_image = models.ImageField(upload_to="dealers/") def image_tag(self): return mark_safe('<img src="%s" style="height: 300px; width: auto;"/>' % (self.featured_image.url)) image_tag.short_description = 'Image' class Meta: verbose_name_plural = "Dealers" def __str__(self): return self.name views.py def create_dealer_view(request): if request.method == "POST": form = CreateDealerForm(request.POST, request.FILES) if form.is_valid(): dealer = form.save(commit=False) dealer.save() return redirect('main:homepage_view') else: form = CreateDealerForm context = { "title": "Create - Dealer", "form": form, } return render(request=request, template_name="main/create/create_dealer.html", context=context) forms.py class CreateDealerForm(forms.ModelForm): class Meta: model = Dealer fields = ('name', 'phone','website', 'address', 'featured_image',) widgets = { 'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}), 'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}), 'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}), 'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}), } -
Django include static CSS JS files - path included but not read
My project base directory is, then app and static dirs as below. I am trying to load CSS and JS. These does get rendered in the html but when I try to open the js css files directly in the browser for verification to see if the page is really addressed, it gives a page not found an error. What is missing here? How do I do this? /data/projectname/ /data/projectname/app/ /data/projectname/app/static/ /data/projectname/app/static/js/ Settings STATICFILES_DIRS = ( os.path.join(BASE_DIR, '/app/static/'), ) View <script type="text/javascript" src="/app/static/js/css-doodle.min.js"></script> {% load static %} <script type="text/javascript" href="{% static 'js/css-doodle.min.js' %}"></script> HTML rendered, tried both ways <script type="text/javascript" src="/app/static/js/css-doodle.min.js"></script> renders home page instead of showing the actual js <script type="text/javascript" href="/static/js/css-doodle.min.js"></script> 404 page not found, it should show raw js file if it is truly properly included/addressed -
List of DateTimeField in Django model
I have a Subject model, and every subject needs a schedule, so I want to have a list of datetimes in the model. I know that postgres has a ArrayField method but I'm using SQLite3. class Subject(models.Model): name = models.CharField() schedule = #Here I need the list of datetimes It's a short question but I didn't find anything like this -
django paginationated first page content different to root page content (with cache)
I am paginating content based on a random queryset and I seem to be getting inconsistent results between the paginated first page ?page=1 and the root page itself. So, I have my ListView like so: class Some1_ListView(ListView): model = Some_Model template_name = "test1.html" paginate_by = 12 context_object_name = "test1" queryset = Some_Model.objects.all().order_by('?')[:24] My urls is like so: urlpatterns = [ path('test1/', cache_page(500)(Some1_ListView.as_view()), name="test1" ), ] and the template is paginated according to the django docs, nothing special. Now, when I go to: localhost/test1 I get the first 12 objects. Now, When I move to the next page, onbiously, my url becomes: localhost/test1/?page=2 This renders fine aswell. Now, when I go back to localhost/test1/?page=1 I see that the results are not the same as localhost/test1/ So, localhost/test1/?page=1 != localhost/test1/ Since I was caching the URL, I was expecting these two to be the same. Can someone enlighten me as to why this is? and how do I get aorund it? Id like both these pages to show the same content (from cache). -
Recommendation on deploying a heavy Django + React.js web-application
I got to build a Django application recently that has a database and performs some floating-point operations( biopython, alpha-shapes and similar algorithms on crystallographic data from the database) upon request from the React.js frontend. I was wondering what would be the best way to deploy something like this long term and how the two codebases would communicate with each other ( runs well on localhost as of now ). I've come across a few suggestions like digital ocean for django and firebase for the frontend, and heroku of course. I have never, however, hosted a website that would go into production eventually, let alone two, and am a little at a loss as to how the two codebases would communicate with each other, how to preserve all the packages installed in django's virtual environment in deployment, how to transfer online the database to which the calls are made. I would appreciate any pointer to resources to read up on or an architecture suggestion very much. Thanks a ton! -
List of DateTimeField in Django model
I have a Subject model, and every subject has a schedule with many datetimes, but I can't figure how to do it. I found that Postgres has an ArrayField method, but I'm using SQLite. class Subject(models.Model): name = models.CharField() schedule = #Here I need a list of datetimes It's a short question but I didn't find anything searching. -
Django: set model choice field options to quesryset values and other value
In the below Django models class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) title = models.CharField(max_length=200,null=True) text = models.TextField() post_url = models.URLField(max_length = 200, blank = True) post_type = models.IntegerField() slug = models.SlugField(unique=True, blank=True) class Tiers(models.Model): user = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,) tier_name = models.CharField(max_length=128, blank = True) tier_value = models.IntegerField() slug = models.SlugField(unique=True, blank=True) I want to use post model for a form like below class PostForm(forms.ModelForm): class Meta: model = models.Post fields = ('title','text','post_url','post_type',) But for post_type field I want to display as dropdown with options from Tiers models tier_value. For example if user1 has 3 entries in Tiers model with tier_values as 10, 20 and 30. I want to display 4 options 0, 10, 20 , and 30. Can someone help me how to achieve this? -
Deploying Django to Heroku - The joined path is located outside of the base path component
I receive the following error when trying to deploy Django to Heroku: django.core.exceptions.SuspiciousFileOperation: The joined path (/tmp/build_a434e585a520d3dda8da83c71ac7b809/font-awesome/fonts/fontawesome-webfont.eot) is located outside of the base path component (/tmp/build_a434e585a520d3dda8da83c71ac7b809/static) My settings file is as follows: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] Any advice -
django serialize exclude primary key for some reason
My model is as following: class PolicyRule(models.Model): uid = models.IntegerField(default=0, primary_key=True, unique=True) maxAmount = models.FloatField() destinations = models.TextField() and for some reason, the following code rules_list = PolicyRule.objects.all() paginator = Paginator(rules_list, 5) rules = paginator.page(page) rules_json = serialize('json', list(rules)) produces this output "[{\"model\": \"webapp.policyrule\", \"pk\": 1576966788, \"fields\": {\"maxAmount\": 50.0, \"destinations\": \"ronen\"}}]" which is without the UID field! why is this happening? -
How to automatically translate models of a django webapp
I need to translate an ecommerce webapp built with Django-Oscar. I got the system language translated, so now I'm focusing only in translating the product names, product descriptions and the categories names. There are hundreds of products, and new ones will be added. So using the method where I have to manually insert translations in the .po files doesn't look like a good idea. I am considering to use the google translation API. I have watched a tutorial just with python. I would like to know if this is suitable for Django? Will this make the app slow? Are there better alternatives? Success Jaime -
Django: 404 URL not found when linking to a new url via the homepage
so I'm new to Django and have been having an issue adding a new page to my website. The home page and blog detail page are working fine. The issue arises when I try to link to an "About me" page. These are the relevant setting I have as of now: blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('about/', views.AuthorDetail.as_view(), name='about'), ] blog/views.py class PostList(generic.ListView): queryset = Post.objects.order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' class AuthorDetail(generic.DetailView): model = Post template_name = 'about.html' where 'about.html' is currently just a 'Hello World' html output. In the directory above I have, app/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] Lastly, in the html of the homepage I have the following link, <a class="nav-link text-white font-weight-bold" href="{% url 'about' %}" >About Author</a> As I said, the homepage (url: /) and post detail (url: slug) work fine. But when I try to go to the url localhost:8000/about/ I get an error saying Page not found (404) Request Method: GET Request URL: http://localhost:8000/about/ Raised by: blog.views.PostDetail Any help would be … -
Django IntegrityError with uuid as primaryKey
Okay so here is the behaviour explained. 1. I create a new Post object via admin panel. 2. Object is saved. 3. Create one more Post object after that. 4. Get error django.db.utils.IntegrityError: duplicate key value violates unique constraint "lp_post_pkey" DETAIL: Key (id)=(5de7b062-14b2-42ef-a9ee-95bbb17ccf3b) already exists. I have read duplicate key value violates unique constraint in django . The problem is probably the same that my primary key sequence in the table i'm working with has become out of sync. And the solution to that was to set the current Primary Key from maximum +1. But i'm using uuid's for my primary key, that probably isn't the solution for me. So, how can i sync my primary keys if the problem really is at that? Btw, when i reset the local server i can repeat the steps from 1-4. As well, i've noticed when i'm doing a manage.py makemigrations even when i have nothing to migrate, my uuid fields keep altering to new ones. Can the problem be somehow related? models.py class SubscriberModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4(), unique=True, editable=False) email = models.EmailField() subscribed = models.DateTimeField(default=timezone.now()) ip_addr = models.CharField(null=False, max_length=250, default="") objects = models.Manager() def __str__(self): return "{%s}/EMAIL\{%s}/\Subscribed On/\{%s}/\From this IP" % … -
Juggling customer data in Django
I want to build a web app with Django which should be multi-client capable. Now I'm facing the question of how to juggling with the customer data. Of course, I want to make sure information from one client does not leak to the other, but what is the best way to do it? Does Django provide any permissions or something else for this job or should I store the client in all db tables and work with queries instead? What is the state of the art approach for this use case? I'm new to web dev, so please be indulgent. :) -
Django: JSONField + Full Text Search + Indexing -> Seq Scan. How to configure indexing to work?
Im using Django 2.2 and PostgreSQL 12. Here is my model: from django.contrib.postgres.search import SearchVectorField, SearchVector from django.contrib.postgres.fields import JSONField class ProfileUser(models.Model): name = JSONField() search_vector = SearchVectorField(null=True) class Meta: indexes = [ GinIndex(fields=['search_vector'], name='user_full_name_gin_idx') ] def save(self, *args, **kwargs): super(ProfileUser, self).save(*args, **kwargs) ProfileUser.objects.update(search_vector=SearchVector('name')) Here Im creating a new user and trying to find it: from apps.profiles.models import ProfileUser from django.contrib.postgres.search import SearchVector ProfileUser.objects.create(name=[{'name': 'SomeUser', 'lang': 'en'}]) ProfileUser.objects.annotate(search=SearchVector('name')).filter(search__icontains='someuser').explain() Result: "Seq Scan on profiles_user (cost=0.00..81.75 rows=1 width=316)\n Filter: (upper((to_tsvector(COALESCE((name)::text, ''::text)))::text) ~~ '%someuser%'::text)" How to make indexing working? -
Connect to google cloud SQL with django from google VM
I'm trying to connect to my google SQL database from my VM instance with django and I get the following error: private key file "./Google Keys/client-key.pem" has group or world access; permis sions should be u=rw (0600) or less how can it be fixed? (Note: it is working from my local machine but not from VM instance :/) -
About module and package on python
enter image description hereenter image description here Recently I started learning Django however I have a problem . Package and modules aren't working. I took a photo on the top. Please help me. Issue: from . import views.The Error type is: from. import views ImportError: attempted relative import with no known parent package -
Sidebar disappears permanently upon resizing
I have a problem with the responsiveness of a website I am currently creating. The problem occurs upon resizing (in chrome and firefox): I have a sticky sidebar (sb1) that I want to show whenever screen width is > 1024 and another that I want to show when the screen width is < 1024 (sb2). I can get sb1 to hide and s2 to show when it is < 1024. However, once I resize the window again, so that it is > 1024, sb1 doesn't show. Curiously, the same thing doesn't happen to sb2 upon resizing. As sb2 works, I won't provide the code for that, but I am using the script below. I have tried to get this to work using media queries and javascript. Here is the HTML: <div id="sticky-sidebar-demo" class="toc-sidebar"> <div class="sidebar__inner"> <h4> table of contents </h4> <div class="js-toc"></div> </div> </div> CSS: #sticky-sidebar-demo { float: left; width: 200px; will-change: min-height; } #sticky-sidebar-demo .sidebar__inner{ position: relative; transform: translate(0, 0); transform: translate3d(0, 0, 0); will-change: position, transform; } .inner-wrapper-sticky { overflow: hidden; } I've tried @media only screen and (max-width: 1024px) { #sticky-sidebar-demo { display: none; }} hoping that that would hide the sidebar (sb1) when the screen was … -
Django groupby day fill missing data with 0
I want to make a request in django where i group by day but I want to fill day where there are no result with 0, is-it possible ? # I use the following query AccessLog.objects.filter(attempt_time__gte=last_30_days).annotate(day=TruncDay('attempt_time')).values('day', 'username').annotate(c = Count('username')).order_by('day') Thanks for your help Best regards -
Stripe API requests being split sent across two Stripe accounts
We have a Django project that needs to use two different Stripe accounts (for compliance reasons). One Stripe account ("SA1") is for SaaS billing and our second Stripe account ("SA2") processes specific one-time payments using Stripe Connect. After we set this up, I'm seeing unexpected behavior where requests are being split sent between both accounts, rather than going to the intended SA1 account. Some API requests get sent to SA1 (what we want), some API requests are sent to SA2 (what we do not want). I will explain further: we have a view admin_billing where new customers save their card to create and save a new Stripe Customer and their Card. def admin_billing(request): """ Query customer table and adds a new card. :param request: :return: Billing rendering with template """ form = StripeAddCardForm(request.POST or None) if form.is_valid(): customer = Customer.objects.get_or_create_for_user(request.user) token = form.cleaned_data['stripeToken'] card = Card(customer=customer, stripe_card_id=token) try: card.save() except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(request, err.get('message')) log.error("Stripe card error: %s" % (e)) except stripe.error.StripeError as e: messages.error(request, 'Please try again or report the problem') log.error("Stripe error: %s" % (e)) except Exception as e: messages.error(request, 'Please try again or report the problem') log.error("Error while handling … -
Django form doesnt rendering. <TestForm.forms.my_form object at 0x000002C7B3B37A20>
I'm trying to render form in my template. It is my model: from django.db import models from phonenumber_field.modelfields import PhoneNumberField class StudyRequest(models.Model): name = models.CharField(max_length=256, blank=True) phone = PhoneNumberField(unique=True, blank=False, null=False) My form: from .models import * from django import forms from phonenumber_field.formfields import PhoneNumberField class send_request_form(): phone = PhoneNumberField(required=True) name = forms.CharField(max_length=256, required=False) class Meta: model = StudyRequest fields = {'name', 'phone'} My view: from django.shortcuts import render, redirect from StudyRequest.forms import send_request_form from StudyRequest.models import StudyRequest def landing_page(request): if request.method == 'POST': form = send_request_form(request.POST) if form.is_valid(): name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] R = StudyRequest(name=name, phone=phone) R.save() else: form = send_request_form() return render(request, 'NetStudy/home.html', {'form': form}) It is result of render: enter image description here Html: <html> <head></head> <body> <form> {% csrf_token %} {{ form }} </form> </body> </html> I tried to use form.as_p, form.as_table, form.as_ul, nothing helps me. -
Помогите пожалуйста с Поисковым запросом в Django в чём моя ошибка?
Я новичок в Django , ошибки не какой-нет , но когда я ввожу в поисковую форму что-то,страница перезагружается и возвращается-все посты, не важно что я ввёл в поисковую форму, как будто фильтр не работает, я без понятия, где и что не так! Просьба по подробнее ответить))) enter image description here enter image description here enter image description here enter image description here