Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot install module page_types using pip
I need to run django/mezzanine project with python 2.7. When I try to start my server using command python mange.py runserver I get the error: No module named page_types. When I try to install it I get: pip install page_types ERROR: Could not find a version that satisfies the requirement page_types (from versions: none) ERROR: No matching distribution found for page_types WARNING: You are using pip version 20.1.1; however, version 20.3.4 is available. You should consider upgrading. Can you help ? I get the same error with python 3.6. -
Django CSRF verification failed. Request aborted. error
i'm try to make image upload using dropzone.js that not using login or register and i got CSRF verification failed. Request aborted. error so pls help... javascript is: <script type="text/javascript"> Dropzone.options.fileDropzone = { url: '/media/', init: function () { this.on("error", function (file, message) { alert(message); this.removeFile(file); }); var submitBtn = document.querySelector("#submitBtn"); var myDropzone = this; submitBtn.addEventListener("click", function () { console.log("upload"); myDropzone.processQueue(); }) }, autoprocessQueue: true, clickable: true, thumbnailHeight: 90, thumbnailWidth: 115, maxFiles: 1, maxFilesize: 10, parallelUploads: 1, addRemoveLinks: true, dictRemoveFile: 'delete', uploadMultiple: false, } </script> and html is: <form class="imageUploaderForm" method="post" id="upload" enctype="multipart/form-data"> {% csrf_token %} <div class="form-title">Upload your Image</div> <div class="upload-type">File should be Jpeg, Png, Gif</div> <div class="dropzone" tabindex="0" class="drop-zone" style="border-style: dotted;" id="fileDropzone"> <input accept="image/jpeg, image/png, image/gif" multiple="" type="file" autocomplete="off" tabindex="-1" name="myFile" class="drop-zone-input" style="display: none;"> <div class="placeholder"> <img class="hide" width="115" height="90" src="#" id="preview"> </div> </div> <span style="color: rgb(169, 169, 169);">or</span> </form> and i used var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); and headers: { 'x-csrf-token': CSRF_TOKEN, }, this two codes but it's still have same error -
Redirect user to index after raising restriction
I have two groups of users Administrators and Clients and I'm trying to redirect user from Clients group to index page in case they try to access detail view of calculations that is not theirs. I still want to allow Administrators to view everyone's calculation details. I'm using Django's built in User model and Administrators group is characterized by is_staff flag. The mechanism itself works but I get 404 Page not found instead of Index page. Any idea on how to fix it? views.py class CalculationDetailView(LoginRequiredMixin, generic.DetailView): model = Calculation def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) try: if not self.request.user.is_staff: qs = qs.filter(pk=self.request.user.pk) return qs except: redirect('index') -
The value of 'list_filter[0]' refers to 'people__type', which does not refer to a Field
First time asking a question here so sorry if I'm not doing this perfectly. Context : Project in django, trying to have a filtering option in my admin panel. I have this Charfield in my model.py file that I am trying to use as a filter in admin.py, however python tells me that it doesn't refer to a field which is very confusing. Here are my codes : models.py class People(models.Model): OWNER = 'owner' TENANT = 'tenant' TYPES = ((OWNER, 'Owner'), (TENANT, 'Tenant')) type = models.CharField(max_length=20, choices=TYPES) people_name = models.CharField(max_length=200) people_surname = models.CharField(max_length=200) people_phone_number = models.CharField(max_length=200) people_email = models.EmailField(max_length=254) people_occupation = models.CharField(max_length=200) people_revenue = models.IntegerField() people_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.people_name admin.py from django.contrib import admin from django.db import models from .models import * from tinymce.widgets import TinyMCE #Register your models here. class PeopleAdmin(admin.ModelAdmin): fieldsets = [ ("Type", {"fields": ["type"]}), ("Information", {"fields": ["people_name", "people_surname", "people_phone_number", "people_email", "people_occupation", "people_revenue"]}), ("URL", {"fields": ["people_slug"]}), ] list_filter = ('people__type',) admin.site.register(People, PeopleAdmin) -
How to sink this error in Django? Invalid HTTP_HOST header
We keep getting this error with Django: Invalid HTTP_HOST header: u'/home/scheduler/run/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. I believe this happens because a "disallowed" host is establishing connection with our Django app. And we are aware we are letting this happen: ALLOWED_HOSTS = ['.mysite.org', '*'] Before you faint, we do this because we reject hosts using custom middleware DomainNameMiddleware. Our site supports clients pointing their own domains to ours and registering those domain names through a controlled process from our side. So yeah, those alien hosts will get rejected, just with extra steps. However it's really annoying to get this "Invalid HTTP_HOST header" error constantly. I'm not sure at what point in the stack this happens, but is there any way we could sink it and ignore it? -
Why is Python XLSWRITER Cell formula does not work programmatically?
I have these simple codes that get the SUM of A1, A2 and A3. workbook = xlsxwriter.Workbook(path) worksheet = workbook.add_worksheet() worksheet.write(0, 0, 5, None) worksheet.write(1, 0, 3, None) worksheet.write(2, 0, 9, None) worksheet.write(3, 0, '=SUM(A1:A3)', None) workbook.close() Theoretically it should work. But it's not. (See image below) But if I manually change one of the 3 numbers then it will work. Manually changing its numbers are no good bc the excel is a generated file via python program, I cannot just say to the client to manually change a 1 number of their choice and change it back when the sum formula works. Send help senior Programmers. -
django-cities-light ValueError: invalid literal for int() with base 10: ''
I am getting error when I run python manage.py cities_light here is the complete error Assuming local download is up to date for http://download.geonames.org/export/dump/countryInfo.txt Traceback (most recent call last): File "manage.py", line 30, in execute_from_command_line(sys.argv) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 215, in handle self.country_import(items) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 308, in country_import country = Country.objects.get(geoname_id=items[ICountry.geonameid]) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 399, in get clone = self.filter(*args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1315, in _add_q child_clause, needed_inner = self.build_filter( File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 20, in init self.rhs = self.get_prep_lookup() File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup return self.lhs.output_field.get_prep_value(self.rhs) File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/fields/init.py", line … -
I'm getting this error when trying to run a django aplication: django.db.utils.OperationalError: unsupported file format
The program was quite running well a few minutes ago, after adding SlugField to my post URLs which I feel like it has nothing to do with the error, this is what I get when I run Python3 manage.py runserver in my terminal. System check identified some issues: WARNINGS: base.Post.tags: (fields.W340) null has no effect on ManyToManyField. System check identified 1 issue (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql) File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 394, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: unsupported file format The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/peace/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/peace/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/peace/.local/lib/python3.6/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations if self.has_table(): File "/home/peace/.local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/peace/.local/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) … -
Django, total price of not iterable object
Hello I have a question I have no idea how can i get total price of not iterable object in Django, I get this error: TypeError at /cart 'OrderItem' object is not iterable Here is my code, I would be pleased by any advise. views.py order_items = OrderItem.objects.filter(cart=cart) order_items = OrderItem.objects.annotate( sum=Sum(F('item__price') * F('quantity')) ).get(cart=cart) order_items.total_price = order_items.sum order_items.save(force_update=True) models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class OrderItem(models.Model): cart = models.ForeignKey('Cart', on_delete=CASCADE, null=True) item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) total_price = models.IntegerField(default=1) -
Is there a way to implement a decorator to choose database for queries inside a function?
I have two databases; "default" and "replica". I know we can choose database explicitly by using ".using()". But I want something like this: @my_decorator(db_name = "replica") def my_fun(): """All queries in this function should perform operation on replica db""" Is there any way to do this? -
TinyMCE emoticon plugin doesn't load in Django
I am trying to set up tinyMCE for my Django website and I'm struggling with including plug-ins, in this case the emoticon one. Settings TINYMCE_DEFAULT_CONFIG = { # Plugins "plugins": "emoticons" # Toolbar "toolbar": "emoticons " [..] Formfield poller_text = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30})) Now on client side it throws the following error: tinymce.min.js:9 Failed to load plugin: emoticonssearchreplace from url plugins/emoticonssearchreplace/plugin.min.js What do I miss? -
"message": "Enum 'AccountsCandidateGenderChoices' cannot represent value: <EnumMeta instance>",
I am tring to create a candidate using graphene django. But is giving me error that cannot represent value . The choice is not saving in the database Enum 'AccountsCandidateGenderChoices' cannot represent value: **Django models** class Candidate(Model): class Gender(models.TextChoices): MALE = "Male" FEMALE = "Female" name = models.CharField(max_length=100) gender = models.CharField(max_length=100,choices=Gender.choices) > **ENUMS** > > class CandidateGender(graphene.Enum): > MALE = "Male" > FEMALE = "Female" > > **Mutations** class CreateCandidate(graphene.Mutation): > _candidate = graphene.Field(CandidateType) > > class Arguments: > input = CandidateInput(required=True) > > @classmethod > @candidate_required > def mutate(cls, root, info, input=None): > candidate = Candidate.objects.create(**input) > return CreateCandidate(_candidate=candidate) > > **Browser** > > mutation{ createCandidate(input: {name: "abc", gender: FEMALE}){ > Candidate{ > id, > gender > } } } -
Django form errors not showing when use id_<field-name>
I'm a beginner in Django, I try to use id_<field-name> method to create a signup form interface, but the default validation like "This field is required." or "This username already exists" is not showing. I don't want to use {{ form.as_p }} because I want to separate the field. The registration still working if i input the true the valid things. HTML <form method="POST" class="register-form" id="register-form" enctype="multipart/form-data" > {% csrf_token %} <div class="form-group"> <label for="id_username"><i class="zmdi zmdi-account material-icons-name"></i></label> <input type="text" name="username" id="username" placeholder="Username"/> </div> <div class="form-group"> <label for="id_email"><i class="zmdi zmdi-email"></i></label> <input type="email" name="email" id="email" placeholder="Your Email" /> </div> <div class="form-group"> <label for="id_password"><i class="zmdi zmdi-lock"></i></label> <input type="password" name="password" id="password" placeholder="Password"/> </div> <div class="form-group"> <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" /> <label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in <a href="#" class="term-service">Terms of service</a></label> </div> <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> views.py def register(request): registered = False if request.method == 'POST': # Get info from "both" forms # It appears as one form to the user on the .html page user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) # Check to see both forms are valid if user_form.is_valid() and profile_form.is_valid(): # Save User Form to Database user = user_form.save() # Hash … -
Is there anyway to create logging files for each user and date wise (Python)
I have an application where I need to create a folder for each user in which they will have their day-wise logs. I have added created custom middleware which will call my custom_logger file for creating logs file for each user. Below is my middleware auth_middleware.py from .custom_logger import LogClass log_obj=LogClass() def simple_middleware(get_response): def middleware(request): user_token=request.headers['userid'] user_name=request.headers['username'] page_name=request.headers['pagename'] log_obj.log_setting(str(user_name),str(page_name)) return response return middleware I am calling my custom_logger.py from middleware. class LogClass: def log_setting(self,user_name,page_name): current_date = datetime.date.today() #set variable which store current date log_path = './logs/' + user_name #log path of user folder if os.path.exists(log_path): #check user folder is already exist or not pass else: os.mkdir(log_path) #use to create user folder with username filename=str(current_date) +'.log' #set file name with current date logging.basicConfig(level=logging.DEBUG,filename=log_path+'/'+ filename,force=True, format='%(asctime)s : %(levelname)s : '+page_name+' : %(pathname)s : %(lineno)s: %(funcName)s : %(message)s') And after this, I import logging in every file and it works fine if one user work at a time for more than one user concurrently it's not working. If two users parallelly calls one API the first user will have initial logs then all the logs of the first user and the second user will come under the second user. Is there any way … -
How to get the URL requested in Django
So my URL which I am requesting in Django is 127.0.0.1:8000/ I want to get the id no. and URL separately in my views. I tried using: current_url = request.build_absolute_uri print(current_url) But it's giving error as: module 'django.http.request' has no attribute 'build_absolute_uri' Same goes with: current_url = request.resolver_match.url_name Not sure what I am doing wrong. -
How to flash ValidationError in Django template
I have a validator for limiting the upload size of a field ('track' & 'artwork') inside a form, I've added my validator function to 'validators.py' and set the validators setting to my model field. This seems to work as the app automatically reloads the form if file is too large , but my ValidationError is not visible, how can I flash this error message on screen ? also just to note, I'm using 'crispy forms' to display the upload form. validators.py from django.core.exceptions import ValidationError def file_size(value): filesize = value.size if filesize > 5242880: raise ValidationError("The maximum file size that can be uploaded is 5MB") else: return value models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio', validators=[file_size]) title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', validators=[file_size]) artist_name = models.TextField(max_length=50) artist = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) forms.py class MusicForm(forms.ModelForm): class Meta: model = Music fields = ['title', 'artist_name', 'track', 'artwork'] help_texts = { 'track': ('Max mp3 size: 5 MB'), 'artwork': ('Max image size: 5 MB'), } widgets = { 'title': forms.Textarea(attrs={'rows':1, 'cols':1}), 'artist_name': forms.Textarea(attrs={'rows':1, 'cols':1}), } -
How i can set file name user wise in loggin in setting.py
Django sessions: How to include session ID in every log record? I referred this article and it worked for me . I want to set the filename/file path dynamically for each user like. user1.log,user2,log like this .But I tried every thing i know can anyone help me. -
Django - Add custom authorization to endpoint. Ensure user editing entity is creator
I have a PUT view endpoint update an existing Post entity, but I only want it to be allowed to update if the user is indeed the creator. So when anyone makes a request an AWS Cognito token is accompanied with the request and authenticated. From the token I can get the user's uuid, then I want to compare it with the Post model's creator_id attribute, if they're the same allow edit, otherwise return a 401. How can I create and add a custom authorizer to check for this? view.py @api_view(['PUT']) @method_decorator(cognito_authenticator) def update_post_by_id(request, post_id): try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: return JsonResponse(dict(error=f'Post id: {post_id} does not exists'), status=status.HTTP_400_BAD_REQUEST) user_id = get_user_from_token(post_id) if user_id != post.creator_id: return JsonResponse(dict(error='Not authorized'), status=status.HTTP_401_UNAUTHORIZED) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): try: post_obj = serializer.save() except django.db.utils.InternalError as e: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) authentication def get_user_from_token(request): auth = request.headers.get("Authorization", None) parts = auth.split() res = decode_cognito_jwt(parts[1]) return res model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) type = models.CharField( choices=PostType.choices, max_length=50 ) -
Django Admin - how to display ManyToManyField values
I want to display the related genres of a music album at my Django admin but I'm not sure how my query has to look like: This is my Albums Model: class MusicAlbums(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255) artist = models.ForeignKey(MusicArtists, on_delete=models.CASCADE, related_name='artist_relation') album_artist = models.ForeignKey(MusicArtists, on_delete=models.CASCADE, related_name='album_artist_relation') cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images) cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images) release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False) genre_relation = models.ManyToManyField(through='GenreMusicAlbum', to='Genre') total_discs = models.IntegerField(verbose_name=_("Total Discs #"), blank=True, null=True,) total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True,) copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255) date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added")) My helper class to Glue Genre together with GenreMusicAlbum: class GenreMusicAlbum(models.Model): music_album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, blank=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, blank=False, null=False) And Finally my Genre Model: class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name=_("Genre"), blank=True, null=True, editable=False, unique=True, max_length=50) So far so good. Now I started to put all this into Django admin class MusicAlbumsAdmin(admin.ModelAdmin): list_display = ['title', 'get_artist', 'get_album_artist', 'release_date', 'date_added'] ordering = ['title'] list_filter = ['title'] readonly_fields = ('get_artist', 'get_album_artist', 'cover', 'cover_tn', 'release_date', 'get_album_genre', 'total_discs', 'total_tracks') exclude = ('artist', 'album_artist', 'genre_relation') list_per_page = … -
Why do I need to use SlugField in Django?
I searched on google and found this: "SlugField is a field for storing URL slugs in a relational database. SlugField is a column defined by the Django ORM. SlugField is actually defined within the django.db." But still, the definition sounds a little complicated to me. I don't even know what a slug is in this context and not sure about Django ORM. I just need a reason why I should use SlugField in Django in simple terms. -
DRF Serializer access value of SerializerMethodField
class SimpleSerializer(serializers.HyperlinkedModelSerializer): value_x = serializers.SerializerMethodField('func_x') value_y = serializers.SerializerMethodField('func_y') def func_x(self, obj): return 0 def func_y(self, obj): value_x ?? In above's example is there any way to access value_x within func_y whereas value_x should have the value of 0? I've tried accessing it by just value_x and self.value_x but obviously both don't work -
How to reverse check if object exisit in many to many django?
I have two models: Model Student: name = models.CharField() ..... .... wishlist = models.ManyToManyField(University, blank=True) Model University: name = models.CharField() ...... . .. . . . . Basically am just creating a wishlist by which user can like on a university and then add it to their wishlist ! ( am expressing this via a heart icon ), So when user reclicks on same item then it will remove it from the wishlist, thats it ! The problem is that, how to check if a user has liked particular university ? here is my code: def index(request): univesity = University.objects.filter(is_approved=True) context = {'univesity': univesity} return render(request, 'search/index.html', context) above is where i fetch all university for searching purpose ! In this i need to check if the use have already added the university to the wishlist relationship. And if its true then the heart icon will turn into red else empty color ! And now this is how i show on template {% if data.student_set.all %} <button><em class="icon ni ni-heart-fill" ></em></button> {% else %} <button><em class="icon ni ni-heart"></em></button> {% endif %} It doesnt work the way i expected ! please guide -
How to create a lock for redis key
I have a django webapp to handle football teams events (match, training...) that are called "team sessions". Each team session is composed by "athlete sessions" whose data (max speed, run distance, etc) are calculated when I create a team session, and this takes a long time. This work very well. The next that I implement is that, once a create a team session, I export it in a postgresql database. To do that I create a redis key "linked" to a gpm command that makes queries. The problem is that: since athlete session takes a long time, some athlete sessions do not finish to be processed when gpm command starts its execution. And so I want to create a redis key that remains "blocked" for a certain period of time (for example 10 minutes) in order to complete the creation of the team session and all of its athlete sessions. This method creates the redis key that I want to lock (I write it in the TeamSession class). It takes two arguments: the first one is a record of django model that contains all information about postgre DB, used by gpm command; and teamsession_id. def queue_gds_for_gpm(self, gds_record, teamsession_id): queue = … -
Why unable to save image to db in django?
I am new to Django and trying to save image to database i have written few lines code, which are not showing any error but are not able to save image to database. View:- def IndexView(request): print("index view..") if request.method == 'POST': print("post") form = ImageForm(request.POST, request.FILES) print("form {}".format(form)) if form.is_valid(): print("valid..") form.save() form = ImageForm() return render(request, "index.html") my template:- <div class="container"> <form enctype="multipart/form-data" action="" method="post"> {% csrf_token%} <hr><br><br> <input type="file" name="" id="" required/> <br><br> <input type="submit" class="btn btn danger" value="Upload"> </form> </div> Hope to here from you soon Thanks in advance -
Django Rest Framework how do I POST nested serializers that contains Files
I have two serializers as follows class VariantSerializer(serializers.ModelSerializer): image_1 = serializers.ImageField(required=False) image_2 = serializers.ImageField(required=False) image_3 = serializers.ImageField(required=False) image_4 = serializers.ImageField(required=False) class Meta: model = Variant fields = ['is_default', 'price', 'old_price', 'quantity', 'size', 'shoe_size', 'color', 'image_1', 'image_2', 'image_3', 'image_4', ] class ProductSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) category = serializers.CharField() class Meta: model = Product fields = ['store', 'name', 'description', 'brand', 'model', 'gender', 'category', 'variants'] def validate_category(self, value): if not Category.objects.filter(slug=value).exists(): raise serializers.ValidationError( {'category': 'category does not exist!'}) return super().validate(value) def validate_variants(self, value): if len(value) > 5: raise serializers.ValidationError( "Maximum of 5 serializers per product") return super().validate(value) def validate_store(self, value): request = self.context.get('request') if not Store.objects.filter(id=value.id, user=request.user).exists(): raise serializers.ValidationError( {'store': 'Store does not exist!'}) return super().validate(value) def create(self, validated_data): name = validated_data.get("name") store = validated_data.get("store") category = get_object_or_404( Category, slug=validated_data.pop("category")) variants = validated_data.pop("variants") # Create Product product = Product(**validated_data) product.save() # Handle category product.category = category # Handle Slug slug = slugify(name) + '-' + str(product.id) product.slug = slug # Handle Variant for variant in variants: new_variant = VariantSerializer(data=variant) if new_variant.is_valid(): variant["product"] = get_object_or_404( Product, id=variant.get("product")) image_1 = variant.get("image_1") image_2 = variant.get("image_2") image_3 = variant.get("image_3") image_4 = variant.get("image_4") if image_1 is not None: variant.pop("image_1") if image_2 is not None: variant.pop("image_2") if image_3 is …