Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chunked upload on apache
I am running a Django application on an Apache2 server, but each time I try to upload a file, I get a PermissionError: [Errno 13] Permission denied: '/chunked_uploads' error. I already gave permission to write into the chunk_uploads directory, but it did not work out either. Does some have an idea how to fix it? My config file: <VirtualHost *:80> Alias /static /home/usr/app/static <Directory /home/usr/app/static> Require all granted </Directory> <Directory /home/usr/app/backend> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess app python-path=/home/usr/app python-home=/home/usr/app/appEnv WSGIProcessGroup app WSGIScriptAlias / /home/usr/app/backend/wsgi.py WSGIChunkedRequest On # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # … -
Django use urls with same ending
I ahve a django project with the application web-api and the following url configuration: main project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('web-api/', include('webapi.urls')), ] application web-api/urls.py urlpatterns = [ path('<param1:param1>/summary', Param1Summary.as_view()), path('<param1:param1>/item/<int:id>/summary', ItemView.as_view()), ] The /web-api/param1/summary endpoint works but /web-api/param1/item/12121/summary does not work and returns a 404 status code. If I change the <param1:param1>/item/<int:id>/summary' to <param1:param1>/item/<int:id>/whatever, in the web-api/url.py I get the desired results. I have tried using url regex without succees. Any ideas on how to solve the problem? Thanks in advance! -
Import "rest_framework_swagger.views" could not be resolved
I wanted to implement swagger in Django rest framework, for that I install django-rest-swagger and register in setting.py but while importing in url.py it show error:- "Import "rest_framework_swagger.views" could not be resolved. How can I use rest_framework_swagger? -
Get the client_id and client_secret dinamically in django with the social_oauth2 authentication
I want to authenticate the users with Oauth but in the request to get the tokens I have to put the client_id and client_secret hardcoded, is there a better form to have dynamically these credentials, or just I have two credentials for all the users? Thank you! -
DJANGO VIews: how can I add another view already developed to a new one?
i am new with django with poor programming experience. I have written a view (agence view) in django which works fine. I would like to add this view to another one in the developing process. the new one includes agnecy view plus other attributes to write.. can someone help me please thanks in advance the existing view def nos_agences (request): """"display nos agences""" try: agence = Agence.objects.all() except Agence.DoesNotExist: raise Http404 return render(request, 'visitor/nos_agences.html', {'agences':agence}) path('nos_agences',views.nos_agences, name= 'nos_agences'), the new one which must include nos_agences def reservation (request): return render(request, 'visitor/reservation.html') -
How to change seed packages versions when creating virtualenv?
I am running into an issue when deploying a django-rest-framework API to production. The addition of seed packages pip, setuptools and wheel upon virtualenv's creation causes my deployment to fail. It appears that the specific version of setuptools (59.1.1) used here prevents usage from Newlines (related to this issue) which are used in the description of django-hijack==2.10.1 and causes the following error. This behaviour has been reverted in the newer versions of setuptools (from 59.4.0). Thus I would like to pin the version of setuptools added in seed packages upon virtualenv creation to make sure my deployment succeeds but I have no idea if/where I can set added packages versions. Any help is appreciated! Successfully created virtual environment! Virtualenv location: /var/www/backoffice/20211223111028/back/.venv Installing dependencies from Pipfile.lock (6e978f)... Ignoring appnope: markers 'sys_platform == "darwin"' don't match your environment To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. Running command 'cd /var/www/backoffice/20211223111028/back && pipenv install' on host 172.31.128.48 Creating a virtualenv for this project... Pipfile: /var/www/backoffice/20211223111028/back/Pipfile Using /home/ignition/.pyenv/versions/3.9.0/bin/python3.9 (3.9.0) to create virtualenv... ⠸ Creating virtual environment...created virtual environment CPython3.9.0.final.0-64 in 152ms creator CPython3Posix(dest=/var/www/backoffice/20211223111028/back/.venv, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, wheel=bundle, pip=bundle, setuptools=bundle, via=copy, app_data_dir=/home/ignition/.local/share/virtualenv) added … -
How to change dates when filtering a queryset in Django?
I want to display a list of all payments done by the company. But I want to be able to filter the dates, only showing payments for example: In the last 30 days In the last 90 days Between two specific dates Now, I know I can filter in my views between two dates, or before today for example. But how I can I do this using something like a dropdown or a Data chooser on the template? Something like this for reference. For reference, the payments model would be this: class Payment(models.Model): name = models.CharField(max_length=250) date = models.DateField(default=datetime.now) value = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0.00)]) -
Google Login Redirect Url Integrity Error
I have done proper configurations and google login is working correctly. When Google authenticates and redirect user to website it shows this error IntegrityError at /auth/social/google/ null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 166, null, null, null, null, null). Request Method: POST Request URL: http://cozmo.gvmtechnologies.com:8000/auth/social/google/ Django Version: 2.0.9 Python Executable: /root/.local/share/virtualenvs/cozmo-FEPF8JuT/bin/python Python Version: 3.6.15 Python Path: ['/root/cozmo-server-develop/cozmo', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/root/.local/share/virtualenvs/cozmo-FEPF8JuT/lib/python3.6/site-packages', '/root/cozmo-server-develop/cozmo'] Server time: Thu, 23 Dec 2021 10:11:01 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.postgres', 'guardian', 'storages', 'rest_framework', 'rest_framework_swagger', 'rest_framework_tracking', 'rest_framework_jwt', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'rest_auth', 'rest_auth.registration', 'cozmo_common.apps.CozmoCommonConfig', 'accounts.apps.AccountsConfig', 'automation.apps.AutomationConfig', 'accounts.profile.apps.ProfileConfig', 'app_marketplace.apps.AppMarketplaceConfig', 'crm.apps.CrmConfig', 'listings.apps.ListingsConfig', 'events.apps.EventsConfig', 'listings.calendars.apps.CalendarsConfig', 'notifications.apps.NotificationsConfig', 'owners.apps.OwnersConfig', 'pois.apps.PoisConfig', 'payments.apps.PaymentsConfig', 'public_api.apps.PublicApiConfig', 'message_templates.apps.MessageTemplatesConfig', 'rental_connections.apps.RentalConnectionsConfig', 'rental_integrations.apps.RentalIntegrationsConfig', 'rental_integrations.airbnb.apps.AirbnbConfig', 'rental_integrations.booking.apps.BookingConfig', 'rental_integrations.expedia.apps.ExpediaConfig', 'rental_integrations.homeaway.apps.HomeawayConfig', 'rental_integrations.trip_advisor.apps.TripAdvisorConfig', 'send_mail.apps.SendMailConfig', 'search.apps.SearchConfig', 'vendors.apps.VendorsConfig', 'send_mail.phone.apps.PhoneConfig', 'services.apps.ServicesConfig', 'chat.apps.ChatConfig', 'settings.apps.SettingsConfig', 'rental_network.apps.RentalNetworkConfig', 'dashboard.apps.DashboardConfig', 'pricing.apps.PricingConfig', 'behave_django', 'corsheaders', 'internal.apps.InternalConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.messages.middleware.MessageMiddleware'] Exception Type: IntegrityError at /auth/social/google/ Exception Value: null value in column "appointments_enabled" violates not-null constraint DETAIL: Failing row contains (166, 2021-12-23 10:11:01.370877+00, 2021-12-23 10:11:01.370907+00, f, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, … -
ModuleNotFoundError: No module named 'django.utils'
Hi am getting these error ...do we know how to fix Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/mnt/c/Users/krammurti/counselcareer/venv/lib/python3.8/site-packages/django/init.py", line 1, in from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' -
How to display files by only its name
[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/sjO7r.jpg Here i want to display only the file name i.e sample.pdf. I use postgresql as database ,django rest for backend and angular as frontend. If you want other code ask me i will share -
KeyError: 'password'
There's frontend on react and backend on Django, on registering user, got an issue with password field,like ** KeyError 'password'**, the code is below. serializer.py ... class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' ... views.py ... from.django.contrib.auth.hashers import make_password ... @api_view(['POST']) def userRegister(request): data = request.user user = User.objects.create( email = data['email'] password = make_password(data['password']) serializer = UserSerializer (user, many=False) return Response (serializer.data) ... -
User form foreignkeyfield form not valid
I was creating a post based website i want to show the author's name to show up in the post it works in the admin site when adding posts but when i try uploading a post from the site the form is not getting validated therefore it is not getting saved please help model : from django.conf import settings class MemeImg(models.Model): Title = models.CharField(max_length=500) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) Post_Img = CloudinaryField('Post') forms : class PostImg(forms.ModelForm): class Meta: model = MemeImg fields = ['Title', 'op', 'Post_Img'] view : @login_required(login_url='/login') def post(request): func = data(request) if request.method == 'POST': form = PostImg(request.POST, request.FILES, instance=request.user) form.op = request.user if form.is_valid(): print('success') posts = form.save(commit=False) posts.op = request.user form.save() return HttpResponseRedirect('https://youtu.be/dQw4w9WgXcQ') else: print("fail") form = PostImg(request) ctx = { 'form': form, 'url': func[0], 'name': func[1], 'date': func[2], } return render(request, 'Post.html', ctx) and finally the post page template : <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="container"> {{ form.Title|materializecss }} <div class="file-field input-field"> <div class="btn"> <span>File</span> <input type="file"> </div> <div class="file-path-wrapper"> {{ form.Post_Img }} <input class="file-path validate" type="text"> </div> </div> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </div> </form> If anymore code is required please … -
How to retrieve data from MySQL database in Django and display it in html page?
I am trying to add data from MySQL database and display it in a html page using python. Here is my view.py: def show(request): data = Persons.objects.all() person = { "Persons": data } return render(request, "home.html", person) models.py: class Persons(models.Model): PersonID = models.IntegerField() LastName = models.CharField(max_length=100) FirstName = models.CharField(max_length=100) Address = models.CharField(max_length=100) City = models.CharField(max_length=100) class Meta: db_table = "persons" html: <div> <div class="numbers">Graph</div> {% for item in Person %} {{ item.LastName }} {% endfor %} </div> But I didnot retrieve anything. Any help will be highly appreciated. -
Google Cloud App Engine (Django) and Google Cloud Storage working on a Single Domain with Custom URLs
I have a Django application working on supereye.co.uk. Django handles all URL routing such as supereye.co.uk/signin supereye.co.uk/watch etc. I am also using Google Cloud Storage that is working with Google Cloud App Engine on gs://production2.supereye.co.uk How shall I handle the routing so both App Engine and Storage can be accessible through the supereye.co.uk domain. For instance : supereye.co.uk -> Django App, Google Cloud App Engine data.supereye.co.uk -> Google Cloud Storage bucket, gs://production2.supereye.co.uk Is there any way to achieve this without relating Django App to bucket at all ? Can the bucket be accessible by its own resources? Is there any internal Google Cloud tool that will let me achieve this ? -
Best way to handle articles with Django
I'm looking for the best possible way to manage articles in Django. My idea was to load the articles as static files (there's no upload from users, so no form necessary, I guess), then create the model, but which field type to use here ? Textfield or FilePathField (in the static ?) or something else ? Then create the view and render it. The articles will be showned as cards with a summary on the index page, and each card will point to the full article page. If someone would point me in the right direction, I would appreciate. I'm checking the docs since yesterday, I might have missed the relevant part. -
Add custom admin actions to django irrelevant to objects
I want to add admin actions (for example with buttons) to django admin site that are irrelevant to particular model, for example doing administrative tasks such as optimizing database or clearing cache or log files or deleting records from multiple tables... I have seen django admin action without selecting objects, but the answers seems tricky and the solutions was selecting objects of particular model, in other ways. Is there a better to add this functionality to admin site anyway? -
How Django works with Mongodb
I need to make a Django restful api. I have a volume of data that is distributed in a tree structure with 3 attachments. I want to implement this nesting in Mongo: base->collection->object. The objects are generally the same so I don't really want to prescribe millions of models. I can draw an analogy with library: hall->stack->book. Each shelf has different books on it, but all of them are made of paper and covers. I found how to work with different databases and how to send the model to a certain database: 'default': { 'ENGINE': 'djongo', 'NAME': 'some_name', 'CLIENT': { { "host": "mongodb://.........../", } }, { "user": { 'ENGINE': 'djongo', 'NAME': 'some_name2', 'CLIENT': { { "host": "mongodb://......../", } } And accessing different databases Author.objects.using('other').all(). How to relate one model to one collection I found too: class MongoMeta: db_table = "some_collection_name" But how to combine all this I can't find. That one model can belong to different databases to different collections while being one single. -
Cannot connect to websocket by unicorn and uwsgi
I have tried the following 6 methods to start my django project. 1. command=python3 manage.py 2. command=daphne myproject.asgi:application -b 0.0.0.0 -p 778 3. command=uwsgi --ini /root/uwsgi.ini 4. command=uvicorn myproject.asgi:application --workers 4 --host 0.0.0.0 --port 778 5. command=gunicorn myproject.wsgi --workers 2 --bind 0.0.0.0:778 6. command=gunicorn myproject.asgi:application -k uvicorn.workers.UvicornWorker -b 0.0.0.0:778 However, only the first two methods are able to connect to websocket. Unfortunately, there is not two much error details left in my client(Only know the error code is 1006). Anyone knows why I cannot connect? -
Django - getting user input from HTML file (jQuery post, get) printed in console
I'm trying to get the user input printed in terminal by using jQuery, but for some reason I'm not getting it. On /aktoriai/ there's a form that requires a movie title to be entered and when I enter it, nothing get printed. When loading up the page, "get" is being printed and after clicking the button, "post" is being printed. HTML snippet: <script src="https://code.jquery.com/jquery-3.5.0.js"></script> <script> // Attach a submit handler to the form $( "#searchForm" ).submit(function( event ) { // Get some values from elements on the page: var $form = $( this ), term = $form.find( "input[name='movie_title']" ).val(), url = $form.attr( "aktoriai" ); // Send the data using post var posting = $.post( url, { s: term } ); }); </script> <form method="post"> <label for="movie_title">Filmo pavadinimas: </label> <input type="text" name="movie_title"> <input type="submit" value="OK"> </form> views: @csrf_exempt def aktoriai(request): # print(request.GET) if request.method == "GET": print("get") print(request.get['movie_title']) objects = Filmlist.objects.none() # # return render(request, "aktoriai.html", context={'objects': objects}) return render(request, "aktoriai.html", context={'objects': objects}) if request.method == "POST": print("post") objects = Filmlist.objects.none() # return render(request, "aktoriai.html", context={'objects': objects}) return render(request, "aktoriai.html", context={'objects': objects}) -
How to post foreign key id only once in Django
class Department(models.Model): name = models.CharField(max_length=50) class Employee(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() department = models.ForeignKey(Department, on_delete=models.CASCADE) I'm really wondering how to do this. Suppose there are three departments with id 1, 2, 3. So in employee model if i posted some employee with name abc and department 1. So next time if i will try to post the same department id that is 1 for another employee. I should not be able to do that. Validating this field does not work i believe because of foreign key.So how to achieve this. Any help would be really appreciated. Thank you !! -
I/O time differing on docker containers
I am running this script to test I/O performances on my docker containers. from tempfile import NamedTemporaryFile d = 500 n = 100000 with NamedTemporaryFile() as f: for i in range(n): nums = [] for j in range(d): nums.append(str(round(random.uniform(0, 1000), 3))) s = ' '.join(nums) f.write(s.encode()) f.write('\n'.encode()) Strange thing is execution time differs depending of containers On container 1 : 65.96740865707397 seconds On container 2 : 71.00589632987976 seconds The only thing differing between these 2 containers is the command docker executes : Container 1 command is : ./manage.py runserver 0.0.0.0:80 (this is django) Container 2 command is : python3 manage.py rqworker my_queue (this is django_rq) Do you have any idea why I have such a difference of 5 seconds ? Or do you know where could I investigate ? -
HOW DO I AVOID DUPLICATE ENTRIES WHILE TAKING DATA FROM AN API IN DJANGO MODELS
from home.models import suppotors for i in items: if i['status'] != "failed": ins = suppotors(name=i['notes']['name'] , amount = i['amount']) ins.save() return True "SUPPOTORS" is a model that im using and "ITEMS" is the data im getting from the api , when ever i reload the page django saves the of items in the suppotors model HOW DO I AVOID DUPLICATE ENTRIES? -
Different upload and download urls for Django Models's Image Field
I need a way to have different upload and download URLs for ImageField. I want to upload the image to AWS S3 and while accessing the image I want the image to route through CDN (in my case Fastly). def get_avatar_upload_path(identity, filename): file_ext = filename.split('.')[-1] file_name = f'{uuid.uuid4()}.{file_ext}' return f'{settings.AWS_MEDIA_PREFIX}{identity.uuid}/{file_name}' class Identity(identity_revision_base): """ Identity model. Ties a user to a chat identity. """ badges = models.ManyToManyField(Badge, blank=True) key = models.UUIDField(_("key"), unique=True, default=uuid.uuid4) uuid = models.UUIDField(_("UUID"), unique=True, default=uuid.uuid4) avatar = models.ImageField(upload_to=get_avatar_upload_path, blank=True) user = models.ForeignKey( to=settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name="+", ) Just like I am specifying upload path in ImageField, I would like a way to do something similar for accessing Image. It also seems that I cannot modify avatar.url once it is created. Is there any way around? -
TypeError while testing answer checker
I'm writing a test for my "answer checker", so I made a test question and I want to test if the result checker works by giving the right answer (so the test should pass). I'm in some trouble with the error that I got back. I know the code it's not that good, but I'm new in this field. I think I've misunderstood something in the logic. Can anybody help? :) Error is: correct = QuestionMultipleChoice.correct_answer() TypeError: 'property' object is not callable Test (the last lines are wrong I know): @when(u'I give an answer to a Multiple choice question') def save_object(context): lab1 = Lab.objects.create(lab_name="testlab", pub_date=datetime.now(), lab_theory="test theory") question1 = QuestionMultipleChoice.objects.create(lab=lab1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer=1) @then(u'I should get true if answer is correct') def should_have_only_one_object(self): given = 1 correct = QuestionMultipleChoice.correct_answer() QuestionMultipleChoice.check_answer(correct, given) assert 1 == Lab.objects.count() Models.py class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given -
Convert a timestamp to a DateTime field?
I've got a DateTimeField(auto_now_add=True) in my model. However, I wish to update this field, and the format I'm receiving from my API is a UNIX timestamp. Can I somehow convert the format I receive from my API to the correct one? (eg 1640206232 to 2021-12-22 20:50:32). Using postgres as my db if that matters..