Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Like button back end logic using Django Rest Framework
I have a Blog app where users can add new Post and any users can like the post. models.py class Post(models.Model): title = models.CharField(max_length=60) class PostLikes(models.Model): likeusers = models.ManyToManyField(User) likepost = models.ForeignKey(Post,on_delete=models.CASCADE,null=True,related_name='likepost') serializers.py class PostSerializers(serializers.ModelSerializer): #likepost = serializers.SerializerMethodField() **I have to mention like count here** class Meta: model = Post fields = '__all__' class PostlikeSerializer(serializers.ModelSerializer): class Meta: model = PostLikes fields = '__all__' views.py class LikeListCreate(APIView): def get(self,request,pk):#function to get total number of likes to particular post post = Post.objects.filter(pk=pk) # find which post's likes are to be extracted like_count = post.likepost.count()# counts total user likes ,besides my code is wrong serializer = PostlikeSerializer(like_count,many=True) return Response(serializer.data) def post(self,request,pk):#function to add likes to post # how do I check if user is already liked the post ? likeusers = request.user likepost = Post.objects.filter(pk=pk) serializer = PostlikeSerializer(data=request.data) if serializer.is_valid(): serializer.save(likeusers,likepost) return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) urls.py path('posts/<int:pk>/like/',LikeListCreate.as_view(),name = 'post_likes'), I am unable to implement logic in views.py module and serializers.py section too. Please help, thanks in advance Git link to my project https://github.com/Anoop-George/BlogApp.git -
Unable to display image in template (Django 3.0)
Unable to display profile_pic image in template I know i m doing something very terrible. model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True) def __str__(self): return self.user.username index.html {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Django Level Five</h1> {% if user.is_authenticated %} <h2>Welcome {{ user.username }}!</h2> <div> <img src="{{ user.profile_pic.url }}" alt="user-image"> </div> {% else %} <h2>Welcome to the site!</h2> {% for b in users %} {% endfor %} {% endif %} </div> </div>{% endblock %} views.py def index(request): #commented: userpro = UserProfileInfo() #commented: var={'userz': userpro} #commented: return render(request, 'basic_app/index.html',context=var) return render(request, 'basic_app/index.html') User authentication is fine and name is getting displayed in template but not the image. I have tried lot of things but image didn't show. Div and Alt-name getting displayed but not the profile_pic. -
if comment.name == user not working correctly
I want users to be able to delete comments they have written. Unfortunately though I can not get the if statement to work. {% if comment.name == user %} <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I could see the value of user and comment.name I included the below code. This was for testing purposes and would not be included in the sites final design. <h3 class="article-content">{{ user }}</h3> <p class="article-content">{{ comment.name }}</p> I also wanted to test to make sure the inside of the if statement was work. <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I included the below code. Again this would not be included in my final sites design. {% if post.author == user %} <a href="{% url 'delete_own_comment' comment.id %}">-------delete this comment---------</a> {% endif %} But by looking at the screenshot you can tell the code is not working properly. The 30th comment is a 'Test comment for StackOverflow purposes.' The comment was written by RossSymonds. The user currently logged in is RossSymonds. If everything was working properly you would see 'delete this comment' (which is different to '------delete this comment---------'). Does anyone have a suggestion? … -
How to access related model object in vuejs component with django rest framework
I am building a full-stack web application, using Django, Django Rest framework and Vue.js as the frontend. I am working with a Post model that has an author column, which is related to the Django User model by foreign key, like so; class Post(models.Model): title = models.CharField(max_length=50, unique=True) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) I have set up my serializers, viewsets and the urls like so; serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username', 'email'] class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ['url', 'title', 'body', 'author'] In my vews.py; class UserViewSets(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class PostViewSets(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer In my urls.py; router = routers.DefaultRouter() router.register('users', UserViewSets) router.register('posts', PostViewSets) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] I can access my Post model on the rest framework console on my browser. Now in my Vuejs component, i can also get the list of my posts if i make a request to the post api endpoint i.e. http://localhost:8000/posts. However, i also want to get the related model, i.e User (the author of individual post), as an object so i can do something like post.author.username or post.author.email … -
Pytest django - Multiple application, multiple database - not able to access any DB other than default db
Problem I have a Django(1.8) project running 2 applications: App1, App2. Both of the applications run with their own databases: app1db and app2db, sharing the defaultdb for users and groups. I am trying to integrate pytest-django as part of the unit testing. This is where I am hitting with problem as Pytest do not support multiple databases. My use case is I would be needing the unit tests only on app1 and I am pretty much sure I won't be needing it on app2. And I can mock my users and groups objects from defaultdb for this unit tests and I won't be needing access to defaultdb. But the problem is I always see the unit tests access the defaultdb and I don't see a way of making the app1db accessible from unit test cases. When I try to access any object form app1db, I get the following error: E ProgrammingError: relation "app1_table" does not exist E LINE 1: INSERT INTO "app1_table" ("field1", "field2", "... E ^ Database Settings 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'defaultdb', 'PASSWORD': 'pass', 'HOST': localhost, }, 'app1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app1db', 'USER': 'postgres', 'PASSWORD': 'pass', 'HOST': localhost, }, "app2": { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': … -
Django Management Command - Write All or Nothing
I have a django custom management command. This is how the handle and other methods in BaseCommand looks: def first_function(data_point): another_model = AnotherModel(data=data, related_data= data_point) another_model.save() def second_function(data_point): yet_another_model = YetAnotherModel(data=data, related_data= data_point) yet_another_model.save() def handle(self, *args, **options): data_cursor = DataPoint.objects.filter(ready_for_migration=True) for data_point in data_cursor.iterator(): with transaction.atomic(): self.first_function(data_point) self.second_function(data_point) data_point.complete=True data_point.save() sleep(20) raise Exception("Testing Exeception") I expect the AnotherModel, YetAnother Model table to be loaded and after Exception is raised I want the data that was loaded in the respective tables to be erased. Instead what I am observing is that the tables get loaded fine, the exception is thrown but after the execption, the data remains in the table. Essentially I want all the related data for a given data point to be loaded but if any of the related tables fail, the transaction for the data point should rollback. What am I missing? -
Receiving 'TypeError: expected string or bytes-like object' when saving object
I have an issue with uploading data from excel to a db using Django. When this function runs, it is suppose to get the data in specified range and upload it to db when 'q.save' is ran. def scrapeExcel(excel): uploadQuery = [] wb = load_workbook(excel) for sheet in wb.worksheets: last_row = sheet.max_row if sheet == wb.worksheets[0]: fullName = sheet.cell(row = 16, column = 4).value for row in sheet.iter_rows(min_row = 20, max_row = last_row - 1): curRow = [] for cell in row: curRow.append(cell.value) uploadQuery.append( time( file = excel, fullname = fullName, cdate = get_date(curRow[3]), dayname = curRow[4], units = curRow[9], submitteddate = get_date(curRow[11]), approveddate = get_date(curRow[15]), project = curRow[21], name = curRow[22], comment = curRow[25], locationname = curRow[26], status = 1 ) ) for q in uploadQuery: q.save() When I run this, it gives me the following error. TypeError: expected string or bytes-like object When I checked each value via print or sys.stderr.write, I know they are getting the right value. But inside the for loop, if I check what q is, with for q in uploadQuery: sys.stderr.write(' query--{} '.format(q)) q.save() it just says query--time Object (none) So I am assuming, it is not getting appended to uploadQuery? or is … -
How do I access Django running on a Google Compute Engine VM from my browser?
I have a Django dashboard application I wish to view from my browser. Django is running in a Docker container on one of Google's Compute Engine instances. The GCE instance is on a Google VPC, on which I've added firewall rules to open Django's port 8000. I've added my IP to Django's ALLOWED_HOSTS in settings.py. The container's logs indicate that it is running fine, yet when I access the GCE instance's IP from my browser, I am immediately unable to connect. I can ping the instance from my command line just fine. Is there something I'm missing here? Been stuck on this for a few hours now. Note: I have the Django container running on a "Docker network" in order for Celery to communicate with a RabbitMQ container. This was recommended to me somewhere, but I am unfamiliar with Docker networks or if they are causing the issue. -
how to create a monthly array between two dates in django?
I have a model that have the following input: monthly income: 100 start date: 31/03/2020 (created with DateField) end date: 24/7/2020 (created with DateField) I want to obtain the following QuerySet: [0, 0, 100, 100, 100, 100, 100, 0, 0, 0, 0, 0] that is the 12 months and the respective income amount. -
Use text input for ModelChoiceField in Django
I'd like to be able to have a user change which product is on a specific line item of an order. Here is my model: class OrderLineItem(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='details') product = models.ForeignKey(Product, on_delete=models.CASCADE) price_before_discounts = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) discount = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) has_applied_discount = models.BooleanField(default=False) total = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) line_number = models.IntegerField(default=1) added_by_promotion = models.ForeignKey('Promotions.CouponRedemption', on_delete=models.CASCADE, blank=True, null=True, default=None) substitute = models.ForeignKey(Product, related_name='substitute', on_delete=models.CASCADE, blank=True, null=True, default=None) The only field I am trying to change is the substitute field. Here is my form: class OrderDetailSubstitutionForm(ModelForm): substitute = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput, required=False) def __init__(self, *args, **kwargs): super(OrderDetailSubstitutionForm, self).__init__(*args, **kwargs) self.fields['substitute'].widget.attrs.update({'class':'form-control text-center','style':'width:100%'}) self.fields['substitute'].label = "" class Meta: model = OrderLineItem fields = ('substitute',) Because there are around 400 products in the database, the page takes a long time to load when there are more than a small amount of line items. So instead of using a select widget, I'd like to be able to allow a user to enter a product's SKU, and then do a lookup and get the appropriate product id, or raise a validation error if it can't find anything. I've tried overriding the clean method to do this lookup, … -
I am having issues with nested serializers in django
from rest_framework import serializers from .models import UsersMan from log.serializers import LogSerializer from log.models import Log class UserSerializer(serializers.ModelSerializer): class Meta: model = UsersMan fields = ("s_no","user_id","name","time_zone") class UserLogSerializer(serializers.ModelSerializer): #members = serializers.SerializerMethodField(source="UsersMan", read_only=True) activity_periods = serializers.SerializerMethodField(source="Log", read_only=True) class Meta: model = UsersMan depth = 1 fields = ("s_no", "user_id", "name", "time_zone","activity_periods",) -
AttributeError: _auto_id_field Django with MongoDB and MongoEngine
I am using mongoengine with Django Below is my Model class class MyLocation(EmbeddedDocument): my_id = IntField(required=True) lat = GeoPointField(required=False) updated_date_time = DateTimeField(default=datetime.datetime.utcnow) My Views.py def store_my_location(): loc = MyLocation(1, [30.8993487, -74.0145665]) loc.save() When I am calling the above method I getting error AttributeError: _auto_id_field Please suggest a solution -
How do I use column data for function calls in a Django filter?
I'm trying to filter a Django QuerySet with the following: result_queryset = result_queryset.filter( start_datetime__gte=datetime.now(F("<foreign__key>__timezone")) ) I'm comparing the start_datetime of a record and checking if it's greater than or equal to the current time localized to a timezone, which is a column in the model. But this results in the error: graphql.error.located_error.GraphQLLocatedError: tzinfo argument must be None or of a tzinfo subclass, not type 'F' I understand that this is because F is not being evaluated as it's a SQL expression. The question is: How do I get the actual value of the timezone column so that I can use it in datetime.now() inside of the filter? -
How do I get linebreaks to show the blank line between paragraphs in Django?
I'm trying to get text from a blog to show on my html page similar to how it shows in the Django admin. I've used both linebreaks and linebreaksbr and the following happens. What the Django admin shows (and how i'd like it to show as paragraphs): This is a test - sentence 1. This is the second sentence after a line break. This is the code I have that renders it out on the page: {% for post in posts %} {% if post.published %} {{ post.title }} Created by: {{ post.author }} on {{ post.published_on }} {% if post.has_been_updated %} Updated by: {{ post.author }} on {{ post.updated_on }} {% endif %} {{ post.body|linebreaksbr }} {% endif %} {% endfor %} This is how it shows on the page:Second sentence on new line without line in between On a side note, if I use linebreaks instead of linebreaksbr it will cancel out all of my CSS code. The CSS code only works with linebreaksbr. -
IntegrityError at /profiles/author/post - NOT NULL constraint failed: profiles_tweet.author_id
NOT NULL constraint failed: profiles_tweet.author_id I want to save the tweet with state pending , but it gives Integrity error . And also I want to view all tweets of author but Iam not able to filter . I want that if any author tweet something is stored as pending in database . and I want it to view in his profile . From models.py class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) USER_TYPE_CHOICES = ( ('AUTHOR', 'author'), ('EDITOR', 'editor'), ('PUBLISHER', 'publisher'), ('SUPERVISOR', 'supervisor'), ('ADMIN', 'admin'), ) user_type = models.CharField(choices=USER_TYPE_CHOICES,max_length=64, default='student') favorite_color = models.CharField(max_length=50) bio = models.TextField(null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['favorite_color'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class Tweet(models.Model): author = models.ForeignKey(MyUser,on_delete=models.CASCADE) text = models.CharField(max_length=140) # author_email = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) published_at = models.DateTimeField(null=True) STATE_CHOICES = ( ('pending','pending'), … -
Django url cannot be found after editting urlpatterns
I'm playing with Django python tutorial and notice a very odd url behavior. My project name is 'mysite', and in its urls.py, it by default has from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] This shows that little rocket base page when I visit localhost:8000. Then I editted like following, from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('student/', include('student.urls')) ] to indicate a new url for my own app, this time the base page localhost:8000 returns a 404. I'm very curious why my new line will affect the base page? BTW my django version is 3.0.6. -
django submit not woking (only returning me csrf tokenvalues)
I had made a form in which I have 3 buttons Out of those 3 buttons, last button is for submit which only return me CSRF value here's my code teacher-profile.html <form name="get_teacher_data" method="post"> {% csrf_token %} <div class="card"> <div class="card-body"> <h2 class="card-title border-bottom pb-3">Go through the following paragraph to fill up some valuable information</h2> <p class="card-text"> I <input id="teacher_name" type="text" placeholder="name of teacher" class="form-control" style="width:auto;display:inline;" disabled> currently gives lecture for students of <select class="selectpicker" data-live-search="true" name="branch" id="branch" title="branch" multiple> <option>B.Tech</option> <option>M.Tech</option> <option>Ph.D</option> </select> at <input id="institute_name" type="text" placeholder="name of institute" class="form-control" style="width:auto;display:inline;" disabled> <div class="card"> <div class="card-body"> <table class="table table-hover"> <thead> <tr> <th scope="col">Semester</th> <th scope="col">Section & Room No</th> </tr> </thead> <tbody> <tr id="row1"> <td> <select class="selectpicker" id="semester1" title="semester" name="semester"> <option>I</option> <option>II</option> <option>III</option> <option>IV</option> <option>V</option> <option>VI</option> <option>VII</option> <option>VIII</option> <option>ALL</option> </select> </td> <td> <div class="form-row"> <input id="section1" type="text" name="section" placeholder="section" class="form-control" style="width:auto;"> <input id="room_no1" type="text" name="room_nos" placeholder="room no" class="form-control" style="width:auto;"> </div> <button id="add_sec" class="btn btn-light" type="button">Add more sections</button> </td> </tr> </tbody> </table> </div> <div class="card-footer"> <button id="add_sem" class="btn btn-danger" type="button">Add more semester</button> </div> </div> </p> </div> <div class="card-footer"> <button id="save" class="btn btn-primary" type="submit" for="get_teacher_data">Save</button> </div> </div> </form> my view def get_teacher_data(request): if request.method == 'POST': val = (request.POST) print(val) return … -
Add select_related() to Django Authentication backend
In my project I have both Group and Custom User Based Permissions. I have a custom authentication backend which essentially checks to see if the user has group permissions and then sees if they have any revoked permissions which need to be removed from the checked perms. I am running into an optimization issue now that I am testing the implementation of said revoked permission, because my CustomUser model has an M2M field that holds these revoked permissions which is a relation to auth_permissions, and my BackendAuthentication checks for it, I am getting crazy amounts of DB hits on page load. How can I pass a perfetched object to my AuthBackend? Here is my AuthBackend: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import Permission class UsersAuthenticationBackend(ModelBackend): def _get_revoked_perms(self, user_obj): if user_obj.is_superuser or user_obj.is_admin: revoked_perms = Permission.objects.none() elif hasattr(user_obj, 'revoked_permissions'): # this causes the issue, I need to pass in the prefetch related to my model backend...HOW? # this should be something like CustomUser.objects.prefetch_related('revoked_permissions') revoked_perms = getattr(user_obj, 'revoked_permissions').values_list('content_type__app_label', 'codename') else: revoked_perms = Permission.objects.none() revoked_perms = ["{}.{}".format(perm[0], perm[1]) for perm in revoked_perms] print(revoked_perms) return revoked_perms def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_active: return False revoked_perms = self._get_revoked_perms(user_obj) all_perms = self.get_all_permissions(user_obj) allowed_perms = … -
ModuleNotFoundError for model class in django
I ran into the following error. File "C:\django-project\CodingWithMitchBlog\demoproject\Blog\api\urls.py", line 3, in from demoproject.Blog.api.views import api_detail_BlogPost_view ModuleNotFoundError: No module named 'demoproject.Blog' Blog is my appname. This is my project structure. -
Django DateTimeInput returns incorrect format for Database
I'm looking for the simplest datetimepicker to implement on a Django form, and would like to use the included Django DateTimeInput widget. No matter what I try however, the widget returns a datetime value in an incorrect format which will not upload to my database. I need the format '%Y-%m-%d %H:%M:%S', but the widget returns '%d/%m/%Y %H:%M:%S' This problem has been discussed a little here: http://stackoverflow.com/a/35968816/1382297 I believe the problem may be from setting the input_type to DateTime-local, but i am unaware of other options and cannot find any in the documentation. I've tried passing format='%Y-%m-%d %H:%M:%S' to the widget, as well as FORMAT_INPUTS = ['%Y-%m-%d %H:%M:%S'], and tried initializing these in the DateInput class, all with no luck. Below is my forms.py class DateTimeInput(forms.DateTimeInput): input_type = 'datetime-local' class EnterMatchForm(forms.ModelForm): class Meta: model = match fields = ('match_name', 'player1', 'player2', 'victory', 'match_description', 'match_date') widgets = { 'match_date': DateTimeInput(), } What is the proper way to initialize the widget so that it returns datetime values in the format Y-m-d H:M:S? Thanks in advance. -
Django DRF send post request parameters as form data
I want to send post request api parameters as form data instead of passing it as url. -
Pass extra args with kwarg running function
Is it possible to pass extra args or kwargs in model photo_1 --> upload_to? I want to pass extra data (size) to prepare custom file name. i have tried def upload_to_id_image(self, filename, size=""): fname = filename.split('/')[-1] return f'thumbs/{fname}' photo_1 = ProcessedImageField( null=True, blank=True, processors=[Thumbnail(192)], options={'quality': 85}, upload_to=upload_to_id_image(size="192") ) but it seems doesn't work whole model: class Photo(AddedUpdatedModel): name = models.CharField(max_length=128, null=True, blank=True) file = ThumbnailerImageField(upload_to='temp/') photo_type = models.ForeignKey(PhotoType, on_delete=models.PROTECT, null=True, blank=True, default=None) def upload_to_id_image(self, filename): fname = filename.split('/')[-1] return f'thumbs/{fname}' photo_1 = ProcessedImageField( null=True, blank=True, processors=[Thumbnail(192)], options={'quality': 85}, upload_to=upload_to_id_image ) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.photo_1: self.photo_1 = self.file.file super().save(*args, **kwargs) i am looking for solution to pass size in model above -
Using django-fsm to determine the state of an object
How do I get the current state of a database item using django-fsm. I have tried get_state() but it returns a null value. Here is my code: from django.db import models from django_fsm import FSMField, transition STATES = ("Open", "In Progress", "Re Opened", "Done", "Closed") STATES = list(zip(STATES, STATES)) class Ticket(models.Model): title = models.CharField(max_length=40) state = FSMField(default=STATES[0], choices=STATES) Is there a way of getting the state field using django-fsm library. Also, how do I get the available state transitions using the model methods. -
Django Settings not configured
I created a web project using Django and PyCharm, everything was working fine. When I reopened the project and added git, all the files were in red and when I tried to runserver I got a huge error message. The last error message is: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTING S_MODULE or call settings.configure() before accessing settings. Here is a screen shot:You must either define the environment variable DJANGO_SETTING I am trying to figure out why everything just stopped working. Any help would be awesome. Thank you in advance. L -
Can't access Django website deployed on EC2
I tried deploying my django project on an AWS EC2 instance but when I try to access the instance through its public DNS I do not get anything back. Things I have already done: Setup the NACL to allow all traffic for now Setup the Security group to allow all traffic for now Ensure that instance is inside a VPC and VPC is connected to an internet gateway Set the allowed hosts config in the django settings to ['.compute.amazonaws.com'] When I try to run the server on 0.0.0.0:8000 and try to access it through the browser I do not get any response. What could I possibly check to solve this problem?