Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO - How to make it possible for my users to connect to their calendars?
I'm planning to build an application with Django. One thing I'm not sure about is how to make it possible to have the users integrate their calendars. The idea is that users can create an appointment based on the availabilities in their calendars. They would be able to add availability slots (ex. this Monday between 14h - 18h) + timeframe (ex. 15 or 30 min) and then we can look if that is still open in their calendar. If it is free, we add it to their calendar. Since users might have a google, yahoo or outlook calendar, I'm not sure where to start. -
Testing DJango Serializer
I am writing a simple plugin (a django app) that performs few logical operations on serializers (of the desired app). For instance, in models.py of my plugin: class Logic(models.Model): # fields def do_something(self, instance): ser = get_serializer(instance) # some operation For the unittest, I thought of using default from django_comments.models import Comment but that does not have a serializer. Is there any default serializer that I could test against? I'd appreciate any suggestions -
How can I allow All users can login() while they are inactive in Django
my views : code = random.randint(100000, 999999) def register(request): #### when registration is ok global code subject = 'ok' message = "activation code" + str(code) email_from = settings.EMAIL_HOST_USER send_mail(subject, message, email_from, [email]) user.is_active = False user.save() login(request, user) ### problem is here, user cant login because activation is false return redirect('email_activation/') def email_activation(request): if request.method == "POST": global code email_activation = request.POST['email_activation'] if str(email_activation) == str(code): request.user.is_active = True request.user.save() return redirect('account') user should login in register to can activation become True in email activation i would be glad someone help me to how inactive user can login -
django.db.utils.OperationalError: no such table: hotel_addhotelstep2
I have make changes in models.py, also added some new models and after migrate I got an error As I understand it says that I have no created the models yet but if I cant do migrations and migrate how can I create any models there? Migrations for 'hotel': hotel\migrations\0029_auto_20210722_1841.py - Create model AddHotelStep1 - Create model AddHotelStep2 - Alter field hotel_name on doubleroom - Alter field hotel_name on singleroom - Delete model Hotel PS C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia> py manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, hotel, sessions Running migrations: Applying hotel.0029_auto_20210722_1841...Traceback (most recent call last): File "C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia\manage.py", line 22, in <module> main() File "C:\Users\Gegi\Desktop\Hotelpedia\hotelpedia\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) migration_recorded = True self.connection.check_constraints() File "C:\Users\Gegi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 343, in check_constraints raise … -
DRF filters.SearchFilter don'e work when I modify the get method?
I have this vide and it was working just find class UsersView(generics.ListAPIView): queryset = User.objects.all() serializer_class = serializers.UsersSerializer search_fields = ('username', 'email') but when I changed it to def get(self, request, *args, **kwargs): super().get(request, *args, **kwargs) context = {'request': request, 'method': 'view'} items = queryset_filtering(self.queryset.model, request.GET) serializer = self.serializer_class( items, context=context, many=True) return Response(serializer.data, status=status.HTTP_200_OK) the /users/?search=Alex don't work anymore? -
Deleting Model Data after specific sweet alert button click - Django
I am creating a donation web application that allows people to donate stuff. I have a screen where users can see details about a certain donation, and if they like it they can click on the accept button, and a sweet alert comes up. I am wondering how I can delete the current donation after the sweet alert is clicked. Basically, I can't figure out how to run python code after the js action happens. My code is down bellow Sweet alert (I want to run python code after the user clicks ok) function showAlert() { swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } -
Django - AutoCompleteSelectMultipleField with values
I'm using AutoCompleteSelectMultipleField from ajax_select.fields and it works fine - I'm getting values based on what I'm wrting, but I would like to have all values displayed before I write something. Is there any configuration I'm missing or should I use something different? At this moment I have: form.fields['teams'] = AutoCompleteSelectMultipleField( 'master_teams', plugin_options={ 'source': f"{reverse('ajax_lookup', kwargs={'channel': 'master_teams'})}?game_slug={self.game.slug}"}, required=False, help_text="Enter team name", ) and in my lookups file I just filter my query to get specific data and I would like to display them as a dropdown list in my template. Can anybody give me any hint how to solve this? -
Error base64 encoding when testing upload image in django restful framework
I'm writing unit tests trying to upload images and base64 encode it. But the encoding is different from expected. This is my tests.py with open('tests/image.jpg', 'rb') as image: r = self.client.post('/images', {'image': image}, format='multipart') This is my views.py def post(self, request): image = request.FILES['image'] base64_str = base64.b64encode(image.read()).decode('utf-8') The base64_str turns out to be like 7f7NCd0Aw29mVx...... Doing in a python script with open('tests/image.jpg', 'rb') as f: print(base64.b64encode(f.read()).decode('utf-8')) The output is /9j/4AAQSk...... I suppose there is something wrong with the encoding. So what's the problem? -
DirectAdmin CloudLinux Python Selector Django App - Application URL goes to root /home/<user>/<app>
I have setup a new DirectAdmin server with CloudLinux. I want to use the Python Selector option to build Django websites. I have created a test website, but the URL redirects to the root folder. django.[domain].nl/myapp/admin -> django.[domain].nl/home/[user]/myapp/admin /home/[user]/ is added extra. The full DirectAdmin path. I doubt whether this is a DirectAdmin setup error or a Django setting. -
getting problem with working json data for web development
hi i am working on python django project i need to convert my json data to datatable in frontend, i have using backend in python and frontend htmt,css,javascript for ex this is my json data- {"json_res": [{"car_number": mh00012, "trip":27,"empid":001,"onlinehrs":16}], "json_res1":[{"car_number":mh00014,"trip":100,"last_Week_trips":10}]} i want to make table like this in frontend- car_number trips empid onlinehrs last_week_trips mh00012 27 001 16 0 mh00014 100 0 0 10 -
Why my function in Views.py is not correct?
I have a Notification List view and this function def mark_as_read(request, notification_id): notification = get_object_or_404(Notification.objects.filter(pk=notification_id).exclude(viewed_at__isnull=False)) notification.viewed_at = datetime.datetime.now() notification.save() return redirect('users:notification') It works good but I think it is written not correct? Any body can tell it correct here working get_object_or_404? -
Saved task_id in database does not match Info from celery worker
I'm currently working on an application, that allows queueing of several tasks which should be allowed to be cancelled. For that to be possible, my task-model has a field for saving the task_id of the worker, and in Django, the user is presented with a list of the tasks and an option to stop individual tasks. The issue I am having is that the task_ids stored away in the database and the task_ids mentioned in the info line from the worker do not match until the worker has finished his task. i.e. the worker returns [2021-07-22 16:35:25,652: INFO/MainProcess] Received task: dop.tasks.execute_report[7490537f-90dd-4966-bff7-63d5461a92ff] but in the database, there's a different task_id saved until the worker returns a successful completion of the task. This prevents me from revoking any of the displayed tasks in the queue, because they have the wrong task_id associated with them. my code is below: def create_report(request, slug): ... # create report report = Report.objects.create( reportDefinition=reportDefinition, user=request.user ) ... transaction.on_commit( lambda: execute_report.delay( user_id=request.user.id, report_id=report.id, command_string=reportDefinition.get_command(), db_name=request.user.basex_prefix, resource_names=report.get_active_user_resource_names(), ) ) ... execute_report looks like this: @celery_app.task(bind=True) def execute_report( self, user_id, report_id, command_string, db_name, resource_names: list ): start_time = datetime.now() # get objects user = get_user_model().objects.get(id=user_id) report = Report.objects.get(id=report_id) report.task_id = … -
Django in_bulk() raising error with distinct()
I have the following QuerySet: MyModel.objects .order_by("foreign_key_id") .distinct("foreign_key_id") .in_bulk(field_name="foreign_key_id") foreign_key_id is not unique on MyModel but given the use of distinct should be unique within the QuerySet. However when this runs the following error is raised: "ValueError: in_bulk()'s field_name must be a unique field but 'foreign_key_id' isn't." According to the Django docs on in_bulk here it should be possible to use in_bulk with distinct in this way. The ability was added to Django in response to this issue ticket here. What do I need to change here to make this work? I'm using Django3.1 with Postgres11. -
DATETIME_FORMAT setting for my customized datetime field
I wrote a customized datetime field Now i want to add DATETIME_FORMAT setting for this customized field? -
How to set is_staff to True in Django when a user is created with a specific group selected
How would I automatically set is_staff to True when creating a new user in the Django admin when they have a specific group selected? -
Uploading image to Django database raises TypeError
I am having trouble uploading image paths into my Django database. When I try to add data without the eventImage field, it works fine. But when I upload anything to the eventImage field, it says: TypeError at /admin/events/event/add/ expected str, bytes or os.PathLike object, not tuple Request Method: POST Request URL: http://127.0.0.1:8000/admin/events/event/add/ Django Version: 3.2.5 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not tuple Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/posixpath.py, line 374, in abspath I've put relevant code snippets below. Please let me know what I'm doing wrong! In my settings.py file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'events', ] STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media'), STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] In my events.py file: from django.db import models class Event(models.Model): venueName = models.TextField() artistName = models.TextField() eventName = models.TextField() time = models.TextField() date = models.TextField() length = models.TextField() description = models.TextField() eventImage = models.ImageField( upload_to='media/', blank=True, null=True) def __str__(self): return self.eventName Any help would be hugely appreciated! -
how to solve Django url patterns not working
I added path('int:pk/',...) in urls.py and access 'http://127.0.0.1:8000/blog/1' the result was 'page not found(404)' Using the URLconf defined in doit.urls, Django tried these URL patterns, in this order: blog <int:pk>/ blog admin/ The current path, blog/1, didn’t match any of these. also, I made 3 pk contents please help me I suffered for a long time. urls.py from django.urls import path from . import views urlpatterns = [ path('<int:pk>/', views.PostDetail.as_view()), path('', views.PostList.as_view()), ] models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_at = models.DateTimeField() def __str__(self): return f'[{self.pk}]{self.title}' views.py from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model = Post ordering = '-pk' class PostDetail(DetailView): model = Post post_list.html <!DOCTYPE html> <html lang = "ko"> <head> <meta charset="UTF-8"> <title>Blog</title> </head> <body> <h1>Blog</h1> {% for p in post_list %} <hr/> <h2> {{ p.title }} </h2> <p> {{ p.content }}</p> <h4> {{ p.created_at }} </h4> {% endfor %} </body> </html> post_detail.html <!DOCTYPE html> <html lang="ko"> <head> <meta charset = "UTF-8"> <title> {{ post.title }} - Blog </title> </head> <body> <nav> <a href="/blog/">Blog</a> </nav> <h1> {{ post.title }} </h1> <h4> {{ post.created_at }} </h4> <p> {{ post.content }} </p> <hr/> <h3> ... </h3> </body> </html> -
Python: Object is missing attributes
Im working with the following object (from PyGuacamole: https://pypi.org/project/pyguacamole/0.7/): class GuacamoleClient(object): """Guacamole Client class.""" def __init__(self, host, port, timeout=20, debug=False, logger=None): """ Guacamole Client class. This class can handle communication with guacd server. :param host: guacd server host. :param port: guacd server port. :param timeout: socket connection timeout. :param debug: if True, default logger will switch to Debug level. """ self.host = host self.port = port self.timeout = timeout self._client = None # handshake established? self.connected = False # Receiving buffer self._buffer = bytearray() # Client ID self._id = None self.logger = guac_logger if logger: self.logger = logger if debug: self.logger.setLevel(logging.DEBUG) @property def client(self): """ Socket connection. """ if not self._client: self._client = socket.create_connection( (self.host, self.port), self.timeout) self.logger.info('Client connected with guacd server (%s, %s, %s)' % (self.host, self.port, self.timeout)) return self._client @property def id(self): """Return client id""" return self._id def close(self): """ Terminate connection with Guacamole guacd server. """ self.client.close() self._client = None self.connected = False self.logger.info('Connection closed.') def receive(self): """ Receive instructions from Guacamole guacd server. """ start = 0 while True: idx = self._buffer.find(INST_TERM.encode(), start) if idx != -1: # instruction was fully received! line = self._buffer[:idx + 1].decode() self._buffer = self._buffer[idx + 1:] self.logger.debug('Received instruction: %s' % … -
Django is loading static files but not image that are stored from backend in production
As the title says, after I changed DEBUG to False, the image that is uploaded from the admin panel are not loading. However, other static files like css files and images that are loaded only from HTML side are rendered properly. -
Django - Sum annotation adding group by id to clause
The following queryset subquery = aggregate_table.objects.filter( item__parent__name=OuterRef(dimension) ).annotate( aggregate_value=Sum(aggregation_field) ).order_by( 'item__parent__name' ).values('aggregate_value') queryset = queryset.annotate(aggregate_value=Subquery(subquery)) produces SQL that groups by both the name (supplied by the order_by) and by the id. SELECT SUM(U0."data") AS "aggregate_value" FROM "aggregate_table" U0 INNER JOIN "item" U1 ON (U0."item_id" = U1."id") INNER JOIN "parent" U2 ON (U1."parent_id" = U2."id") WHERE U2."name" = (T12."name") GROUP BY U0."id", U2."name" ORDER BY U2."name" ASC the ID produces incorrect results and instead of summing and returning 1 row with say 100 as the sum'd value, it returns 100 rows with 1 as the sum'd value. any ideas on how to remove the u0.id from the group by clause? -
display a spinner during data processing
I have written a django application for some data processing. In some cases, there could several minutes to wait until the processing is done. So I'd like to display a spinner on the page as soon as the user clicked on "excute" and all along the processing until the page is refreshed to display the results... I followed a tutorial (here) where I could set things up on the application and show the spinner when the page is loading. But this is not exactly what I'm looking for. The follwing JS code is coming from the video and shows the spinner until the page is loaded: const spinnerbox = document.getElementById('spinner-box') //console.log(spinnerbox) $.ajax({ type: 'GET', url: '/', success : function(response){ spinnerbox.classList.add('not-visible') console.log('response', response) }, error : function(error){ console.log(error) } }) I guess I need to modify this code, type should be 'POST' but I don't know what to add next to the script. Thanks for any help! Sébastien -
Django testing image
How to create image for test? I tried simpleUploadFile in different ways and it didn't work. I need test my endpoint. but have problem in image field My test: def setUp(self): self.card = Card.objects.create( title='card titulo', image='', amount=0, description='descricao', id= 1 ) self.user = User.objects.create_user( username='test', email='', password='have_senha' ) self.referral = Referral.objects.create(refferal_user=self.user, reffered_user=self.user) self.redeem = Redeem.objects.create(card=self.card,user=self.user) self.factory = RequestFactory() self.image = SimpleUploadedFile('donwload.jpeg', b'') def test_new_card(self): data ={ "title": "teste", "image": self.image, "amount": 0, "description": "TESET", "id": 24 } client = APIClient() client.force_authenticate(user=self.user) response = client.post('/card', data, format='json') print(response.json()) -
AWS EC2 and OpenCV with UDP consumer
I have two EC2 A That grabs the video feed from Amazon Kinesis Video to send it into via UDP to B B the consumer which it will grab the UDP feed from the A While debugging my opencv not grabbing the UDP feed, I suspect something is wrong with ffpmeg, so I am going to make sure that ffplay can read packets sent from A. Now when I try to read udp packets with ffplay {adress-ip-with-port}I have the following error : Could not initialize SDL - No available video device (Did you set the DISPLAY variable?) How do I fix this one since there is no display on EC2. Also if it can help, this is my code for the consumer part Create your views here. from django.http import HttpResponse from django.template import loader from django.shortcuts import render # from .models import Vehicule import cv2 import threading from django.views.decorators import gzip from django.http import StreamingHttpResponse @gzip.gzip_page def webcam(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'vebcam.html') #capture video class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture('udp://172.31.57.243:55055', cv2.CAP_FFMPEG) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) … -
Django Views: Display and access data from csv file of users to create them
Currently I'm doing this via a management command that takes a csv, iterates through to create users. I'd like to do this via a view form where rows are populated by the data so eventually I can look and modify if typos in rows before importing. Here is an example of the csv. code: password = 'tempass12345' with open(file_path, mode='r', encoding='utf8') as csv_file: data = csv.reader(csv_file) for row in list(data)[1:]: first_name, last_name, email = row user = User.objects.create( username=email, first_name=first_name, last_name=last_name, email=email, password=password ) # csv file First Name,Last Name,Email Roy ,Cot, rcot@xyz.com What's the best django approach to doing this? The file will not be stored. -
How can assign foreign key of Abstrat User Model in django
When i submit the button it show the error "Vendor_Profile.auth_user" must be a "Auth_User" instance. Auth_User is an Abstract User Model.py class Auth_User(AbstractUser): is_vendor = models.BooleanField(default=False) class Vendor_Profile(models.Model): auth_user = models.ForeignKey(Auth_User, on_delete=models.CASCADE) name = models.CharField(max_length=50) View.py try: vendor = Vendor_Profile( auth_user=request.session['USER_ID'], name=self.request.POST.get('name') ) vendor.save() return render(request, 'home.html') except Exception as e: return HttpResponse('failed{}'.format(e))