Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why do I get 'ImproperlyConfigured' exception, implying circular imports?
I have had this issue before, but I've managed to find the circular import being referenced. I face it again, but I can't find the problem. My project's name is 'sare', and my sare/urls.py looks like this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('users/', include('users.urls', namespace='users')), path('admin/', admin.site.urls), ] And users/urls.py is this: from django.urls import path from .views import UsersTableView, UserCreateView, UserUpdateView, UserDeleteView app_name = 'users' urlpatterns = [ path('table/', UsersTableView.as_view(), name='users_table'), # path('create/', UserCreateView.as_view(), name='users_create'), # path('update/<int:pk>', UserUpdateView.as_view(), name='users_update'), # path('delete/<int:pk>', UserDeleteView.as_view(), name='users_delete'), ] The only piece of code that is not commented in my views is the UsersTableView, that looks like this: from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import CustomUser from .tables import UsersTable from .filters import UserFilter from .form_helpers import UsersFilterFormHelper from django.views.generic import CreateView, UpdateView, DeleteView from .forms import UserForm from django.urls import reverse_lazy, reverse from django_tables2.export import ExportMixin from django_tables2 import RequestConfig,SingleTableView,Table as TableBase from django_filters import FilterSet class InitUserMixin(object): def __init__(self, *args, **kwargs): self.user = kwargs.pop("user", None) super(InitUserMixin, self).__init__(*args, **kwargs) class FilterUserMixin(InitUserMixin, FilterSet): pass class Table(InitUserMixin, TableBase): pass class PagedFilteredTableView(ExportMixin, SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, … -
Django: How to handle error message in CreateView for UNIQUE constraint failed
I have a generic class based createview, which generates "UNIQUE constraint failed" error. I am able to handle this and redirect it to the same createview form. However i need to send an error msg to the createview saying 'Name already exists'. How to i achieve this. view.py class FeatureCreate(CreateView): model = Feature fields = ['name', 'summary'] def form_valid(self, form): form.instance.release_id = self.kwargs.get('pk') from django.db import IntegrityError from django.http import HttpResponseRedirect try: a = super(FeatureCreate, self).form_valid(form) except IntegrityError as e: if 'UNIQUE constraint failed' in e.args[0]: return HttpResponseRedirect(reverse_lazy('feature-create', args=(form.instance.release_id,))) return a url.py: path('release/<int:pk>/feature/create/', views.FeatureCreate.as_view(), name='feature-create'), feature_form.html: {% block content %} <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> <input type="button" value="Cancel" onclick="history.back()"> </form> {% endblock %} Any suggestions is welcome. Please help. -
Django DurationField format options
Good evening. I have a question do you have some snippet for DurationField to show it in django admin in format HH:MM? I can't find anything over the internet and 3rd party apps doesn't work in new django. Thank you for help. Model: from django.db import models # Create your models here. class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.DateTimeField(help_text = "test", null = True) #current hours ch = models.TimeField(help_text = "test", null = True) #rm = models.IntegerField(help_text = "test", null = True) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) def __str__(self): return self.registration -
Django Api KeyError in a login
Good evening, I am doing a login with vue. mysql and django. Everything is correct in the registry. But in the login using the sessions I receive an error from KeyError. To set the session use: request.session['u'] = data['username'] And to receive it: (when I get the error) mySession = request.session['u'] return HttpResponse(mySession) Does anyone have any ideas? -
How to program and visualize N-ary tree in Python
How to program and visualize N-ary tree in Python I have a basic understanding of Python but ran into a problem that I consider can be solved with that programming language. The problem is the following: there are a series of activities that are carried out throughout the day and there are some that depend on others. I make mention that I was doing a little research on linked lists but I did not find an answer to connect a node on its left side with two nodes at the same time and viceversa. Continuing with the mission I have, there are approximately 953 processes. We were told that an activity was going to stop one of those processes and we needed to find out which of the processes that depended on it would be affected. The process configuration files are designed as follows (run.conf file) run.conf DEPENDENCIES = (if you have them) EXECUTE = /sources/run.sh Where /sources/run.sh is executed once the previous processes that are in DEPENDENCIES are successfully concluded (if it has dependencies) Here I will graph an example of the conf file. Then I show you what I have done so far and what I would like … -
Django Foreign key relationship not saving
I have a model class Messages(models.Model): from_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="from_user_messages") to_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="to_user_messages") subject = models.CharField(max_length=50, null=True) content = models.TextField(max_length=200, null=True) read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.from_user} to {self.to_user}" Form class MessagesForm(forms.ModelForm): class Meta: model = Messages fields = ['subject', 'content'] labels = { "content": 'Message' } view def profile(request, slug) profile = Profile.objects.get(slug=slug) usr = profile.user logged_usr = request.user if request.method == 'POST': form = MessagesForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.from_user = logged_usr message.to_user = usr message.save() messages.success(request, "Message Sent") return HttpResponseRedirect(reverse('profile', args=(), kwargs={'slug': slug})) else: form = MessagesForm() return render(request, 'users/profile.html', context) This does not throw any error, but it does not save to database. I tried doing this same thing on the django shell, and it saved without errors. Is there something I'm missing? -
Why is my Django, jQuery, Ajax like button liking all posts?
I am attempting to make a twitter like social media feed in a Django ListView and have added an Ajax like button from the Django 3 By Example book. The like feature works perfectly in the DetailView but I cannot get it to work in the ListView. When hitting the like button in the DetailView it likes all of the posts on the page and will show 1 like, then 11110 likes, then goes up exponentially from there. The toggling of like/unlike is correct but does not reduce the count by 1; it just keeps going up. Please help! Models.py: class Post(models.Model): content = models.TextField(max_length=150, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(storage=PrivateMediaStorage(), upload_to = pics_path, blank=True, null=True) vid = models.FileField(storage=PrivateMediaStorage(), upload_to = vids_path, blank=True, null=True) users_like = models.ManyToManyField(User, related_name='posts_liked', blank=True) -
Django Rest Framework unique together validation with field absent from request
I'm implementing some voting functionality in an application, where a logged-in user specifies a post that they would like to vote for using a payload like this: { "post": 1, "value": 1 } As you can tell, the a user field is absent - this is because it gets set in my viewset's perform_create method. I've done this to ensure the vote's user gets set server side. This is what the viewset looks like: class CreateVoteView(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = VoteSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) Here is what the model looks like: class Vote(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='votes', null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='votes', null=False) class Values(models.IntegerChoices): UP = 1, _('Up') DOWN = -1, _('Down') value = models.IntegerField(choices=Values.choices, null=False) class Meta: unique_together = ('post', 'user') and finally, the serializer: class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = ['post', 'value'] From what I understand, in order for DRF to enforce a unique together validation, both fields (in my case, user and post) must be included in the serializer's fields. As I've mentioned, I'd like to avoid this. Is there any other way of implementing this type of validation logic? -
Django returning Json dictionary instead of html page
I am trying to build a system where users can like a comment in a post. so far the functionality works except that when users click on like instead of staying on the page and only updating the DOM elements it return a Json dictionary such as { 'comment_like_count' : 0 } my intention is to simply update the DOM on the same page without going to the URL. Meaning if a user likes a comment on a post_detail page it simply changes the number of likes for that comment on the same page without going to the comment-like url. So far my view and JS functions are: comment_like view: @login_required def comment_like(request,id): comment = get_object_or_404(Comment, id=id) user = request.user if request.method == 'POST': if comment.likes.filter(id=user.id).exists(): comment.likes.remove(user) else: comment.likes.add(user) return JsonResponse(data) my js function: $(document).ready(function (e) { $('.comment-like-form').on("click", ".comment-like-button", function (e) { var like_count = parseInt($(".comment-like-count", this).text()); e.preventDefault(); if($(this).find("span .u").hasClass("text-danger")){ like_count--; $(".comment-input-like-count", this).val(like_count); $("span .u", this).removeClass("text-danger") $(".comment-like-count", this).text(like_count); } else { like_count++; $(".comment-input-like-count", this).val(like_count); $("span .u", this).addClass("text-danger") $(".comment-like-count", this).text(like_count); } $.ajax({ type:"POST", dataType: 'json', url: $(this).closest("form").attr("action"), headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: $(this).closest("form").serialize(), success: function (data) { event.preventDefault(); if($(this).find("span .u").hasClass("text-danger")){ like_count--; $(".comment-input-like-count", this).val(like_count); $("span .u", this).removeClass("text-danger") $(".comment-like-count", this).text(like_count); } else … -
CheckboxInput always displaying as True
I have a BooleanField on my database and am wanting to display it to the user as a CheckboxInput, but the value displayed to the user is always Yes(True). The value updates correctly in my database and diplays correctly in my admin panel. model graduated = models.NullBooleanField() form graduated = forms.NullBooleanField(label='Have you graduated?', required=False, widget=forms.CheckboxInput(attrs={'checked data-toggle':'toggle', 'data-on':'Yes', 'data-off':'No'})) Thank you. -
why overwriting the init function of forms makes form fields return none
hey Im new to django and i need help i have a form that has two fields one of them is a choicefield and the choices attribute gets its data from views but the problem is when i call the form both fields return none here is my forms.py class AddToCardForm(forms.Form): quantity = forms.CharField(required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', 'type': 'text', 'name': 'quantity', 'value': "1", 'size': "2", 'id': "input-quantity", })) color = forms.ChoiceField(widget=forms.Select(attrs={ 'name': "color", 'class': "form-control", }), required=True,) def __init__(self, user, *args, **kwargs): my_arg = kwargs.pop('choices', None) super(AddToCardForm, self).__init__(*args, **kwargs) self.fields['color'].widget.choices = my_arg and here is my views.py def ItemDetail(request, slug): item = get_object_or_404(models.Item, slug=slug) template_name = "core/test.html" li = [] for i in item.color.all(): tu = (i.color_name, i.get_color_name_display()) li.append(tu) form = forms.AddToCardForm(request.POST or None, choices=li) # context = { 'object': item, 'form': form } if request.method == 'POST': print(form['color'].value()) print(form['quantity'].value()) if form.is_valid(): color = form.cleaned_data.get('color') print(color) quantity = form.cleaned_data.get('quantity') print(quantity) add_to_cart_quantity(request, slug, int(quantity), color) else: print('form invalid') print(form.errors) return render(request, template_name, context) html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST">{% csrf_token %} {{ form.as_p }} <button type="submit">submit</button> </form> </body> </html> when i set the choices attribute in form with static data everything works fine … -
How to reference a foreign key in a Django template that references another foreign key
I am trying to reference a foreign key named data_source in ProtocolUserCredentials in my html template. When I run this it just comes up with a blank header for each cred object in creds, and not the username and password. Running if cred.data_source.name == ... doesn't work and if protocoldatasource__data_source.name == ... doesn't work as well. If I run a non-foreign key in the conditional similar to if cred.data_source_username, and then the password in the if <h4> username: {{ cred.data_source_password }} </h4>, it'll display with no error. ProtocolUserCredentials references a foreign key named data_source from ProtocolDataSource, and ProtocolDataSource references a foreign key named data_source from DataSource. Im wondering if there is a way to reference a foreign key from a foreign key in Django? <div class="container" style="border:1px solid #cecece;"> {% for cred in creds %} <div class="jumbotron jumbotron-fluid"> <div class="container"> {% if cred.data_source.name == 'Demonstration Protocol, External Identifiers, demo_exrecs' %} <h4> username: {{ cred.data_source_username }} </h4> <h4> password: {{ cred.data_source_password }} </h4> {% endif %} </div> </div> {% endfor %} </div> {% endblock %} def post(self, request): post_data = request.POST self.user = post_data['user'] self.protocol_user = post_data['protocol_user'] self.protocol = post_data['protocol'] self.data_source = post_data['data_source'] self.data_source_username = post_data['data_source_username'] self.data_source_password = post_data['data_source_password'] context = … -
Postgres database of a cloned project not showing up when I run psql
I was under the assumption that Django's models would automatically create the database when I ran migrations, however, I cannot find the database listed in psql despite the fact that the project runs perfectly with all the database info populating the website. I don't exactly know what to look for in the settings.py file to see where the database is actually being stored but is there any way to find out? -
DRF: multiple permissions in a viewset
I have a viewset to retrieve information about users. Requesting '.../users/' with get method results in displaying list of all users. It has to be accessible only for users whose role is 'admin'. Same if address '.../users/{username}/' is accessed. But if someone calls '.../users/me/' he should retrieve an information about his own profile. Thus I need 2 different permissions for a single viewset. I have my own permission (has_permissions) which works to prohibit regular users viewing user list but since has_object_permissions will not be executed unless request passes has_permissions, it is not working properly. I tried to verify request in get_queryset method but despite technically it works, the result is not what I am looking for. Here is my view: class UsersViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UsersSerializer permission_classes = [permissions.IsAuthenticated, IsAdminOrProhibited] lookup_field = 'username' lookup_url_kwarg = 'username' def get_object(self): if self.kwargs['username'] == 'me': obj = User.objects.get(id=self.request.user.id) return obj obj = User.objects.get(username = self.kwargs['username']) return obj What should I do in order to achieve this? Thanks for any help. -
ISSUE: How to show an object (child) inside another (parent) in a many to one relationship (FK)? Django REST framework
I am working on a mini order dispatching system (e.g. Uber Eats) and I would like to show the object OrderItem inside the object Order. As you see, Order is a FK in the OrderItem model. I've tried inserting serializers.RelatedField(), also OrderItemModelSerializer() in the orders/serializers/orders.py without success. For sure I am doing something wrong. This is the Order list, there is no the OrderItem object inside it :( [ { "id": 3, "user": 1, "customer": 1, "store": 2, "paid": true, "ordered": false, "picked_up": false, "deliveried": false, "created": "2020-04-29T21:57:07.671934Z", "updated": "2020-04-29T21:57:07.671996Z" }, { "id": 1, "user": 1, "customer": 1, "store": 2, "paid": true, "ordered": false, "picked_up": false, "deliveried": false, "created": "2020-04-29T18:43:56.394898Z", "updated": "2020-04-29T18:43:56.394943Z" } How would you tackle this issue? The code is shown bellow: orders/models/orders.py class Order(models.Model): '''Orders models.''' user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) paid = models.BooleanField(default=True) # not added payments yet # Status ordered= models.BooleanField( 'Order made', default=False, help_text='Set True when the Customer wants the order to be delivered.' ) picked_up = models.BooleanField( 'picked up by the rider', default=False, help_text='Set True when the rider has picked up the order on the Store.' ) deliveried = models.BooleanField( 'deliveried to customer', default=False, help_text='Set True … -
Generate JWT token in Django view on form submit without DRF
I would like to know how can I generate a JWT token in django based on some fields which I get from a form submit in the view. This toke is not used authentication in django but I need to pass this token back in response which will then be sent to another service using JavaScript. I am not using DRF currently. The flow will be something like FrontEnd -> Form submit -> Django Backend generate JWT -> Send back to FrontEnd in response Again this is not for authentication on django. If someone can point me to a working example that will definitely help me out. Regards, M. -
How to handle errors in django views?
I have a view to log in and when the user does not exist it throws me an error, I would like this error to be printed in the template, saying that the user does not exist, try this way but it does not work for me. Would there be any other way to make it work? View def login_rfid(request): ''' Login ''' if request.method == 'POST': username = '' if 'username' in request.POST: print("sasrfwrfsrsf") rfid = request.POST['username'] user = User.objects.get(rfid=rfid) if user is not None: user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect('/') else: messages.error(request, 'The user does not exist') return render(request, "registration/login_rfid.html") HTML {% if messages %} <div class="span12"> {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message|safe }} </div> {% endfor %} </div> {% endif %} ERROR -
Django - display the right variable
My Goal: If the user has score > 1 display only the jobs that have the correlated category. So, if category.1 (name of the quiz) is DataScience, shows only the jobs that are about Data Science. What my result is: If the score > 1 it displays all the job offers present on the database. (as in picture) What am I doing wrong? Any suggestions? quiz/models.py from django.contrib.auth.models import User from django.db import models # Create your models here. class Questions(models.Model): CAT_CHOICES = ( ('datascience', 'DataScience'), ('productowner', 'ProductOwner'), ('businessanalyst', 'BusinessAnalyst'), #('sports','Sports'), #('movies','Movies'), #('maths','Maths'), #('generalknowledge','GeneralKnowledge'), ) question = models.CharField(max_length = 250) optiona = models.CharField(max_length = 100) optionb = models.CharField(max_length = 100) optionc = models.CharField(max_length = 100) optiond = models.CharField(max_length = 100) answer = models.CharField(max_length = 100) catagory = models.CharField(max_length=20, choices = CAT_CHOICES) student = models.ManyToManyField(User) class Meta: ordering = ('-catagory',) def __str__(self): return self.question quiz/views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render from .models import Questions from .decorators import allowed_user # Create your views here. @allowed_user(allowed_roles=['Admin','Students']) def quiz(request): choices = Questions.CAT_CHOICES print(choices) return render(request, 'quiz/quiz.html', {'choices':choices}) def questions(request , choice): print(choice) ques = Questions.objects.filter(catagory__exact = choice) return render(request, 'quiz/questions.html', {'ques':ques}) def result(request): print("result page") if … -
Not able to connect to postgresql in production, using AWS RDS
my django app, when I ran it locally(localhost + sqlite3) or in production(public Postgres RDS) on port 8000, it works perfectly. As ports below 1024 are not accessible without root permissions, hence to run on port 80 I used: sudo python3 manage.py runserver and got the following error : OperationalError at / could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I am using it from the same region EC2 instance. I was able to make migrations and migrate it over the same RDS Postgres database. I also tried running on port 80 with gunicorn and root privileges but the same error. Here is my production settings.py file : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SKEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_skeleton', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Can't Import psycopg2._psycopg Inside a docker
I am trying to build a docker image with the following requirement.txt file but when I call my python function, there is a part that calls to a redshift database to perform query and ectract data, then I get an error : ImportError: /usr/local/lib/python2.7/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference python-dateutil==2.6.0 numpy==1.12.0 jsonschema==2.6.0 pandas==0.20.3 python-consul==0.7.2 boto==2.49.0 datadog==0.15.0 invoke==1.4.1 SQLAlchemy==1.1.5 graypy==0.2.14 llvmlite==0.31.0 fastparquet==0.2.1 simple-salesforce==0.74.2 pytz==2019.1 psycopg2==2.7.1 My docker file is : FROM python:2.7 ENV COLLECTION aa ENV TASK_PARAMS aa RUN apt-get update -y && \ apt-get install -y python-pip python-dev WORKDIR /opt/airflow_repository ADD analytics ./analytics ADD FrameworkPY ./FrameworkPY COPY requirements.txt requirements.txt ENV PYTHONPATH ${PYTHONPATH}:/opt/airflow_repository/similarweb_analytics ENV INI_ENVIRONMENT_SETTINGS_PATH=/etc/ RUN pip install -r requirements.txt CMD invoke -c $COLLECTION mainrun $TASK_PARAMS after building the docker image I am trying to run a python script that read data from my redshift : Using the following cmd : docker run -it -e COLLECTION=/opt/airflow_repository/ods/sf/sf_to_ods -e TASK_PARAMS="--job-type /opt/airflow_repository/ods/sf/configs/sf_contact_delta.json" airflow_bidev i get the following error traceback : pid 6 - 2020-04-29 20:34:27,083 - INFO - sf_to_ods.py - run - line 60 - starting sf_to_ods Setting value pid 6 - 2020-04-29 20:34:27,087 - INFO - consul_connections.py - get_connection_settings - line 15 - retreving general_settings … -
Django: How to Make Decision Based on Tuple Choices
Please I want to know how to show another input based on someone's choice. Take the Django form code below for instance. Staff_or_Student = forms.ChoiceField(choices=(('Staff','Staff'), ('Student', 'Student')), widget=forms.Select(attrs={'class':'form-control'}), required=True ) With this, I expect when a user picks Staff, then s/he should see a form to input staff_id i.e Staff_ID = forms.CharField( label='Staff ID', max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter ID'}), required=True, ) but matriculation number if the student is chosen. Matriculation_Number = forms.CharField( label='Matriculation Number', max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Matric Number'}), required=True, ) Please how can I achieve this? -
Django. I need data in my "first" model from my "third" model. Does it mean that I made a mistake or it is doable?
I would like to kindly ask you for your help. I need data from my third model in my first model. And I am struggling right now with it. Can I fix it as it is or I will have to rebuild my code ? Maybe first I will show you what I got. models.py: from django.db import models from django.contrib.auth.models import User class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.question class Answer(models.Model): question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) answer = models.TextField(max_length=1000) created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.answer class VoteQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) votesubmitted = models.DateTimeField(null=True, blank=True) votesscore = models.IntegerField(default='0') amountofvotes = models.IntegerField(default='0') class Meta: unique_together = ['user', 'question'] And in my views.py I am doing this: def home(request): allquestionswithanswers = Question.objects.filter(datecompleted__isnull=False) allquestionswithoutanswers = Question.objects.filter(datecompleted__isnull=True) return render(request, 'main/home.html', {'allquestionswithanswers': allquestionswithanswers, 'allquestionswithoutanswers': allquestionswithoutanswers}) And that's because in home.html I want to call this: <ul> {% for question in allquestionswithanswers %} <li> {{ question }} Score: {{ question.votesscore }} {{ question.user }}<br><br> <form class='my-ajax-form' method='POST' action='' data-url="{% url 'questionvoteup' question.id %}" > {% csrf_token %} … -
is it possible for a fileField t save a url in django
I am working and using dj-rest-auth and Django-allauth on a project where the user has a profile photo field in his user model. This field has a one to one relationship with another model that has a file field. It is a file field because the user should be able to add images and gifs as his profile photo. The problem is that when the user signs up using google the profile photo is gotten from google, which is a URL. How can I go around this? my photo model class Photo(models.Model): ''' This model will be a general model for files upload to amazon ''' url = models.FileField() def __str__(self): return self.url class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) display_picture = models.OneToOneField(Photo, on_delete=models.CASCADE, related_name='dp', blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) -
Not able to install the latest django in virtualenv
Hello I am trying to install latest version of django in my virtualenv through the following command. pip install Django==3.0.5 for which I got an output as below ERROR: Could not find a version that satisfies the requirement Django==3.0.5 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1,1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3,1.3.4, 1.3.5, 1.3.6,1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, … -
Node (npx one time run) and Django talking to each other
How can this be done? Use case is say I have some assets to be generated from an image upload. Note I don't mean compressed - like django-compressor etc does. I literally mean new assets from an uploaded one. Typically, you could run a process offload it to celery ping task status for progress and have a display if it was all Django / data stuff. But, for this I have no idea. You have to get django + npx command talking to each other, need progress, a preview of the image returned once done, etc. There's subprocesses where I can do subprocess.run(my npm command). But, this is still missing the "talking" portion and watching the generated assets / progress status. If I can figure this out can do the rest. Just not sure where to start. No resources I could find on this. At a high level: Django request posts -> subprocess is called -> 200 returned -> subprocess calls npx one-off task in background -> ??? <-> django watches for this / displays.