Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django initial_forms.is_valid() returns false
My goal is to edit/update existing data. I am able to display existing data and add new data but not edit data. My model are Recipe and Ingredient. I am using modelformset_factory to add ingredients to recipe. Here is the forms.py: class RecipeModelForm(forms.ModelForm): class Meta: model = Recipe fields = ('name', ) labels = { 'name': 'Recipe Name' } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Recipe Name here' } ) } IngredientFormset = modelformset_factory( Ingredient, fields=('name', 'amount', 'unit'), labels={ 'name': 'Ingredient Name', 'amount': 'Amount', 'unit': 'Unit' }, extra=1, widgets={ 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Ingredient Name here' } ), 'amount': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Amount here' } ), 'unit': forms.Select( attrs={ 'class': 'form-control', 'placeholder': 'Enter Unit here' } ) }, can_delete=True ) views.py: @login_required def update_recipe(request, pk): template_name = 'recipe/create_with_ingredients.html' # template_name = 'recipe/update.html' recipe = Recipe.objects.get(id=pk, author=request.user) ingredients = Ingredient.objects.filter(recipe=recipe) if request.method == 'GET': recipeform = RecipeModelForm(instance=recipe) formset = IngredientFormset(queryset=ingredients) elif request.method == 'POST': recipeform = RecipeModelForm(request.POST, instance=recipe) formset = IngredientFormset(request.POST, queryset=ingredients) if recipeform.is_valid(): # and formset.is_valid(): recipe = recipeform.save(commit=False) recipe.author = request.user recipe.save() for form in formset.initial_forms: print(form.is_valid()) if form.is_valid(): data = form.cleaned_data for form in formset: if form.is_valid(): data = … -
CheckConstraint constantly throwing a FieldError
So I've been struggling with trying to implement a Following-system in my project. Something similar to how the Twitter following system works. I've looked around and come across a few ideas. Right now my models.py in it's entirety looks like this: models.py from django.contrib.auth.models import AbstractUser from django.db.models.fields import DateTimeField from django.utils import timezone from django.db import models # pylint: disable=no-member class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friend = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) class Post(models.Model): creator = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post_creator") content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) def serialize(self): return { "id": self.id, "creator": self.creator.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } The problem is right now, as is, a user can follow themselves which I do not want. So of course I tried to use CheckConstraint by adding a class Meta to my Profile model so it looks like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friend = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('friend')), name="user_cannot_be_following_themselves"), ] This keeps producing this error django.core.exceptions.FieldError: Cannot resolve keyword 'friend' into field. Choices are: id, user, user_id everytime I try to migrate the changes (after makemigrations). Even when … -
Writing a view to fetch user data and add it to the database
I make a project which generates a random book when the user press a button. The view that does that is: def random_book(request): cartile=Books.objects.all() random_item=random.choice(cartile) return render(request, 'carti/book.html', context={"random_item": random_item}) On the page were you are redirected to see the generated random book I want to add a button that says "add to read later". I know how to make a manyotmany relationship between profile model and books model, but I have no idea how to write a view that gets the generated random book, adds it to the profile view_later field in the database, delete it with another button, what html tag and what should I write inside for "add to read later" and the delete button. Some help would be appreciated! -
Django | AWS: How to get username?
I've deployed my django project on aws ec2-instance and I want to know the users system login username. My Django project doesn't have signin system. I know in python you can get system login username from getpass.getuser() But as I said that my project is hosted on ec-instance, hence when I use getpass.getuser() I am getting username as ec2-user Is it possible to get user's system username if project is hosted on ec2-instance. -
Django None Type object is not callable
I want to create an own usermodel, so I can login with email instead of using the username. For this I used this tutorial: https://testdriven.io/blog/django-custom-user-model/ I used the AbstractBaseUser. I also changed the model a bit, so I have some other fields. The problem is, that when I send the request I get an error: TypeError at / 'NoneType' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: TypeError Exception Value: 'NoneType' object is not callable Exception Location: ...\managers.py, line 18, in create_user Python Executable: ...\venv\Scripts\python.exe Python Version: 3.8.5 Traceback Switch to copy-and-paste view ...\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … :arrow_forward: Local vars ...\venv\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, callback_kwargs) … :arrow_forward: Local vars ...\views.py, line 7, in index user_creator.create_user(request.POST['email'], request.POST['username'], request.POST['displayname'], … :arrow_forward: Local vars ...\managers.py, line 18, in create_user user = self.model(email=email, user_name=user_name, display_name=display_name, extra_fields) I think the problem is, that it doesn't know what the self.model in the manager.py at line 11 should be. Here is my code: my views.py from django.shortcuts import render from .managers import CustomUserManager def index(request): if request.method == 'POST': user_creator = CustomUserManager() user_creator.create_user(request.POST['email'], request.POST['username'], request.POST['displayname'], request.POST['password1'], request.POST['password2']) return render(request=request, template_name='index.html') … -
why does my logger not inherit handlers from root logger
I have followed advice from django docs and other SO questions about how to configure logs in a django project. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s.%(msecs)03d [%(levelname)s:%(name)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', 'level': 'INFO', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } portfolio/models.py: logger = logging.getLogger(__name__) def testfunc(): print(logger) print(logger.handlers) when i run testfunc i get the following output: >>> testfunc() <Logger portfolio.models (INFO)> [] however if i add a logger explicitly to my config like so: 'root': { 'handlers': ['console'], 'level': 'INFO', }, 'loggers': { 'portfolio.models': { 'handlers': ['console'], 'level': 'INFO', }, } then the handler is picked up by the logger: >>> testfunc() <Logger portfolio.models (INFO)> [<StreamHandler <stderr> (INFO)>] I have also tried creating a 'catch-all' logger like based on another SO answer: 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', }, } but this didn't work. Any ideas why i can't get my logger to inherit from the root logger? -
How To Pass Value of Select Box as Foreign Key (Django)
Hi I am working on a Django web app - I have a select box which holds all objects from a particular model. The select box is created in the template, it is not a part of the form directly. When I submit, I am able to access the value selected by the user, but when I try to use the value as part of a queryset it does not return the expected values. models.py class TaskGroup(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class TaskGroupDetail(models.Model): taskGroup = models.ForeignKey(TaskGroup, null=True, blank=True) taskType = models.ForeignKey(TaskType, null=False, blank=False) views.py def CreateShipmentView(request): if request.method == 'POST': shipment_form = CreateShipmentForm(request.POST) if shipment_form.is_valid(): new_shipment = shipment_form.save() group = request.POST.get('groups') #get the task group selected print(group) #this returns the expected value ..... #if a task group was added, create the tasks groupDetails = TaskGroupDetail.objects.get(taskGroup = group) #this returns a blank queryset print(groupDetails) #this returns a blank queryset return redirect('ShipmentListView') ... else: shipmentForm = CreateShipmentForm() groups = TaskGroup.objects.all() context = { 'shipmentForm': shipmentForm, 'groups': groups, } return render(request, 'create-shipment.html', context) create-shipment.html <form class="well contact-form" method="POST" action="{% url 'CreateShipmentView' %}"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> {% for error in form.Reference_Number.errors %} <P class='error'>{{ error … -
Django client tests requests wrong path
I am building django REST app with mixins: ModelViewSet(mixins.RetrieveModelMixin, mixins.CreateModelMixin) queryset = Model.objects.all() (...) and retrieve() is visible in localhost:8000/model/<uuid> Then I add a function for counting all Model instances: @action(detail=False, methods=["GET"], url_path="count") def get_model_count(self, request): queryset = self.get_queryset() data = {"count": queryset.count()} return Response(status=status.HTTP_200_OK, data=data) Then when I try to test it: def test_model_count(self): list_size = 10 for i in range(list_size): response = self.create_model() self.assertEqual(response.status_code, 200, response.content) response = self.client.get(reverse("model-get-model-count")) self.assertEqual(response.status_code, 200, response.content) I get this error: AssertionError: 400 != 200 : b"Invalid parameter robot_id value: 'all' is not a 'uuid'" Interesting part is that when I use web or curl, everything works fine, I can get count correctly, I can get model details, I can create new model. I tried changing the order, so count is implemented first, before retrieve but the error still exists. Hope I provided enough of information, thanks in advance -
Cannot resolve keyword 'user_following' into field. Choices are: id, user, user_id
I have just added a new model 'Profile' to my models.py. I do not have any views.py or forms.py for this model. I am hoping that Profile will act as a kind of extension to my AbstractUser model that is why I have used a OneToOneField for Profile.user. Initially I created the model like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) user_following = models.ManyToManyField("User", symmetrical=False, related_name="following", blank=True) class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('user_following')), name="user_cannot_be_following_themselves"), ] @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except Profile.DoesNotExist: Profile.objects.create(user=instance) I did the usual manage.py makemigrations network and that was fine, it recognised my changes. I then went to migrate and got a traceback error ending with django.core.exceptions.FieldError: Cannot resolve keyword 'user_following' into field. Choices are: id, user, user_id. I assumed it had a problem with the name of the field 'user_following' so I changed it to 'following'. I then did makemigrations again and got this error: ERRORS: network.Profile.following: (fields.E302) Reverse accessor for 'Profile.following' clashes with field name 'Profile.following'. HINT: Rename field 'Profile.following', or add/change a related_name argument to the definition for field 'Profile.following'. network.Profile.following: (fields.E303) Reverse query name for 'Profile.following' clashes with field name 'Profile.following'. HINT: Rename field 'Profile.following', or add/change a … -
python-social-auth with custom django User model - custom user creation and sign in logic
I am using python-social-auth with Django 3.1 I want to allow social sign-in to a website using the following logic/scenarios: Scenario 1 Sign in with social login (user has not signed in before and email not present in db) generate a random username between 1 and 999999 create user in database and record email and other profile data Scenario 2 Sign in with social login (user has signed in before using this social provider) retrieve user from database (after authenticating with provider) Scenario 3 Sign in with social login (user has not signed in before with a different social provide BUT same email [i.e. user uses same email for more than one social provider]) fetch user with matching email and return Scenario 4 Create user from either admin console or command line Allow user to provide username (not auto-generated) Here is my code: user/models/customuser.py from socialengagement.models import SocialItem class CustomUser(SocialItem, AbstractUser): email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() # other fields continue ... managers.py from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from django.db import IntegrityError from django.db.transaction import TransactionManagementError class CustomUserManager(BaseUserManager): """ Custom user model manager … -
Video stream python
I am working on a video hosting platform and I wonder is there any python library to stream video files? Now I am using default models.FileField() to upload a video file and serializing it using Django Rest Framework. as a Frontend using React.js. -
How to display user's role in template
I made two custom groups from the django's admin page, 'free' and 'premium'. How do i display the group name on a template {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in. your account status is {{ }}</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %} -
I want to understand testing with unittest
I want to understand testing with unittest, with the help of this piece of code could you explain how it should be tested? ` class AddStarRating(View): """Добавление рейтинга фильму""" def get_client_ip(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def post(self, request): form = RatingForm(request.POST) if form.is_valid(): Rating.objects.update_or_create( ip=self.get_client_ip(request), movie_id=int(request.POST.get("movie")), defaults={'star_id': int(request.POST.get("star"))} ) return HttpResponse(status=201) else: return HttpResponse(status=400) ` -
Why request.GET.get('tag', '') returns C rather than C++ in django GET request?
This is my code in django template: {% for tag in tags %} <a href="{% url 'tag_find' %}?tag={{ tag }}" > {{ tag }}</a> {% endfor %} in view.py: def tag_find(request): page = request.GET.get('page', 1) tag = request.GET.get('tag', '') print('show_tag:', tag) ........ Some example are not working perfectly, like: When tag is C++ then request.GET.get() shows C, when returning tag from template is Portraits&Caricatures then request.GET.get() shows Portraits. I have no idea why request.GET() cuts some part of text. -
Approach to building asynchronous views in Django
I started learning Django about a month ago. I built an app that looks like this: 4 models class based views using Django built in views, a couple custom ones Django HTML templates for the front end with some JavaScript Yesterday I explored building in Ajax for the front end, but realized that gets messy pretty fast. I decided to build an api using Django rest framework. Now I’m faced with a decision and I’m looking for some advice. Build a front end app on Django using Django templates and Ajax templates Build a completely separate front end that uses react or vue Some other option that I’m unaware of -
Django Rest - testing api delete
Currrently I am testing my django rest api, but I am stuck on delete method. My url looks like this path('books/shelfs/<int:shelf>/readers/<int:pk>/', views.ReaderViewSet.as_view( {'get': 'retrieve', 'delete': 'destroy', 'patch': 'partial_update'}), And My ViewSets looks like this def destroy(self, request, pk=None, *args, **kwargs): if request.data.get("book_type") is None: raise ParseError(detail="book_type is required, options are : 'global, non-global'") try: instance = self.get_object() user = self.request.user serializer = self.get_serializer(self.get_object()) ....... self.perform_destroy(instance) except Http404: pass return Response(status=status.HTTP_204_NO_CONTENT) And my test case is this def test_book_delete(self): # check if delete works book_type = {'book_type': 'global'} response = self.client.delete("/api/v1/books/shelfs/{}/" "reader/{}/".format( 1, 2), data=book_type) self.assertEqual(response.status_code, 204) But its alway 415 error The question is, how to pass this book_type in delete ? -
dynamically adding series to highcharts
I'm relative new to highcharts so I'm not that knowledgeable. But what I am trying to do is that I am trying to dynamically create series with a name and some x, y values. To get the x and y values I use two dictionaries looking like this: The X values. They are dates The Y values. They are seconds What I want to do is create a series that have the names of the keys and then they can have multiple points for x, y values. So for example at "Fiber_Mätning" I have two values in the key in both dictionaries. What I want to do is that I create a series with the name "Fiber_Mätning", and then it should have two points where I give both x and y value. So the 1st point in "Fiber_Mätning" would be x:"2020-10-28" y:"28800" and the 2nd point in "Fiber_Mätning" would be x:"2020-10-29" y:"18000" After that I would move on onto the next key in both dictionaries and do the same. So the way I create the series need to be a function that is dynamically creating series and the points depending on the amount of keys and values in the dictionaries. … -
Making API request using React
I am building a "Yahoo Finance" clone and I am having trouble fetching the users data from my own API and displaying it using React components. I have tested the API route itself and it works fine, however when trying to fetch the data from within the React component, the request is never made. (I know this because I added the line for printing "Data fetched" in order to verify) views.py: @login_required def dashboard(request): return render (request, "holdings/dashboard.html") def user_holdings(request): user = Profile.objects.get(user=request.user) positions = user.positions.all() data_response = {} data_response["holdings"] = [] for position in positions: position_data = {} position_data["symbol"] = position.symbol response = requests.get("https://www.alphavantage.co/query?function=OVERVIEW", params={"symbol": position.symbol, "apikey": "4JU2DZ6Q8876MFXK"}) data = response.json() name = data["Name"] position_data["name"] = name response = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY", params={"symbol": position.symbol, "apikey": "4JU2DZ6Q8876MFXK"}) data = response.json() price = data["Time Series (Daily)"]["2020-10-28"]["4. close"] position_data["price"] = price data_response["holdings"].append(position_data) print("Data fetched") return JsonResponse(data_response, safe=False) dashboard.html: <div id="app" /> <script type="text/babel"> class App extends React.Component { render() { return ( <UserHoldings /> ); } } class UserHoldings extends React.Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, items: [] }; } componentDidMount() { fetch("http://127.0.0.1:8000/user_holdings") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.holdings }); }, // … -
Bundle and Minify CSS and JS for plotly dash
I am using this package for using plotly dash for Django in one of my projects. django-plotly-dash The website I am working on expects heavy traffic and the scaling of the web app is very important for the client. Dash applications in Django are being served in an iframe and there are pages where I have multiple iframes and dash applications rendered on a single page. These iframes take ages to load due to all CSS and javascript files they are loading which is not a good user experience. I did R&D and a lot of googling but could not find a good resource in any of the forums on how can I use bundled and minified CSS and javascript files with plotly-dash. Any suggestion related to plotly-dash or Django-plotly-dash is welcome. Note: Packages used to minify and bundle Django static files will not work with this scenario as I do not control the javascript and CSS files being loaded in the dash application plotly dash handles it. (Or let me know if I am wrong.) -
Image field doestn work propertly in template [django]
I dont know why image doestn show in template... I have: MODEL.py class Ad(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, blank=False, null=False, unique=False) image = models.ImageField(blank=False, null=False, upload_to='ads_image/') In my view I have VIEW.py class AllAdsListView(ListView): template_name = 'ads/ads_list.html' model = Ad paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') In project settings: STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') In project urls (...) path('', include('ads.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) At last my template: {% if object_list %} {% for ad in object_list %} <img src="{{ ad.image.url }}" alt="Photo"> {% endfor %} When im using only: {{ ad.image.url }} -> on wbsite is correctly dir with file: /mediafiles/ads_image/a591133ab7babbcc48b2bb7b74a45815.jpg but when I'm usint this <img src="{{ ad.image.url }}" alt="Photo"> nothing is show up ;/ -
Creating a College CMS | Which one will be suitable Django or Node
I have a Final Year Project, Now I want to create a College Management System Where students can view their result, Attendance, Fee, announcements and other activities too. It has Multiple Users ( Admin (HOD), Teachers and Students (Semester 1,2,3,4,5,6,7,8 ) ). Now my question is Which tool will be best for this kind of multiple users tasks. Let me Share your Detail Opinion. -
blog.Post: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). in django
I am making models for my django blog application. But upon running python manage.py makemigrations blog, I get this error message: SystemCheckError: System check identified some issues: ERRORS: blog.Post: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). Here is my models.py file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') class Meta: ordering = ('-publish') def __str__(self): return self.title The error says that my ordering should be a list or tuple. But it already is. I can't understand this error. Can someone please help me out? Thanks in advance -
django Social media post Automation
How can I write a script in Django that will post an image and description on all social media pages like Facebook, Instagram, Twitter, and LinkedIn? -
CSS is not connecting in HTML?
"I am aware that there are other posts on this, however, none of the answers have helped fix my issue. I am making a django project and would like to use some basic css on my page, however it does not seem to be linking. The html file is in a folder called templates, while the css is in a folder called static. Here is what I used to link my css."This is the way i linked; <link rel="stylesheet" type="text/css" src="{% static 'css/defualt.css' %}">. I tried different ways to link the css file from folder static.please bare with since I am still new in programming. please help, thnks in advance. -
Django allauth facebook login
Imm trying to use facebook login from Django allauth social login, I think i missing some config. When i try to login to using facebook it keeps greetings with a error ..... SITE: domain name = localhost:8000/ display name = localhost ERROR: Facebook has detected {AppName} isn't using a secure connection to transfer information. Until {AppName} updates its security settings, you won't be able to use Facebook to log into it. ERROR 2: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.