Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: __init__() got an unexpected keyword argument 'topic' POPULATING SCRIPT
So, I tried to populate my code my django website when i came across type error.i am really new to django webframe work and have no idea why i got this error. I followed a tutorial on udemy. ''' import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() import random from first_app.models import AccessRecord,Webpage,Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Game'] 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): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0] acc_rec =AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("Populating Script!") populate(5)`enter code here` print("populating Complete!") ''' -
How to use tuple in Django expression?
How can I use tuple in Django expressions? I want to be able to annotate QuerySet with some tuple, so that I can make ordering according to that annotation or filter things greater or smaller according to that annotation. I can order by multiple fields (without the need for annotation), but I can't easily filter something without implementing complex logic myself. It would be also nice if this could be used with existing code that uses "greater than" or "less than" filtering. (I could chain bunch of ORs handling things element by element, but I would be surprised if I'm the only one who needs something like this, I don't want to reinvent wheel.) I want standard SQL ordering, where left-most element has highest priority (for example SELECT (1,2) < (3,0) AS TEST returns TRUE). -
Browser blocks cross domain iframe cookies
I have a forum-like component which I use in an iframe on other websites. This component uses django-allauth for authentication with Facebook and Google. Everything worked fine but now the authentication stopped working some time ago. When I look at the cookies in my browser, the cookies from Facebook/Google which are set by the iframe, are not loaded. Although, the cookies from the component itself are set. The authentication still works when I load the iframe on a website which is on another subdomain of the component itself. Tool on another subdomain (working): https://shop-sandbox.adbuddy.be/discussie/ Tool on a totally different domain (not working): https://mama-calinka.webbuddy.be/discussie/ I guess this problem had something to do with CORS-headers but nothing I've tried helped. Can someone help me with this problem please? -
Paused on exception TypeError: document.getElementById(...) is null
Well Here I am creating commenting system. It works fine if there is at least one comment already but if there is no comment and try to create one than it shows me an error Paused on exception TypeError: document.getElementById(...) is null . I don't know how can i fix it. html <div id="post_id" post-id="{{post.pk}}" post-slug="{{post.slug}}"> {% if node.level < 3 %} <button class='btn btn-success' onclick="myFunction({{node.id}})">Reply</button> {% endif %} </div> jquery,ajax funtion $(document).on('click', '#newcomment, #newcommentinner', function (e) { e.preventDefault(); var button = $(this).attr("value"); var post_id = document.getElementById('post_id').getAttribute('post-id'); #Here is an error appearing. var post_slug = document.getElementById('post_id').getAttribute('post-slug'); console.log(post_id,'postid') var placement = "commentform" if (button == "newcommentform") { var placement = "newcommentform" } $.ajax({ type: 'POST', url: '{% url "posts:addcomment" %}', data: $("#" + button).serialize() + "&post_id="+post_id + "&post_slug="+post_slug, cache: false, error: console.log('post_id' + post_id), success: function (json) { console.log(json) $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result2'] + '</div> \ <hr> \ </div>').insertBefore('#' + placement); $('.commentform').trigger("reset"); formExit() }, error: function (xhr, errmsg, err) { } }); }) if more code is require than tell me in comment session. i will update my question with that information. -
Django + AWS s3 can upload files but not access them
Following this tutorial I set up our system to use Amazons S3 file storage using boto3 and Django-storages. I ran the collectstatic command and it worked just fine, the files show up in the AWS Management Console. But when running the server locally (runserver) all static files are missing. Looking at the console there are the error messages GET https://BUCKET.s3.eu-central-1.amazonaws.com/static/admin/css/nav_sidebar.css net::ERR_ABORTED 403 (Forbidden) for each of the files. The url looks right to me, the upload worked fine, but apparently the access doesn't work. Does this have something to do with my config in AWS? Or is this a django settings issue? -
Django - Certain Py Module doesn't work in IIS
This is my first time putting a question here. Some background, I started coding on Django this year and Python more than a year but less than 2 years so I don't much. This problem is a concern to my what I developing in at work. And my team working on it is novice or no experience on coding Python or Django or both. The Problem We have a web app based on Django 3.0.2 and use MSSQL for the db. Our company policy is to use Windows server and IIS as the prod and test server. We done a lot of work on it and all work well except for some python library and Django module that don't work, mainly Xlwings and Django-post-office. For XLwings, it doesn't run the code and Excel(we have valid license and latest Excel programme on the server). code below; filepath = BASE_DIR + '\\media\\Template.xlsm' temp_path = BASE_DIR + '\\media\\' + '{}.{}'.format(uuid4().hex, 'xlsm') shutil.copyfile(filepath, temp_path) pythoncom.CoInitialize() app1 = xw.App(visible=True) wt = xw.Book(temp_path) sht = wt.sheets['Cover'] sht.range('E5').value = request.POST.get('year') sht.range('E6').value = request.POST.get('company') sht.range('E7').value = companydata.employer_no sht.range('E8').value = email wt.save(temp_path) app1.quit() As for Django-post-office, we have module using it working but other modules using it doesn't work. … -
Django - What field or fields in model should I be indexing to speed up the following query?
What field or fields in model should I be indexing to speed up the following query? Query Subscriber.objects.filter(audience=audiencepk).order_by('-create_date') Models: class Subscriber(models.Model): first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=15, blank=True) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) class Audience(models.Model): audience_name = models.CharField(max_length=50) create_date = models.DateTimeField() store = models.ForeignKey(Place, on_delete=models.CASCADE) -
django template rendering fail?
Variables are not rendered correctly by django my views dynasty_li=['a','b','c','d'd] html {% for d in dynasty_li %} {% if d == dynasty %} <a href="{% url 'poet_list' '{{ d }}' %}" class="active">{{ d }}</a> {% else %} <a href="{% url 'poet_list' '{{ d }}' %}">{{ d }}</a> {% endif %} {% endfor %} actual <a href="category/{d}">a</a> <a href="category/{b}">b</a> <a href="category/{c}" class="active">c</a> <a href="category/{d}">d</a> -
Where are my environment variables in Elastic Beanstalk for AL2?
I'm using elastic beanstalk to deploy a Django app. I'd like to SSH on the EC2 instance to execute some shell commands but the environment variables don't seem to be there. I specified them via the AWS GUI (configuration -> environment properties) and they seem to work during the boot up of my app. I tried activating and deactivating the virtual env via: source /var/app/venv/*/bin/activate Is there some environment (or script I can run) to access an environment with all the properties set? Otherwise, I'm hardly able to run any command like python3 manage.py ... since there is no settings module configured (I know how to specify it manually but my app needs around 7 variables to work). -
Image is not showing in Django on Heroku server
The images I'm uploading in the model are showing in the localhost but not working on the Heroku server. I'm already using the white noise, and staticfiles(CSS, js, and images) which is stored in static folder are working fine in both places (locally and on the server) the only problem is happening with images I uploaded in the model. Heroku logs "GET /media/product_image/pixel4a_8dq6jPP.jpeg HTTP/1.1" 404 771 "https://mobile-care.herokuapp.com/explore/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" models.py image = models.FileField(upload_to='product_image', urls.py urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file {% for item in products %} <img src="{{item.image.url}}"> {% endfor %} I repeat I'm already using whitenoise and already initialized the MEDIA_ROOT and MEDIA_URL in settings.py. -
ModelNotFoundError in Django
For some reason, VS code doesn't recognize some standard external Django modules. I keep getting the ModelNotFoundError. When I try to run pip or pip3 install on for example django.contrib I'm getting the following error: ERROR: No matching distribution found for django.contrib I'm using VS Code on Windows 10. Would be awesome if someone could help me fix this problem. -
How to add a file upload progress bar with percentages in django and jquery
I want to create a file upload progress bar to my form, but am getting an error inside my console saying "jquery.min.js:4 POST http://localhost:8000/music/create/ 403 (Forbidden)" below is my code #Model class Song(models.Model): genre = models.ManyToManyField(Genre) #FORMS class SongCreateForm(forms.ModelForm): class Meta: model = Song fields = ['audio',] #VIEWS def songcreate(request): artist = Artist.objects.get(user=request.user) form = SongCreateForm() if request.method == "POST": form = SongCreateForm(request.POST or None, request.FILES) form.instance.artist = artist if form.is_valid(): form.save() return render(request, 'music/song_form.html', {'form':form}) #URLS path('music/create/', songcreate, name="song_create"), #TEMPLATE AND JQUERY <form action="/" method="post" enctype="multipart/form-data"> <legend><h3>Update</h3></legend> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn-block razo-btn" placeholder="upload"> </form> <script> $(document).on('submit', function(event){ event.preventDefault(); var formData = new FormData($('form')[0]); var csrf = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ xhr : function(){ var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e){ if (e.lengthComputable) { console.log('Bytes loaded: ' + e.loaded); console.log('Total ' + e.total); console.log('Percetage uploaded ' + (e.loaded / e.total)); } }); return xhr; }, type : 'POST', url: '', data : { formData, csrfmiddlewaretoken:csrf }, processData : false, contentType : false, success : function() { alert('File uploaded'); } }); }); </script> -
Form automatically downloading data from the user's profile
I would like to create a function that will automatically retrieve data from a user's profile by clicking the save button. I want to create a platform on which a user can sign up for a tournament and I would like to do this in the purest and most intuitive way -
What the proper way of uploading an image in Django
I have a REST endpoint for creating certain resource, but now I want to add the functionality of uploading an image when creating the resource. What's the proper way of doing such feature? Do you need to upload the file separately then do another POST request for creating the resource? -
Django: multiprocessing: multiprocessing in a module with windows?
I am using multiprocessing inside one of my views.py #current module is someapp.views #current file is someapp.views.py from someapp.models import ModelA. ModelB getScore(args): --get some data from ModelA and ModelB based on args --do some calculation with the args and models return a value def Getsomedata(request): arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) It keeps giving error Apps not loaded I tried def Getsomedata(request): if __name__ == "__main__": arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) the if statement does not quality because __name__ = someapp.views HOw to run the multiprocessing -
How to url encode in Django views
In Django, I want to do this <a href="{% url 'firstapp:create' %}?next={{ nextos|urlencode }}"> but in my views.py, when I render a page return render(request, 'create' + parameter next=nextos) Any ideas? -
How can I get the full URL from my request argument? [duplicate]
I have a method that resolves a get request that looks like this: import json import json_api_doc import requests from django.conf import settings from django.core.cache import cache from django.utils import timezone from rest_framework.response import Response from rest_framework.views import APIView class MyClassAPIView(APIView): def get(self, request): foo = request.query_params.get('foo', '') # url = request.url <-- this does not work, but is what I'm trying to accomplish ... return {...} As you can see, I am able to get the query_params, but I would also like to get the full URL that is coming in. For example, this is the URL I am trying to read: https://example.com?foo=bar I have tried print(dir(request)) to see what is available, but not seeing anything related to path or url. I am successfully getting the query_param -- how can I get the full URL? -
Can we make an android app using django and briefcae packaging?
Can we make an android app using django and briefcae packaging? I mean use django as its gui framework and make an android apk installer using briefcase. -
Django Models (dynamic?)
I am just starting Django Website; I have deciced to go with a model (with SQLite DB), which have the following properties: class Flow(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Owner", default="ADMIN") source = models.CharField(default='HTTP', choices=SOURCE_CHOICES, editable=True, max_length=12) name = models.CharField(max_length=50, default=" ") date = models.DateTimeField(verbose_name="Creation date") I want to add others fields to this model depending on the source field value. For example if the source field : 'File' is selected. I will create additionnal field (like file name, file directory ...) If 'Http' is selected, I will create a field URL. Thus depending on the source field, I will have differents field and type. I have read this kind of model is difficult to reprensent in Django; I am open minded to other kind of solution. My idea was to created as many model as the possible source value. -
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag?
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag? My homepage code {% extend "mainApp/wrapper.html" %} {% block content %} <p> Darbibas parbaude! </p> {% endblock %} My wrapper code <!<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <meta http-equiv = "X-UA-Compatible" content = "ie=edge"> <title></title> </head> <body> <body style media = "background:silver"> {% block content %} {% endblock %} </body> </html> -
Django i18n translation after changing default language
I have two languages on the website - en and ru. When the project started, the default language was en. So, in the template I type something like {% trans 'Hello' %} and make translations only for ru in the locale folder. But now I have changed the default language to ru. And now the website was in ru even if the language is en because I haven't translated anything for en (it's already in en however). How to fix it? how to make it so that in the absence of translation i18n doesn't translate anything and shows just the text as it is? Thanks. -
How to insert two user chat data into firebase database using Django?
i am new in Firebase. i want to implement chat module in firebase using django.i want insert users chat into firebase according to image structure, here is the image as mentioned in image , all the messages of user number 30 are under entry number "30" . how to insert data in above formet? -
Django 3: Passing slug in URLs to views?
I'm trying out Django for a webshop, I'm following the instructions of a book(Django 3 by example), but there seem to be something missing. I have tested if return to home in def product_list seen in views.py, so I believe the problem is in the "if category_slug:" condition or it is not receiving the slug. In main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] In app urls.py urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='products_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ] In views.py: def product_list(request, category_slug=False): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) -
Can't perform migration on django 3, python 3, sqlite3
I run manage.py migrate on my django blog project and get this: (joelgoldstick.com) jcg@jcg-hp:~/code/p3/joelgoldstick.com/blog$ python manage.py migrate . . . django.db.utils.OperationalError: table "django_content_type" already exists During handling of the above exception, another exception occurred: . . . raise IntegrityError( django.db.utils.IntegrityError: The row in table 'blog_app_entry_categories' with primary key '8' has an invalid foreign key: blog_app_entry_categories.category_id contains a value '3' that does not have a corresponding value in blog_category.id. but the table blog_category contains a row with id = 3 -
Django project not start
Why my django project not start? django version - 1, path - 2