Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating django-image-cropping to Azure Blob Storage
I am trying to move my media files to an azure file storage, however I'm finding an issue when trying to generate the cropped file as it is not being saved in the azure file storage. Files in model file is as per the below: class ImageShow (models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='homepage/images/') active = models.BooleanField(default=False) cropping = ImageRatioField('image', '1200x400') In template I'm calling it as per the below: <img class="d-block w-100" src="{% cropped_thumbnail images "cropping" scale=1.0 %}"> and the below are the settings specified in setting.py from easy_thumbnails.conf import Settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL_PROCESSORS As for Azure File Storage I have the below code: In settings.py AZURE_ACCOUNT_NAME = '' AZURE_ACCOUNT_KEY = '' AZURE_CUSTOM_DOMAIN = f'' AZURE_LOCATION = '' AZURE_CONTAINER = '' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_LOCATION}/' DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' In custom_azure.py from storages.backends.azure_storage import AzureStorage from django.conf import settings class AzureMediaStorage(AzureStorage): location = settings.AZURE_LOCATION file_overwrite = False And in Urls I have the below code: urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Any Ideas please on how to make it work with Azure blob storage. Thanks -
Django {% trans %} not translating new changes
I am trying to run a web-app locally (forked from here ) . I am using the {% trans %} tag to mark strings to be translated. The original piece of code was <h3> Personal data</h3>. However , when I change it to <h3>{% trans "Personal data" %}</h3> , the "Personal data" does not get translated , even though the original text (from the forked repository) in the following line gets translated . The following screenshot highlights the issue : When I make any changes to the text between <html> tags, it gets reflected in my local instance. But when I make changes to strings marked with {% trans %} , it does not get translated in my local instance (even though the rest of the original text gets translated) . Note : Changes made to text without {% trans %} tag are getting reflected in my local instance. The app is run using docker-compose up Why does the {% trans %} tag not work on new changes ? -
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.error
hi I'm testing my Django rest framework project on a hosting server. when I open the my site domain my site is without any default django style. my admin panel is just html it doesn't have django admin panel style. I connected to the project on host and when i type the collect static command I have this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. this is the admin panel: and this is my project settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # ckeditor CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" -
Does Django Development Web Server Cache Redirects?
I have a Django view that I redirect a user to after they login: # settings.py LOGIN_REDIRECT_URL = 'login-redirect' # account/urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), ... ] # home/views.py from account.models import Member def login_redirect(request): """ Redirect member to appropriate page when they log in. """ member = Member.objects.get(user__id__exact=request.user.id) if member.has_profile: return redirect('homepage', member_id=member.id) else: return redirect('profile-create', member_id=member.id) If I start Django's development server and execute this code when the condition member.has_profile = True, Django redirects me to the homepage view as expected. But if I then go into the database and set has_profile to False, restart the web server, and execute code again, my website acts as if the code isn't executed. Instead, I'm sent immediately to the homepage view again. I can see this by looking at the terminal console: [19/Feb/2021 ...] "GET /account/login/ HTTP/1.0" 200 4268 # I'm using Django's default login method [19/Feb/2021 ...] "POST /account/login HTTP/1.0" 302 0 [19/Feb/2021 ...] "GET /home/login_redirect/ HTTP/1.0" 200 4599 This happens even though I am restarting the server and clearing my browser's cache. In fact, I can edit the login_redirect function so that it only contains a single line pass and I'm still sent to the homepage after … -
React & Objects - TypeError: Cannot read property 'map' of undefined
I'm trying to retrieve a list of objects (motors) from a django database and store it in the state of my MachineTemplate component. Here's the component export default class MachineTemplate extends Component { constructor(props) { super(props); this.state = { myName: this.props.match.params.id, motors: {}, error: "None", loaded: false } this.getMachineDetails = this.getMachineDetails.bind(this); } componentDidMount() { this.getMachineDetails(); } getMachineDetails = () => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: this.state.myName, }), }; fetch("http://127.0.0.1:8000/get-motors", requestOptions) .then((response) => { if (response.ok) { this.setState({ motors: response.data }); } else { this.setState({ error: "Motors not found." }); } }) .catch((error) => { console.log(error); }); this.setState({loaded: true}); } render() { if (this.state.loaded) { return ( <div> <h1>{this.state.name}</h1> <h3>{this.state.error}</h3> {this.state.motors.map(motor => { return <Button key = {motor.number}>{motor.number}</Button> })} </div> ) } else { return( <div> <h1>Awaiting machine details...</h1> </div> ) } } } Here's the error I get TypeError: Cannot read property 'map' of undefined I can confirm the fetch is properly returning the list of motor objects I need, which are formatted like this in the response: 0: {number: 0, enabled: true, item: "EMPTY", machine: 48} I was able to get this exact setup to work fine with a … -
Django Rest Framework not accepting JWT Authentication Token
I am using the Django Restful API Framework together with Simple JWT and have successfully created a URL for receiving and refreshing a user token. In order to try out the authentication using the token, I have created a view that simply lists all the posts inside the database. I have then assigned the IsAuthenticated class to the view. As expected, I get an error message saying that the authentication credentials were not provided. I then went ahead and made a simple GET request using Postman, with the authentication token provided in the "Authorization" tab. The type was set to "Bear Token". Unfortunately, I still get the message "Authentication credentials were not provided." with a 403 Forbidden code. I have also tried to provide the token in the Headers, as well as make CURL requests, everything to no avail. My view looks like this: class PostListView(generics.ListAPIView): permission_classes = (IsAuthenticated,) queryset = Post.objects.filter() This is the serializer: class PostListSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('__all__') The settings.py of the Django project: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny'], 'DEFAULT_AUTHENTICATION_CLASSES:': ('rest_framework_simplejwt.authentication.JWTAuthentication',) } CORS_ALLOW_ALL_ORIGINS = True # For testing purposes I have followed several different tutorials online, read through numerous posts … -
Write JSON to a file in pretty print format in Django
I need to create some json files for exporting data from a Django system to Google Big Query. The problem is that Google BQ impose some characteristics in the json file, for example, that each object must be in a different line. json.dumps writes a stringify version of the json, so it is not useful for me. Django serializes writes better json, but it put all in one line. All the information I found about pretty printing is about json.dumps, that I cannot use. I will like to know if anyone knows a way to create a json file in the format required by Big Query -
why I can not in folder static inside app for project django
i can't access to folder static for project the project structure: -myproject --core --settings.py --myapp --static --------myapp ---- js ---- css --templates --static in settings.py STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR, "static"), ] print STATICFILES_DIRS ['/media/my_pc/Apps/my_project/static'] in main urls.py usethis: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() now i do call file static js don't work -
Django postgis point is in polygon or on boundary
I have a PolygonField poly in my model. For a given point I want to filter all items that either lie within polygon, or lie on its boundary or the smallest distance between the point and polygon is x. .filter(poly__contains=point) checks only first. What about other two conditions? -
Django-Graphene - Relation to an object of the same type
I have defined a database model in which a task object has a relationship to the same task object. class Task(models.Model): id = models.AutoField(primary_key=True) status_id = models.ForeignKey(Status, null=True, on_delete=models.SET_NULL) parent_id = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=128) description = models.CharField(max_length=256) entry = models.IntegerField() In the Graphql API I made it possible to get a task object for myself. I would like to achieve the possibility of retrieving the entire object tree of the same type by calling a graphql query with one call to the object type task. Is it possible? class TaskType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) parent_id = graphene.Field(graphene.Int) name = graphene.NonNull(graphene.String) description = graphene.NonNull(graphene.String) entry = graphene.NonNull(graphene.Int) parent = graphene.List(lambda: TaskType) @staticmethod def resolve_parent(task, _info): return Task.objects.filter(parent_id=task.id) I know I can return such a tree in JSONString type, but I'm looking for a different solution. -
Django query, finding the maximum object
I'm hitting my head on something that should be simple. I have a query like this: MyModel.objects.filter(...).aggregate(max_value=Max('value')) and this does, indeed, return a (dictionary) with key 'max_value' and value that maximum value. But what I want is the object that has that maximum value. -
Heroku issues when uploading pdf and jpg through admin panel | Django, Python
I have a simple project made with python/django and I upload pdfs and jpgs through admin panel. These files can be reached for a day or two, after that I think Heroku delete them. I use in setting whitenoise and I don't get why the server removes them. Settings MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Template for pdf <p>{{ IntroductionCv.paragraph }}</p> <a href="{{ IntroductionCv.pdf.url }}" class="btn btn-fill" target="_blank" download>Download my cv</a> Template for jpg <div class="row"> {% for project in Projects %} <div class="col-md-4 col-xs-6"> <div class="portfolio-item"> <img src="{{ project.image_project.url }}" class="img-res" alt=""> <div class="portfolio-item-info"> <h4>{{ project.title }}</h4> <a href="{{ project.github_link }}"><i class="fab fa-github-square" style="font-size: 5em;"></i></a> <a href="{{ project.site_link }}"><span class="glyphicon glyphicon-link" style="font-size: 4em;"></span></a> </div><!-- /.portfolio-item-info --> </div><!-- /.portfolio-item --> </div> {% endfor %} </div> Views def index(request): context = {'BackEndSkills': BackEndSkills.objects.all(), 'SoftSkills': SoftSkills.objects.all(), 'Services': Services.objects.all(), 'Projects': Projects.objects.all(), 'Counter': Counter.objects.all(), 'IntroductionCv': IntroductionCv.objects.latest('id'), 'title': 'Alexandru Aprodu'} return render(request, 'the_professional/index.html', context) Model for pdf class IntroductionCv(models.Model): paragraph = models.TextField() pdf = models.FileField(upload_to='media', verbose_name='PDF') def __str__(self): template = '{0.paragraph} {0.pdf}' return template.format(self) class Meta: verbose_name_plural = "Introduction Cv" Model for jpg class Projects(models.Model): … -
Create blank (null) profile with writable nested serializers DRF
so I am trying to have an empty profile be created whenever a new user signs up. The problem is the nested (null) serializers are not being created along with the other serializer and returns "education": [ "This field is required." ] Now if I add required=False than if will just return empty data without actually creating the blank education model { "id": #, "education": [], # I want this to be a null list "image": "null", "resume": null, "bio": null, "interests": null } Profile and Education model: from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_default.jpg', upload_to='profile_pics') # TALENT FIELDS resume = models.FileField(upload_to='resumes', null=True) bio = models.TextField("Bio", blank=True, null=True) interests = models.TextField("Interest", blank=True, null=True) class Education(models.Model): owner = models.ForeignKey(Profile, related_name='education', on_delete=models.CASCADE) # TODO: change delete type field = models.CharField(max_length=100, null=True) school = models.CharField(max_length=100, null=True) start_year = models.CharField(max_length=4, null=True) start_month = models.CharField(max_length=10, null=True) graduation_year = models.CharField(max_length=4, null=True) graduation_month = models.CharField(max_length=10, null=True) degree = models.CharField(max_length=100, null=True) gpa = models.CharField(max_length=10, null=True) awards = models.TextField(max_length=100, blank=True) Serializers: from rest_framework import serializers from .models import Profile, Education class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education exclude = ['owner', ] class CreateProfileSerializer(serializers.ModelSerializer): education = EducationSerializer(many=True, … -
How to proper save documents in MongoDB using Djongo
I am facing a problem in which I cannot save documents inside MongoDB with Django. The error follows: AttributeError: 'NoneType' object has no attribute 'attname' With the help of the library Djongo I made these models: from djongo import models from django.utils import timezone class LatLng(models.Model): latitude = models.FloatField(null=False) longitude = models.FloatField(null=False,) def __init__(self,latitude, longitude): self.latitude = latitude self.longitude = longitude class Meta: abstract = True class Parameters(models.Model): cond1= models.IntegerField(null=False,) cond2= models.IntegerField(null=False,) cond3= models.IntegerField() class Meta: abstract = True class MyModel(models.Model): name = models.CharField(max_length=150, null=False) des= models.CharField(max_length=500) pub_date = models.DateTimeField(editable=False) mod_date = models.DateTimeField() parameters = models.EmbeddedField( model_container=Parameters ) wp= models.ArrayField( model_container=LatLng, null=False ) objects = models.DjongoManager() def __init__(self, name, parameters, wp,des=""): self.name = name self.parameters = parameters self.waypoints = waypoints def save(self, *args, **kwargs): ''' On save, update timestamps ''' if self.id is None: self.pub_date = timezone.now() self.mod_date = timezone.now() return super(MyModel, self).save(*args, **kwargs) def __str__(self): return self.name My API looks like: def get_wp(pls): wps = [] for pin pls: coord = LatLng(latitude=p['latitude'], longitude=p['longitude']) wps.append(coord) return wps @api_view(['POST']) def save(request): data = json.loads(request.body.decode('utf-8')) scores = Parameters(cond1=data['cond1'], cond2=data['cond2']) wps = get_wp(data['pls']) obj = MyModel(name=data['name'],parameters=scores, waypoints=wps) print("--> {}".format(obj.name)) #working fine itinerary.save() ## it dies here return JsonResponse({}) I don't know what I'm … -
Using DJ-Rest-Auth: Updating User Profile
I am struggling to figure out why I cant update my user profile I keep getting the below error. {'profile': {'email': [ErrorDetail(string='user with this email address already exists.', code='unique')]}} django.request:log.py:224 Bad Request: /api/students/cf6c35b7-0202-4465-add9-135c52c0bed6/ From my understanding is that the update is actually trying to create a another User. Which is not what I am trying to do. Here is the test code that is failing. def test_change_school(self): createResponse = client.post('/api/auth/reg/', { "email":"test@test.com", "password1":"10wer1232", "password2":"10wer1232", "first_name": "Blake", "last_name": "Alvernaz", "image": "No Image", "is_student": True, "is_teacher": False, "school": self.school1.id}, format="json") self.assertEqual(createResponse.status_code, 201) self.assertTrue(createResponse.data['key']) profile = client.get('/api/auth/user/') id = Student.objects.get(profile_id=profile.data['id']) editRes = client.put('/api/students/{}/'.format(id.id), {"gpa":1.0, "profile":{ "email":"test@test.com", "first_name": "Blake", "last_name": "Alvernaz", "image": "No Image"}, "school": self.school2.id}, format="json") print(editRes.data) self.assertEqual(editRes.status_code,200) Serializers: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "first_name", "last_name", "image", "email"] def update(self, instance, validated_data): profile_serializer = self.fields['profile'] profile_instance = instance.profile instance.save() profile_data = validated_data.pop('profile', {}) profile_serializer.update(profile_instance, profile_data) return super().update(instance, validated_data) class StudentSerializer(serializers.ModelSerializer): profile = UserProfileSerializer() class Meta: model = Student fields = ["gpa", "profile", "id", 'school'] read_only_fields = ("profile",) class SchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ['id', 'name', 'image' ] class CustomRegisterSerializer(RegisterSerializer): is_student = serializers.BooleanField(default=True, write_only=True) is_teacher = serializers.BooleanField(default=False, write_only=True) school = serializers.CharField() @transaction.atomic def save(self, request): user … -
Automatically attach VS Code configuration to container
I'm using a VS code config to attach to a running container so I can run my tests inside the container. ptvsd is used for this. launch.json has the following config: { "version": "0.2.0", "configurations": [ { "name": "Run Django", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}/src", "remoteRoot": "/app" } ], "port": 3000, "host": "127.0.0.1", } ] }< ´´´ I also have a volume mapping in my `docker-compose.yml` so my updates are reflected directly in the container: volumes: - ./src:/app The issue is ... when I make a change VS code unattaches itself and I have to go into debug to restart it. Is there any way to configure VS code so that if an attach fails it will retry it after a few seconds for, say up to a minute or so? This would allow the StatReloader to complete and give it something to attach to. -
VS Code and Python
just reinstalled VS code on my new Mac, and everytime I start it it asks me to install python. Python is referenced in the .zshrc to my brew install, it is also correctly referenced in VS Code, and I have no issues working in python it just throws the error when I open a Python file. Screen shot of VS Code, bar and error -
How to remove clicked line from Bokeh plot
I need to plot several lines in one figure, and by clicking on one get it's reference and remove it from the figure, but I have no idea how to do it. I need to do it in django, so interactive matplotlib code I wrote is no good. In Matplotlib I did it like this: def on_pick(event): id = event.artist event.artist.remove() fig.canvas.draw() I can't find anything usefull, is it possible to do it in bokeh? Please direct me -
Firebase Firestore doesn't retrieve data under Apache (Django)
The following Django 3 code print("trying to add doc") db.collection('col_name').document('doc_name').set({'test_field':1}) print("doc added") works when running python manage.py runserver i.e, a document is created on Firebase When deployed to Apache24 (ApacheLounge version) with mod_wsgi on Win10, the second line hangs. Same hanging problem happens when we try to iterate through the collection (only read operations). for doc in collection('col_name').stream(): -
How can I use images in Django back end without saving it?
I want this site to take an image from user and show it on another page, well I want to to something more with the picture but I have already managed it. I am stuck here, how can I fix it. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload a Photo</title> </head> <body> <form action="showpicture/" method="GET"> <h1>Upload An Image</h1> <label for="img">Select image:</label> <input type="file" id="img" name="img" accept="image/*"> <br><br> <input type="submit"> </form> </body> </html>` My View File from django.shortcuts import render from django.http import HttpResponse, HttpResponseForbidden def index(req): return render(req, "pic/index.html") def showPic(req): return HttpResponse(req.GET['img'])` I want to show the picture in the next page without saving it, how can I do it ? -
I made Hashtag system for my website but after using special characters like " ' " or " ; " and so on it makes #hashtag in Django
I have uploaded an screen shot of the issue. I've tried to use SAFE but it doesn't work. post.content|safe|hashchange Hope someone can help me here -
how to filter items in django
I have some users in my application where some are admin and some are suppliers, I will like to filter only those that are suppliers. I have tried using some queryset but I am not getting it. I will also like some recommendation where I can learn more about to filter objects in Django or python. Thanks models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=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) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) telephone = models.IntegerField(blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" views.py def Viewsupplier(request): suppliers = User.objects.filter(i am getting stuck here with the appriopriate filter) context = {"suppliers":suppliers} print(suppliers) return render(request, 'core/view-suppliers.html', context) -
Creating a registration view in django, always getting an integrity error
So here's the function i wrote for the view: def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] year = request.POST["Year"] form = registerForm(request.POST) if form.is_valid(): branch = form.cleaned_data['branch'] else: return render(request, "events/register.html", { "message": "You didn't provide all the fields", "form": registerForm() }) if not email.endswith("ac.in"): return render(request, "events/register.html", { "message": "You must have an institution account", "form": registerForm() }) # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "events/register.html", { "message": "Passwords must match.", "form": registerForm() }) try: name = User.objects.get(email=email) except ObjectDoesNotExist : name = None # Attempt to create new user #Now This is where the problem is if name is None: user = User.objects.create(username=username, email=email, password=password, year=year, branch=branch) user.save() else: return render(request, "events/register.html", { "message": "email already taken.", "form": registerForm() }) login(request, user) return HttpResponseRedirect(reverse("events:index")) else: ctx = { "form": registerForm() } return render(request, "events/register.html", ctx) So when the form is submitted, i first check if an object with the entered username already exists, if it does than return the form with a message(email already taken). But everytime i try to create a new user, this message is returned and i am unable to … -
unix venv django-admin permission denied
I am trying to set up django project on a Linux CentOS system. I have created a virtual environment like this: $ python3 -m venv venv And activated it like this: $ source venv/bin/activate Within this virtual environment I updated pip like this: (venv)$ python -m pip install -U pip This returned the message below: Successfully installed pip-21.0.1 Next I installed django and djangorestframework like so: (venv)$ python -m pip install django djangorestframework This returned the message below: Successfully installed asgiref-3.3.1 django-3.1.7 djangorestframework-3.12.2 pytz-2021.1 sqlparse-0.4.1 I then tried to start a new project like this: (venv)$ django-admin startproject myproject . This is when I get the response: -bash: /home/me/projects/venv/bin/django-admin: Permission denied I don't think the solution to this should be a simple chmod on that file, because I think perhaps something is incorrect in how I installed things in the first place? Surely all permissions should be automatic considering I was working with (venv) activated? What am I missing here? -
How to update ManyToMany data?
I have a User who can follow/unfollow other users. Each User have a Profile where the users he follows he stored. MODEL class User(AbstractUser): pass class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) following = models.ManyToManyField("User", blank=True, related_name="following_name") follower = models.ManyToManyField("User", blank=True, related_name="follower_name") VIEWS @login_required def userlookup (request, username): if request.method == "POST": # Foo has ID = 5 # Bar has ID = 6 # Baz has ID = 7 # CurrentUser is FOO so CurrentUser = 5 CurrentUser = request.user.id # I am looking at Bar's Profile page so username = 'bar' # This gives TargetUser = 6 TargetUser = User.objects.get(username=username).id # Setup variable has a "boolean" to false by default isfollowing = 'false' # Obtain the list of users that Foo currently follows Following = list(Profile.objects.filter(user=CurrentUser).values('following')) # This returns : [{'following': 6}, {'following': 7}] # Loop through each entry to check if the TargetUser is followed by Foo or not for i in Following: if i['following'] == TargetUser: # On this occasion, Foo do follow Bar so we change the variable to true isfollowing = 'true' # Since the var is set to true, we want to remove the TargetUser from the list because we are "unfollowing him". if …