Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a django model with multiple images?
I've been betting for an hour, but apparently I don't understand something. There is a task to write a scraper with the django admin panel and everything is fine and works here. Now i need to save all the data to the database and here is the problem, only one photo appears in the django admin panel, but everything is downloaded in the media folder. # models.py from django.db import models class Apartment(models.Model): rooms = models.CharField('кол-во комнат', max_length=64) price = models.CharField('цена', max_length=10) address = models.CharField('Адрес', max_length=256) desc = models.TextField('описание') floor = models.CharField('этаж', max_length=5) def __str__(self): return self.address class Meta: verbose_name = 'квартира' verbose_name_plural = 'квартиры' class Image(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) img = models.ImageField(upload_to='media/') class Meta: verbose_name = 'фото' verbose_name_plural = 'фото' class Url(models.Model): created = models.DateTimeField(auto_now_add=True) url = models.URLField('ссылка') def __str__(self): return self.url class Meta: verbose_name = 'ссылка' verbose_name_plural = 'ссылки' ordering = ['-created'] #save function def save_data(apartments_list): for ap in apartments_list: im = Image() try: apartment = Apartment.objects.create( rooms=ap['rooms'], price=ap['price'], address=ap['address'], desc=ap['desc'], floor=ap['floor'], ) for image in ap['photos']: pic = urllib.request.urlretrieve(image, image.split('/')[-1])[0] im.img = im.img.save(pic, File(open(pic, 'rb'))) im.apartment = apartment except Exception as e: print(e) break -
how i store user input data in a file that give from front side of the browser?
Actually i want to store data in file that give from front side of the browser. well we can use form or ModelForm or maybe we give input in json and that json data store in a file..anyone have an idea or any hint? -
How to make a query from a selected choice from the user from a drop-down list in Django
I am new here. In an internship context, I have to developp a website in which the user will have the opportunity to select a program, a localisation or a thematic he wants to visualise in a heatmap. To do so, I decided to use Django. I am encoutering 2 issues : First one : I have a mysql database constituted with 1 table with the location names (detailed in many columns) and the coordinates, and one table by program of the raw datas. I need to find a way to join the two tables but one localisation name can have different coordinates depending on the program. So i need to concatenate 2 columns by table (2 columns from the raw datas that I join to two columns from the table with the coordinates) For now I have thought about using new_var = table.objects.annotate but i cannot join the two newly variables ... Do you have any ideas ? Secondly : The user is supposed to choose a localisation from a drop-down list, that i can use to filter my database and display the map as he wishes. For now I have that : (views.py) ''' def map(request): m = … -
Postgres createdb and create database is not working in Ubuntu 18.04
I have a Django project I am trying to set up on Ubuntu and am creating a new database in PostgreSQL 14. The default root user is Postgres as usual. Then I tried creating a new user with my Linux username "abc" with all the privileges: "SUPERUSER", "CREATEDB", etc. Everything worked fine and a new user was created. And it was suggested that I create a database with the same name "abc". So, I did CREATE DATABASE abc; in the psql shell, it gives no error and results in nothing. I tried createdb abc or creatdb in the bash terminal but this also does nothing either. The solution from this SO answer link does not work for me at all. I also tried this which did not do anything. I ultimately just want to be able to create the database for my Django project, which I am not able to do, and I have now no clue what I am doing wrong. Here's the command I am using to set up the Django project db: # create new user who will be the db owner # on Ubuntu, root user is postgres createuser -P <new_user_name> -U <root_user> # if you're … -
how to invite people from social to your django app [closed]
I am creating an app where I want some buttons just like you see on most of the apps where people can invite other people on app. like facebook, twitter or any other social link. if you click on it you can share the link on whatsapp or all of these sites and when the person who I sent click on that link he should redirect to my site -
How to add paginator and filter in your website?
I'm doing a project in which I need to display cars and the user is allowed to filter their queries based on price, make, model etc. Earlier today the filter was not working but the Paginator was, but now, the filter is working and the paginator is not. I've been stuck on this the whole day and I don't know what else to do. This is my code: views.py def posts(request): cars = Userpost.objects.all() myFilter = UserpostFilter(request.GET, queryset=cars) cars = myFilter.qs p = Paginator(Userpost.objects.all(), 2) page = request.GET.get('page') cars_list = p.get_page(page) nums = "a" * cars_list.paginator.num_pages context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums} return render(request, 'store/userposts.html', context) userposts.html {% extends 'store/main.html' %} {% load static %} {% block content %} <div class = 'row'> <div class = 'col'> <div class = 'card card-body'> <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type = "submit">Search</button> </form> </div> </div> </div> <div class="row"> {% for car in cars %} <div class="col-lg-4"> <img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}"> <div class="box-element product"> <h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6> <hr> <a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a> <h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> <nav aria-label="Page navigation"> <ul class="pagination"> {% if cars_list.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1" aria-label="Previous"> <span … -
postgres setup error: "movie_dev" dosen't exist in TDD with Django, DRF and Docker
I tried "re-build image, run container and then apply migration" approach in the course (Test-Driven Development with Django, Django REST Framework, and Docker), but not work -
Django call save method passing related instance
Following on from this question, which I was unable to resolve, I've decided to try implementing a save method on the Asset class. After the Asset is created, the Trade instance needs to save the Asset that has just been created, and update additional fields from variables. I think that post_save will be the best method to use. In addition to this a related model on the Trade instance also needs to be updated. The instances are created using a Celery Task. How can the Trade instance be passed to the post_save method of the Asset class? Or is there a better way to implement the updating of related models? -
Celery unable to use redis
Trying to start Celery first time but issues error as below, i have installed redis and its starting fine , but still somehow django seems to have issues with it , File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/atif/Documents/celery_test/celery-env/lib/python3.8/site-packages/kombu/transport/redis.py", line 263, in <module> class PrefixedStrictRedis(GlobalKeyPrefixMixin, redis.Redis): AttributeError: 'NoneType' object has no attribute 'Redis' Celery.py from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_test.settings') app = Celery('celery_test',) app.config_from_object('django.conf:settings') # Load task modules from all registered Django apps. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Settings #celery stuff --------------- BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' celery_module/tasks.py from celery import Celery app = Celery('tasks',) @app.task def add(x, y): return x + y -
Django - Set ManyToMany attribute with empty list and serialize
I have this code below that sets relations tagged_users and hash_tags in a Post. It takes in the Post body and parses it for hashtags (Any word starting with a #) or a tagged_user (Any word starting with an @). Sometimes the post will contain neither, which causes an error at this line request.data['tagged_users'] = tagged_users. How do I resolve this so that it can be okay that it gives an empty list? view.py def request_to_post_data(request): post_text = request.data['body'] hash_tags_list = extract_hashtags(post_text) hash_tags = [HashTag.objects.get_or_create( hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags tagged_users_list = extract_usernames(post_text) tagged_users = list() for username in tagged_users_list: try: tagged_users.append(User.objects.get(username=username).uuid) except User.DoesNotExist: pass request.data['tagged_users'] = tagged_users serializer = PostSerializer(data=request.data) if serializer.is_valid(raise_exception=True): post_obj = serializer.save() create_image_models_with_post(request=request, post_obj=post_obj) create_video_models_with_post(request=request, post_obj=post_obj) return serializer serializer.py class PostSerializer(serializers.ModelSerializer): hash_tags = HashTagSerializer(many=True, read_only=True) class Meta: model = Post fields = ('creator', 'body', 'uuid', 'created', 'type', 'updated_at', 'hash_tags', 'tagged_users') models.py class Post(models.Model): # ulid does ordered uuid creation uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN, validators=[MinLengthValidator(POST_MIN_LEN)]) hash_tags = models.ManyToManyField(HashTag) tagged_users = models.ManyToManyField(User) -
Setting up and calling a group of celery tasks with individual countdown
Using: Django==2.2.24, Python=3.6, celery==4.3.0 This is what I am currently doing: from celery import group the_group_of_tasks = group( some_task.s(an_object.the_data_dict) for an_object in AnObject.objects.all() ) the_group_of_tasks.delay() What I want to do: The group documentation: celery docs link I would like to spread the the_group_of_tasks individual some_task calls over some time range. Best if I can use the countdown feature, and spread the tasks over a variable number of seconds (like an hour, 3600 seconds). The distribution will be done to a random seconds integer between zero and 3600, imagine it can easily be calculated once I have the range. I think that I can add the countdown arg, with a random number generator within my range such that it will be "packaged" and ready to be executed in the group with the individual task preparation? some_task.s(an_object.the_data_dict, countdown=some_generator_call) Would that work? In case it helps, I am adding the code snippets for delay(), apply_async(), and Task.s(). Thank you! class Task(object): def apply_async(self, args=None, kwargs=None, task_id=None, producer=None, link=None, link_error=None, shadow=None, **options): """ Apply tasks asynchronously by sending a message. Arguments: args (Tuple): The positional arguments to pass on to the task. kwargs (Dict): The keyword arguments to pass on to the task. countdown … -
Django - Can I safely put information about is_staff in user model required fields to fetch them easily?
The problem is that I've tried to fetch info about user in react and the only fields that get returned from backend are the fields that are put in the required fields: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Provide an email!') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_staff'] def get_full_name(self): return self.name def __str__(self): return self.email Is it safe to do it like this or do I have to create separate api endpoint to return this information (I hope it is not necessary)? -
fixture not found using Factoryboy SubFactory
I'm getting an error building factories with subfactories to test django models. With models: class Space(ExportModelOperationsMixin('space'), models.Model): name = models.CharField(max_length=128, default='Default') class ShoppingListEntry(models.Model): food = models.ForeignKey(Food) space = models.ForeignKey(Space) class Food(models.Model): name = models.CharField(max_length=128) description = models.TextField(default='', blank=True) space = models.ForeignKey(Space) and fixtures: class SpaceFactory(factory.django.DjangoModelFactory): name = factory.LazyAttribute(lambda x: faker.word()) class FoodFactory(factory.django.DjangoModelFactory): name = factory.LazyAttribute(lambda x: faker.sentence(nb_words=3)) description = factory.LazyAttribute(lambda x: faker.sentence(nb_words=10)) space = factory.SubFactory(SpaceFactory) class ShoppingListEntryFactory(factory.django.DjangoModelFactory): food = factory.SubFactory(FoodFactory, space=factory.SelfAttribute('..space')) space = factory.SubFactory(SpaceFactory) and test def test_list_space(shopping_list_entry): assert 1 == 1 throws the following error Failed with Error: [undefined]failed on setup with def test_list_space(sle_1): file <string>, line 2: source code not available file <string>, line 2: source code not available E fixture 'food__name' not found I'm struggling to figure out how to troubleshoot this. -
Dash datatable wont render on page in django-plotly-dash
I am creating a web application using django_plotly_dash, a module combining Django, Plotly, and Dash into one package. I am having an issue where I can trying to load some dash datatables that are part of the dash app, but they never end up rendering on the page. The page is stuck on "Loading..." like so: As you can see, the middle of the page (starting from Home Page) is where the dash datatables are supposed to load, but the screen is stuck on "Loading..." from the log output after starting the app, it seems it has something to do with Django not locating the right static files. Here is the output below: Watching for file changes with StatReloader Performing system checks... C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_core_components package is deprecated. Please replace `import dash_core_components as dcc` with `from dash import dcc` return _bootstrap._gcd_import(name[level:], package, level) C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_html_components package is deprecated. Please replace `import dash_html_components as html` with `from dash import html` return _bootstrap._gcd_import(name[level:], package, level) C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py:127: UserWarning: The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format … -
Error running WSGI application, ModuleNotFoundError: No module named 'decouple' -- but module is installed
I've error with is "Error running WSGI application, ModuleNotFoundError: No module named 'decouple'" but i do have installed module. On the local version everything works fine with no errors, but when i put everything into pythonanywhere this erros starts to occur. requirements.txt asgiref==3.4.1 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.7 cryptography==35.0.0 defusedxml==0.7.1 Django==3.2.8 django-extensions==3.1.5 idna==3.3 oauthlib==3.1.1 Pillow==8.4.0 pycparser==2.21 PyJWT==2.3.0 pyOpenSSL==21.0.0 python-decouple==3.5 python3-openid==3.2.0 pytz==2021.3 requests==2.26.0 requests-oauthlib==1.3.0 six==1.16.0 social-auth-app-django==5.0.0 social-auth-core==4.1.0 sqlparse==0.4.2 urllib3==1.26.7 Werkzeug==2.0.2 manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookmarks.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() settings.py import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = ['mysite.com']#, 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django_extensions', ] MIDDLEWARE … -
Calling a function from another html template
So I have a base.html template and a review_result.html template that extends the base.html template. The base.html template has a script tag with lots of function. I am going to move a function called format from a script tag in the review_result.html to the base.html file. How do I then call the format function in review_result.html from base.html? -
Creating Django application inside of the project directory hierarchy?
In django rest framework quick start it creates the application inside of parent project directory instead of the top-level hierarchy for the sake of preventing conflicts with other packages. I'm asking is there any other benefit to this approach or on the other hand it will add overhead to the performance because of extra nesting? -
How to create users using Faker in Django Rest Framework
I am trying to create a fake user using faker and although the user instance is created I can't log in with its credentials. This is what my faker command looks like: from django.core.management.base import BaseCommand from faker import Faker from users.models import NewUser import random class Command(BaseCommand): help = "Command Information" def handle(self, *args, **kwargs): fake = Faker(["tl_PH"]) fname = fake.unique.first_name() lname = fake.unique.last_name() uname = "%s%s%d" % (fname.lower(), lname.lower(), random.randint(1000, 9999)) email = fake.unique.ascii_safe_email() password = "QaxSf96H" about = fake.sentence() newuser = NewUser.objects.create_user( first_name=fname, last_name=lname, username=uname, email=email, password=password, about=about ) newuser.save() -
Django - Error: NoReverseMatch at /post/.../ . Reverse for 'post_remove' not found
I'm working on my project "my-first-blog" and I'm totally stuck right now. I'm creating a blog with information about me for my portfolio. I've followed the Django tutorial and checked the code a hundred times but obviously there is something I'm missing. I'm creaing Delete Post. I'm getting an error when click on Title one of the blog: "Reverse for 'post_remove' not found. 'post_remove' is not a valid view function or pattern name." Can anybody see what I'm missing? Here you can see the full code https://github.com/valeriamilshtein/my-first-blog post_remove.html {% extends 'blog/base.html' %} {% block content %} <h1>Delete Post</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Delete</button> </form> {% endblock %} post_detail.html {% extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> <a class="btn btn-default" href="{% url 'post_remove' pk=post.pk %}"><span class="glyphicon glyphicon-remove"></span></a> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaks }}</p> </div> {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), url(r'^post/(?P<pk>[0-9]+)/remove/$', views.post_remove, name='post_remove'), ] views.py from django.shortcuts import render … -
django custome aggregate function in MySQL
Trying to create custom aggregate function to calculate median price in my tables, my code look like this: from django.db.models import Aggregate, FloatField class Median(Aggregate): function = "percentile_cont" output_field = FloatField() template = "%(function)s(%(expressions)s)" but if i run this in my query i get 1305, 'FUNCTION DATABASE.percentile_cont does not exist') Some one can help me with this? I use MySQL server, not mariadb -
How do I use retrieve database data using a Django GET Form?
I am having a bit of trouble understanding how forms work in Django. I would like to retrieve information from my database and display it in a dropdown menu. When the user selects one of the items and submits their choice, the following page should display the contents of that item. In my example I have 'Workouts' that contain 'Exercises'. After selecting a Workout, the Exercises of that Workout should be displayed. The error I am receiving is this: NoReverseMatch at /routines/ Reverse for 'routine' with arguments '('',)' not found. 1 pattern(s) tried: ['routines/(?P<workout_id>[0-9]+)/$'] And here is where I believe the issue lays: routines.html <form action="{% url 'routine_workouts_app:routine' workout.id %}" method="get"> {% csrf_token %} {{ form.as_p }} <button name="submit">Make Workout</button> </form> I am having an issue with the action of the form. The error says that it can't find the routine.html template (which I have double checked and it is spelt correct and exists). I think this is because whatever I'm doing with 'workout.id' is incorrect but I don't know why. Below, I will show the corresponding url and view. If more information, such as the form.py file, is needed I will provide. views.py def routines(request): #as it is, there … -
How to see the common runserver log from django in heroku?
I am running a Django app on Heroku, and I am getting an error that I am not getting on my local machine. I am getting a 500 error. Normally, I just see the log Django outputs on the CMD, but I can't see it in Heroku. How can I do this? BTW, it is not a dependency cause I just pip freeze > requirements.txt. Thanks! -
compress with pyminizip and return to response
I am trying to compress data with pyminizip and return the data as response in a Django project as follows def get_csv_file(request): response = HttpResponse(content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="member.zip"' users = User.objects.all() file_path = os.path.join(tempfile.gettempdir(), 'member.csv') f = open(file_path, 'w') file_writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL) for user in users: file_writer.writerow([user.username, user.email]) f.close() pyminizip.compress(file_path, "members", response, "pass", int(1)) return response getting this error ValueError at /get_csv_file/ expected arguments are compress(srcfile, prefix, zipfile, password, compress_level) -
Problem passing dictionary to API via requests.post()
As noted below, I am trying to pass the dictionary data to the API. def create_flow_and_phases(request): data = { "name": "name_example", "description":"description_example", "category": 2, "precedents": [2,3], "users": [1], "phases": [{ "name": "phase_name", "description": "description name", "sequence_number": 1, "precedents": [1] }] } # Making a POST request to save flow_and_phases url = API_HOST + "/api/flows/save_flow_and_phases/" answer = requests.post(url, data=data, headers={'Authorization': 'Token ' + request.session['user_token']}) if not answer.ok: raise Exception("An error occurred while creating flow.") Below, you can see that the dictionary data format is the same one passed in Insomnia to the API and that it works perfectly. { "name": "Testando criação de fluxo pelo Insomnia", "description": "Fluxo teste simulando informações de trato e colheita de café na fazendo fictícia Quipo", "category": 2, "precedents": [2, 3], "users": [1], "phases": [ { "name": "Trato anual", "description": "Descrição teste fase 1.", "sequence_number": 1, "precedents": [] }, { "name": "Trato anual 2", "description": "Descrição teste fase 2.", "sequence_number": 2, "precedents": [1] } ] } The backend receives data as below flow_data = dict(data) # data is passed as parameter But when I go to run the debub, the data referring to phases are not passed to the API as shown in the screenshot below … -
Nginx is not passing Authentication to gunicorn socket
So I've basically set up my basic backend. Locally the api runs like butter but whenever I deploy the application to production, the API responds always with: "detail": "Authentication credentials were not provided." I think nginx is not passing the header correctly to my socket running gunicorn. But I don't know how I would pass the Header to the socket. The Authorization is a basic JWT Token, so: AUthorization: Bearer bla-blubb-i-am-a-token-420-69 This is my nginx setup: server { listen 80; server_name dev.website.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/platform/backend/static; } auth_basic "Admin Login"; auth_basic_user_file /etc/nginx/.htpasswd; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } What am I missing?