Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does this Error Message ModuleNotFoundError: No module named 'betterforms' show up and how to avoid it?
I have built this model and would like to have its forms on one page using MultiModelForm but I am receiving this Error message: ModuleNotFoundError: No module named 'betterforms' from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __unicode(self): return u'%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __unicode(self): return u'%s' % self.image_file class Question(models.Model): questions_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __unicode(self): return u'%s' % self.question_description class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __unicode(self): return u'%s' % self.answer_description This is the forms.py from django import forms from .models import Topic, Image, Question, Answer from betterforms.multiform import MultiModelForm class TopicForm(forms.ModelForm): topic_name = forms.ModelMultipleChoiceField( queryset = Topic.objects.all(), widget = form.SelectMultiple( attrs = {'class': ''} )) class Meta: model = models.Topic fields = ['topic_name'] class QuestionForm(forms.ModelForm): topic_name = forms.ModelChoiceField( queryset = Topic.objects.all(), widget = form.Select( attrs = {'class': ''} )) class Meta: model = models.Question fields = ['questions_type'] class QuizMultiForm(MultiModelForm): … -
Django EmailValidator validating trailing dots
I'm using Django 1.9, and EmailValidator seems to be validating trailing dots in email ids. faulty_email = 'sid@h.in.' user.email = faulty_email user.save() The above piece of code runs smoothly even though email is an EmailField, which has EmailValidator. The weird thing is, when I run the validation manually, it throws a ValidationError. In [1]: from django.core.validators import validate_email In [2]: faulty_email = 'sid@h.in.' In [3]: validate_email(faulty_email) --------------------------------------------------------------------------- ValidationError Traceback (most recent call last) <ipython-input-3-bdbbd57d5fe1> in <module>() ----> 1 validate_email(faulty_email) /usr/local/lib/python2.7/dist-packages/django/core/validators.pyc in __call__(self, value) 201 except UnicodeError: 202 pass --> 203 raise ValidationError(self.message, code=self.code) 204 205 def validate_domain_part(self, domain_part): ValidationError: [u'Enter a valid email address.'] Does anyone know what the issue is? -
Serialize Admin Change List Filters for Celery
Given the following conditions: A non-trivial admin action must be performed on thousands of rows. The rows are the result of complex custom admin filters. What's the best way to handle this scenario? We have considered Synchronously handling the request within the request/response cycle. This takes too long. Sending the resulting QuerySet to celery via Pickle, but the Pickle serializer is considered to be insecure. Reconstructing the QuerySet in a Celery task from admin URL query parameters. Would require delving into private Django admin methods. -
Django : Add post id to the slug only if it already exists
Here is my code to generate slug,in models.py, def save(self): self.slug = slugify(self.title) super(Post, self).save() I want to check if the slug already exists in my database or not and then only add the id to that slug. Only way I can think of now is to add id in every slug by doing this, def save(self): super(Post, self).save() if not self.slug: self.slug = slugify(self.title) + "-" + str(self.id) self.save() The problem is, it adds id in all the slugs. So how can I check if a slug already exists due to same title and then only add the id to that slug? -
Update contents of a form without refreshing the page in django
I am working on a django application. In this application a user can upload an image. Once the image is uploaded an image classifier runs on the image and an image_description form is auto-filled based on the classifier output. When the form is submitted the item is displayed in a new page. This is my url patterns urls.py urlpatterns = [ path('', views.index, name='home'), path('accounts/', include('django.contrib.auth.urls')), path('signup/', views.signup, name='signup'), path('items/', views.item_list, name='item_list'), path('items/upload/description/', views.upload_item, name='upload_item'), path('items/<int:pk>/', views.delete_item, name='delete_item'), path('items/upload/image_classification/', views.image_classification, name='image_classification'), ] here item_list is the page where all items are displayed. This page is displayed once the form is submitted. upload_item page contains a form to upload the image and also contains another form that is auto-filled once the classifier runs on the image. image_classification runs when upload image button is clicked.this happens in the upload_item page. views.py def item_list(request): items = Item.objects.all() return render(request, 'item_list.html', {'items':items}) def upload_item(request): if request.method == 'POST': form_des = ItemForm(request.POST, request.FILES) if form_des.is_valid(): form_des.save() return redirect('item_list') else: form_des = ItemForm() return render(request, 'upload_item.html', {'form_des': form_des}) def image_classification(request): form_des = ItemForm() if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) img = np.expand_dims(cv2.resize(cv2.imread(os.path.join('./media/item/img/', str(request.FILES['file']))), (170, 100)), axis=0) cat_prediction = cat_classifier.predict_classes(img)[0] pattern_prediction = pat_classifier.predict_classes(img)[0] … -
Ansible Failed! OpenEdx Hawthorn .2 Native Installation
My apology if I posted it in wrong place because I am not sure where should I post the problem (StackOverflow or ServerFault) I am trying to install OpenEdx Hawthorn .2 Native on a fresh Ubuntu 16.04 machine. But failed with the following error each time. Here are the exact same commands I have used to install OpenEdx: export OPENEDX_RELEASE=open-release/hawthorn.2 wget https://raw.githubusercontent.com/edx/configuration/$OPENEDX_RELEASE/util/install/ansible-bootstrap.sh -O - | sudo bash wget https://raw.githubusercontent.com/edx/configuration/$OPENEDX_RELEASE/util/install/generate-passwords.sh -O - | bash wget https://raw.githubusercontent.com/edx/configuration/$OPENEDX_RELEASE/util/install/native.sh -O - | bash I performed the 3 commands on my /home/username/ directory. The first 3 commands performed successfully but on the last command, I am getting the following error. Here are the machine details where I tried to install OpenEdx: OS Name: Ubuntu 16.04.05LTS (Xenial Xerus) 64-bit PC (AMD64) desktop image RAM: 16GB Storage: 80GB CPU Core: 4 Condition: Fresh Install Java Version: 1.8.0_201 Without th,is machine I have tried installing it on 3 different Google Cloud Compute Engine (Singapore Based), 1 Azure Virtual Machine (Singapore Based) and on 3 local Virtual Machine. I have also tried it on Ubuntu 16.04 LTS Server version. But each time I am getting this error. When I go my browser and type http://127.0.0.1 I am getting the … -
Sending data from Python Web socket client to Django Channels
I am trying to send data to Django Channels (chat application) from Python web socket client . I am able to do the handshake but my data (string) is not being populated in the chat web page. My consumers of django channels consumers.py class EchoConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'power_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message })) My Python web socket client my-websocket.py def on_message(ws, message): print (message) def on_error(ws, error): print ("eroror:", error) def on_close(ws): print ("### closed ###") # Attemp to reconnect with 2 seconds interval time.sleep(2) initiate() def on_open(ws): print ("### Initiating new websocket connectipython my-websocket.pyon ###") def run(*args): for i in range(30000): # Sending message with 1 second intervall time.sleep(1) ws.send("Hello %d" % i) time.sleep(1) ws.close() print ("thread terminating...") _thread.start_new_thread(run, ()) def initiate(): websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:8000/ws/power/room/", on_message … -
How to display data in table?
I m using report generator, so my data is following a format [{1:20,2:30,3:40},{1:50,2:10,3:80},{1:70,2:30,3:60}] hear 1,2,3... are keys and 20,30,40,... value so this data send frontend side and display in the table. table format like 1 | 2 | 3 ----------- 20| 30| 40 ----------- 50| 10| 80 ----------- 70| 30| 60 ----------- Hear 1,2,3,.. are table head() and other is data() so how to show data this format. -
Auto reloading Django server on Docker
I am learning to use Docker and I have been having a problem since yesterday (before I resorted to asking, I started to investigate but I could not solve the problem), my problem is that I have a Django project in my local machine, I also have the same project with Docker, but when I change my local project, it is not reflected in the container that the project is running. I would be very grateful if you could help me with this please. Thank you. Dockerfile FROM python:3.7-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 \ && apk del build-deps RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /code RUN pipenv install --skip-lock --system --dev COPY ./entrypoint.sh /code COPY . /code ENTRYPOINT [ "/code/entrypoint.sh" ] docker-compose.yml # version de docker-compose con la que trabajaremos version: '3' # definiendo los servicios que correran en nuestro contenedor services: web: restart: always build: . command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 #python manage.py runserver 0.0.0.0:8000 volumes: - .:/code - static_volume:/code/staticfiles - media_volume:/code/mediafiles expose: - 8000 … -
Django: url instead of image in Admin
I need to show a image preview (small size image) of my order_item in admin. I'm basically following these other question/answer here: Django Admin Show Image from Imagefield However, I cannot get the desired results. I'm getting this instead: I though it was maybe the URL, but the relative path of that file is the same (except for the static part): static/media/images/python.png What could be wrong? models.py: class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.CharField(max_length= 200) quantity = models.CharField(max_length= 200) size = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price') image = models.ImageField(upload_to='images', blank=True, null=True) comment = models.CharField(max_length=200, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "OrderItem" def image_thumbnail(self): return u'<img src="%s" />' % (self.image.url) image_thumbnail.short_description = 'Image Thumbnail' image_thumbnail.allow_tags = True def sub_total(self): return self.quantity * self.price admin.py # Register your models here. class OrderItemAdmin(admin.TabularInline): model = OrderItem fieldsets = [ # ('Customer', {'fields': ['first_name', 'last_name'], }), ('Product', {'fields': ['product'],}), ('Quantity', {'fields': ['quantity'],}), ('Price', {'fields': ['price'], }), ('Image', {'fields': ['image'], }), ('Image_Thumbnail', {'fields': ['image_thumbnail'], }), ] readonly_fields = ['product', 'quantity', 'price', 'image', 'image_thumbnail'] can_delete = False max_num = 0 template = 'admin/order/tabular.html' ### Order Display ### @admin.register(Order) class OrderAdmin(admin.ModelAdmin): model = Order list_display = ['id', 'first_name', … -
Return only single field of the nested field(array) using Django
My model: class Languages(models.Model): code = models.CharField(max_length=2) name = models.CharField(max_length=50) class Translate(models.Model): lang_code = models.ForeignKey(Languages,related_name = 'translate', on_delete=models.CASCADE) ncode = models.CharField(max_length=2) name = models.CharField(max_length=50) My view: class Languages_List(mixins.ListModelMixin): queryset = Languages.objects.all() serializer_class = LanguagesSerializer def get_queryset(self): queryset = Languages.objects.all() lang = self.request.query_params.get('ncode',None) queryset = queryset.filter(translate__ncode=lang) return queryset My serializer: class TranslateSerializer(serializers.ModelSerializer): class Meta: model = Translate fields = ('ncode','name') class LanguagesSerializer(QueryFieldsMixin,serializers.ModelSerializer): translate = TranslateSerializer(many=True) class Meta: model = Languages fields = ('id', 'code','name','translate') I am able return the result by filtering my nested field.my url looks like: GET /lang/?ncode=kn Now my result is : I need only 'kn' should be returned without 'te'. How to achieve this using Django? -
Trying to save data scrapped from LinkedIn into SQL database
I'm trying to save scrapped data from LinkedIn in to a SQL database on a button click. I have tried saving data using django models and views but nothing is working. views.py def home(request): form = ProfileData(request.POST) if request.method == 'POST': form.save() return render(request,'ScreeningWebApp/home.html',{'form':form}) I want to save data coming in the below variables which are in another function def extract(): name = validate_field(name) job_title = validate_field(job_title) company = validate_field(company) college = validate_field(college) location = validate_field(location) linkedin_url = validate_field(linkedin_url) models.py class ProfileData(models.Model): name = models.CharField(max_length=100) job_title = models.CharField(max_length=100) company = models.CharField(max_length=100) college = models.CharField(max_length=200) location = models.CharField(max_length=100) linkedin_url = models.CharField(max_length=200) def __unicode__(self): return "{0} {1} {2} {3} {4} {5}".format(self.name,self.job_title,self.company,self.college,self.location,self.linkedin_url) html <form action= '' method="POST" novalidate> {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Start Searching..</button> <h1>{{ data }}</h1> </form> -
Zip File downloaded from ReactJs/Axios is corrupted
I'm trying to download a zip file from a Django api and have the user download it. There are two .csv files in the zip. I am able to download a single .csv files individually, but when I try to download the zip and unzip, I get errors that the zip is corrupted. For sanity check, I am able to send the request via Postman. I am able to successfully download and unzip the file using that. Here is my code fragment: axios .post('http://0.0.0.0:8000/sheets/', data, { headers: { 'Content-Type': 'multipart/form-data', 'responseType': 'arraybuffer' } }) .then(res => { console.log(res.data) const disposition = res.request.getResponseHeader('Content-Disposition') var fileName = ""; var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { fileName = matches[1].replace(/['"]/g, ''); } let blob = new Blob([res.data], { type: 'application/zip' }) const downloadUrl = URL.createObjectURL(blob) let a = document.createElement("a"); a.href = downloadUrl; a.download = fileName; document.body.appendChild(a); a.click(); -
solution for django.db.utils.OperationalError
I am a student (using Ubuntu) who has recently started with studying database and django. I have been trying to open one of my team member's django web, but when I type 'python manage.py runserver', it shows me a message at the end saying 'django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")' Is there any good solution for this problem? I have been searching for similar problems, but still haven't found a good solution yet. Please let me know if there is any other additional information needed. Thank you. -
Why does the deployment process return below error?
I am deploying my app on heroku, my connection string in setting.py is as per below.the dependencies in the requirement.txt have been deployed successfully. #################################################################### #################################################################### #################################################################### ########################################################################## import dj_database_url ####not working for my case DATABASES = { 'default': dj_database_url.config( default=os.environ.get('DATABASE_URL') ) } Please see error I got after deployment attempt ,any help would be welcome. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/urls/resolvers.py", line … -
I want to apply a version control system that applies only to text to my web [on hold]
When the text file is modified, a record is made. You can go back and be comparable . I want to implement the following. Do you have any reference or library that already exists? -
Django customizing blog eed
How do I conditonally add <wfw:commentRss> to each item in my django blog feed conditionally? (you can choose to enable / disable comments per post) I see there is an item template option on the syndication class but am not sure if this is the proper way to use it. I know you can add root elements etc from te syndication classes methods but these are the root (<channel>) and there are only a limited set of item fields that are allowed to be overridden. -
Errors with password change form
I created a form to change the users password; however, the form is not retrieving the user properly, nor is it changing the password. I am trying to confirm that a user put in their current password in "old_password", and then change their current password to a new one called "password". I have tried using the Django PasswordChangeForm, but it does not seem to work with my custom user model. forms.py (my account module that creates the user) class RegisterForm(forms.ModelForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class' : 'form-control', 'placeholder' : 'Email', 'id' : 'email', 'required' : 'true'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'First name', 'id' : 'first-name', 'required' : 'true'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Last name', 'id' : 'last-name', 'required' : 'true'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'placeholder' : 'Password', 'id' : 'password', 'required' : 'true'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'placeholder' : 'Confirm password', 'id' : 'password2', 'required' : 'true'})) class Meta: model = User # what fields from that model you want fields = ('first_name', 'last_name', 'email', 'password', 'password2') def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("Email is taken") return email def clean_password2(self): # Check that the two password entries match password … -
How to make django-hosts subdomains redirect even when user is not logged in
I am using django-hosts to create user subdomains, e.g sally.website.com will redirect to sally's profile. I understand how to do that if sally is logged in but let's say a random user john tries to access sally's profile at sally.website.com, how would I make this work with django-hosts? Kind of like how whether you are logged in or not if you go to facebook.com/sally it will return sally's page. I included the views.py and hosts.py to help clarify things. The users created url is stored in the dashboard views as url. So what I want to do is make that url returns sally's profile regardless of her login status. hosts.py: from django.conf import settings from django_hosts import patterns, host from main import views host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), # <-- The `name` we used to in the `DEFAULT_HOST` setting host(r'', 'path.to.custom_urls', name='wildcard'), ) views.py: def dashboard(request): if request.user.is_authenticated == True: name = request.user.first_name name2= name[0].upper() + name[1:] if request.method == "POST": choosestorename = request.POST.get("choosestorename").lower() preurl = request.user.username.split("@")[0] baseurl = request.META.get('HTTP_HOST').lower() url = choosestorename+ "." + preurl + "." + baseurl request.session[url] = url print(url) return render(request, 'main/dashboard.html', {'name2':name2}) elif request.user.is_authenticated == False: return redirect('home') else: return redirect('home') -
ImportError of mixins for Django 1.8 in Cygwin64
I'm trying to setup a remote repository locally on my computer. The road has been bumpy, and now I'm stuck here with this error message: from django.contrib.auth import mixins ImportError: cannot import name mixins The error does not appear until I runserver and write the url in a browser. Based on answers of previous questions, I had installed the following: Django==1.11.18 django-filer==1.4.4 django-picklefield==2.0 django-polymorphic==2.0 And I think they solved the problem, but the project which I'm working on uses Django 1.8 , and when I install the versions of these that are compatible with Django 1.8, the mixins error comes back. I'm using Cygwin (64-bit). -
On button click add data from model to a new form
I'm new to stackoverflow and django so sorry if this isn't descriptive enough. models.py file from django.db import models # Create your models here. SPORTS_CHOICES = ( ('nfl', 'NFL'), ('nba', 'NBA'), ('mlb', 'MLB'), ) class Event(models.Model): sports = models.CharField(max_length=3, choices=SPORTS_CHOICES, default='nfl') event_name = models.CharField(max_length=100, default='') home_team = models.CharField(max_length=100) away_team = models.CharField(max_length=100) home_team_moneyline_odds = models.DecimalField(max_digits=3,decimal_places=2) away_team_moneyline_odds = models.DecimalField(max_digits=3, decimal_places=2) home_team_spread = models.CharField(max_length=100) home_team_spread_odds = models.DecimalField(max_digits=3, decimal_places=2) away_team_spread = models.CharField(max_length=100) away_team_spread_odds = models.DecimalField(max_digits=3, decimal_places=2) total_points_over = models.CharField(max_length=100) total_points_over_odds = models.DecimalField(max_digits=3, decimal_places=2) total_points_under = models.CharField(max_length=100) total_points_under_odds = models.DecimalField(max_digits=3, decimal_places=2) def __str__(self): return format(self.event_name) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Event # Create your views here. @login_required def sports(request): context = { 'events': Event.objects.all() } return render(request, 'sports/sports.html', context) sports.html {% extends "blog/base.html" %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm-8"> {% for event in events %} <table class="table table-light table-sm table-hover"> <tr class="thead-dark"> <th style="width: 31%">Teams</th> <th style="width: 23%">Spread</th> <th style="width: 23%">Win</th> <th style="width: 23%">Total</th> </tr> <tr> <th class="table-bordered">{{ event.home_team }}</th> <td class="table-bordered"><button class="removebuttonstyling">{{ event.home_team_spread }} ({{ event.home_team_spread_odds }})</button></td> <td class="table-bordered"><button class="removebuttonstyling">{{ event.home_team_moneyline_odds }}</button></td> <td class="table-bordered"><button class="removebuttonstyling"> O {{ event.total_points_over }} ({{ event.total_points_over_odds }})</button></td> </tr> <tr> <th class="table-bordered">{{ event.away_team }}</th> <td class="table-bordered"><button class="removebuttonstyling">{{ event.away_team_spread … -
How to convert video and output to BytesIO without saving?
Using ffmpy to convert video(or gif image) that uploaded. I want to convert the file without saving (i.e. input is a BytesIO, and output with a BytesIO). How can I do that? -
Django Rest Framework ViewSet filtering issue based on forsignkey User field
I have a django project that I am working on. There are two models in this project. There is a user and account model. I am integreating the django rest framework viewsets. I will include them below. I am now integrating the Django Rest Framework in the project. I am trying to digure out how to do two things. 2 models: Default django user Account Model: class Account(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) _id = models.CharField(max_length=45) name = models.CharField(max_length=140) balance = models.DecimalField(max_digits=100, decimal_places=2) currency = models.CharField(max_length=12) bank_name = models.CharField(max_length=120) routing = models.CharField(max_length=8) _class = models.CharField(max_length=22) type = models.CharField(max_length=22) active = models.BooleanField(default=True) main = models.BooleanField(default=False) synapse = models.BooleanField(default=False) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username + ' - ' + self.name + ': ' + str(self.balance) 1 => I want to be able to type in the endpoint /api/users/accounts/omarjandlai and grab the single or many acounts with the omarjandali user foreignkey 2 => I want to be able to type into the following api/users/accounts/ and return all of the accounts that are in the database I tried 4 - 5 different ways to get this to work and I couldnt get it to work. Here are my serializers and views serializers: class … -
Getting user's old image if no image is selected
I have a form that takes in user data like bio, profile picture, gender, etc. and upon submission either creates this new row about the user or updates the existing row. This will only work if the user uploads an image. If no image is uploaded for the profile picture, then the form doesn't submit. How can I make it so that if the user didn't upload a profile picture, then it'll keep the user's previous profile picture and still submit? Here's my code: class ProfileSettings(UpdateView): model = Profile template_name = 'blog/settings.html' form_class = ProfileForm success_url = reverse_lazy('blog:settings') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): bio = form.cleaned_data['bio'] gender = form.cleaned_data['gender'] avatar = form.cleaned_data['avatar'] Profile.objects.update_or_create(user=self.request.user, defaults={'avatar':avatar, 'bio':bio, 'gender':gender}) return HttpResponseRedirect(self.success_url) -
Annotate but with non-Django supplied values
Is there any way to append a non-Django supplied value to a query? For instance, to find out if a store closed, I may run a function called get_closed_stores() which returns a list of closed stores. Stores Closed [00090, 00240, 00306, 00438, 03005, 05524] Great, now we have store numbers for stores that are closed. Lets get those actual store objects. Query Store.objects.filter( store_number__in=[00090, 00240, 00306, 00438, 03005, 05524] ) We now have the QuerySet, but we have absolutely no way to detect when the store closed, because the database doesn't contain any information about emergency closings, but Sharepoint does. So back at get_closed_stores() we can return the Date Closed alongside the store number so our Closed Stores List (dictionary) would look more like below: Store List with Dates { [00090, '1/28/19 5:00PM'], [00240,'1/28/19 5:00PM'], [00306, '1/28/19 5:00PM'], [00438,'1/28/19 5:00PM'], [03005,'1/28/19 5:00PM'], [05524, '1/28/19 5:00PM'] } Now that the dates are with my store numbers, I can add this to my Queryset (ideally) and access it from my front end. So annotate() would be ideal here if I were working with anything Django ORM related, but when it comes to "injecting" external data, what is it I'm looking for?