Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
No module named 'config.settings' while deploying Django app on heroku (STILL NOT ANSWERED FROM OTHER QUESTION)
First of all, the question already asked here is still not answered. Secondly, this link is for an Apache server. The problem that I am having is with a website that builds and deploys with no errors. However, there is an application error and this is the Heroku logs: 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-09-17T03:34:09.334127+00:00 app[web.1]: ModuleNotFoundError: No module named 'config.settings' 2021-09-17T03:34:09.334298+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-09-17T03:34:09.367176+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-09-17T03:34:09.462499+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [INFO] Shutting down: Master 2021-09-17T03:34:09.462582+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-09-17T03:34:09.609202+00:00 heroku[web.1]: Process exited with status 3 2021-09-17T03:34:09.666279+00:00 heroku[web.1]: State changed from starting to crashed 2021-09-17T06:31:35.431068+00:00 heroku[web.1]: State changed from crashed to starting 2021-09-17T06:31:44.765393+00:00 heroku[web.1]: Starting process with command `gunicorn td-auth-master.wsgi --log-file -` 2021-09-17T06:31:46.007394+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-09-17T06:31:46.007831+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Listening at: http://0.0.0.0:13306 (4) 2021-09-17T06:31:46.007879+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Using worker: sync 2021-09-17T06:31:46.011232+00:00 app[web.1]: [2021-09-17 … -
user input and text choice as well in django model
In django model, user input and text choices to be filled to a field name. class Store(models.Model): class Size(model.TextChoices): MEDIUM = "M", "Medium" LARGE = "L","Large" shirt_size = models.CharField("Shirt Size", choices=Size.choices, default=Size.MEDIUM) When django is run with admin to add records to table, it will show drop down to choose Size which are available and at the same time, i want to have custom fill as well for user input(S, XXL, etc..) -
how to render list directory tree structure using python in django?
[enter image description here][1] i tried to print list of directories in html web page using python-Django but facing error. Python code run perfectly in pycharm but while i render the same it's shows error. Kindly help on this [1]: https://i.stack.imgur.emphasized textcom/e5q8M.png -
ParseError at /api/ JSON parse error - Expecting value: line 1 column 1 (char 0)
''' Internal Server Error: /api/ Traceback (most recent call last): File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\parsers.py", line 65, in parse return json.load(decoded_stream, parse_constant=parse_constant) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\utils\json.py", line 31, in load return json.load(*args, **kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 293, in load return loads(fp.read(), File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 370, in loads return cls(**kw).decode(s) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "F:\Projects\DRF\fpro\firstapp\views.py", line 17, in get data=JSONParser().parse(stream) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\parsers.py", line 67, in parse raise ParseError('JSON parse error - %s' % str(exc)) rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) [17/Sep/2021 12:06:07] "GET /api/ HTTP/1.1" 500 102139 F:\Projects\DRF\fpro>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ''' -
How to insert values in user table and to map the user table and role table and store the user_id and role_id into the role_user table using django
I need to get the user values from postman by using "POST" method and to map the role values into all the users and save user_id and role_id into role_user table. The way i inserted the values: { "email": "sk@hara.com", "phone": "1234567890", "roles": { "id": 1, "name": "Lab User", "is_deleted": false }, } usermodel.py class user(AbstractBaseUser): email = models.EmailField(max_length=255, blank=False, null=False, unique=True) phone = models.CharField(max_length=20, blank=True, null=True) roles = models.ManyToManyField('Role', related_name="role_user", db_table="role_user") class Meta: db_table='user' userserializer.py class Adduser(serializers.ModelSerializer): email = serializers.CharField(max_length=255, required=True, validators=[user_exists]) roles = serializers.PrimaryKeyRelatedField(queryset=Role.objects.all(), many=True, default=None) class Meta: model = User fields = ['email', 'roles', 'phone'] rolemodel.py class Role(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False, null=False) is_deleted = models.BooleanField(default=False, null=False) class Meta: db_table = "role" roleserializer.py class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ['id', 'name', 'description'] -
Filtering and grouping over many-to-many relationship Django
How can I write the code below with the .filter() method in the best way? These are my models class RoomCategory(models.Model): price = models.CharField(max_length=1000, default='', blank=True, verbose_name=_("Price")) title = models.CharField(max_length=1000, default='', blank=True, verbose_name=_("Title")) description = RichTextField(default='', blank=True, verbose_name=_("Description")) class Room(models.Model): category = models.ForeignKey(RoomCategory, verbose_name=_("Room category"), related_name="rooms", on_delete=models.CASCADE, null=True) class Reservation(models.Model): forename = models.CharField(verbose_name=_('First name'), max_length=20, blank=True,) surname = models.CharField(verbose_name=_('Last name'), max_length=20, blank=True,) reservation_status = models.CharField(max_length=10,verbose_name=('Reservation status'), choices=( ('pending', _('Waiting')), ('accept', _('Accept')), ('reject', _('Reject')), ),default=('pending'),blank=True, null=True) rooms = models.ManyToManyField(Room) To better express my intentions. I want something that I would achieve in pure python with something like this: def check_availability(room, check_in, check_out): available_list = [] reservation_list = room.reservation_set.all().filter(reservation_status="accept") for reservation in reservation_list: if reservation.date_from > check_out or reservation.date_until < check_in: available_list.append(True) else: available_list.append(False) return all(available_list) Views.py room_list = Room.objects.all() available_rooms = {} for room in room_list: if check_availability(room, data['date_from'], data['date_until']): if room.category.title in available_rooms: available_rooms[room.category.title] += 1 else: available_rooms[room.category.title] = 1 I need to get output like this: <QuerySet [{'RoomCategory': <RoomCategory>, 'count': 14}, {'RoomCategory': <RoomCategory>, 'count': 25}, {'RoomCategory': <RoomCategory>, 'count': 13}, {'RoomCategory': <RoomCategory>, 'count': 2}, {'RoomCategory': <RoomCategory>, 'count': 17}, '... (remaining elements truncated)...']> -
How to get only most recents objects?
I have an option object that contains a list of options that I keep track of. I would like to retrieve the most recent values of this option. My model: class MachineOption(models.Model): name = models.CharField(max_length=200) value = models.CharField(max_length=80) value_type = models.CharField(max_length=10) date_time = models.DateTimeField(auto_now_add=True) machine = models.ForeignKey( "machine.Machine", verbose_name=_("machine"), related_name="machine_options", on_delete=models.CASCADE ) class Meta: verbose_name = _("MachineOption") verbose_name_plural = _("MachineOptions") ordering = ["machine", "name"] def __str__(self): return self.name Each time the value of an option must be modified, I don't overwrite the previous value but I add a new MachineOption object which will have the most recent date_time. I can retrieve the value of a single most recent option with this request: MachineOption.objects.filter(name="threshold temp").latest("date_time") But I don't know how to get the values of all the most recent options. For example, I can have 4 objects: { "id": 6, "name": "name", "value": "m1", "value_type": "string", "date_time": "2021-09-17T07:12:15.446282Z", "machine": 1 }, { "id": 7, "name": "name", "value": "m1.0", "value_type": "string", "date_time": "2021-09-17T07:12:19.904487Z", "machine": 1 }, { "id": 1, "name": "threshold temp", "value": "20", "value_type": "int", "date_time": "2021-09-17T06:57:37.881934Z", "machine": 1 }, { "id": 5, "name": "threshold temp", "value": "30", "value_type": "int", "date_time": "2021-09-17T07:12:06.128011Z", "machine": 1 } I want to be able to … -
The most pythonic way of handling exceptions
I've got this code: normalize_data['key1'] = json.loads(normalize_data.get('key1', '')) normalize_data['key2'] = [key for key in json.loads(normalize_data.get('key2', '[]'))] normalize_data['key3'] = [json.loads(normalize_data.get('key3', ''))] normalize_data['key4'] = [json.loads(normalize_data.get('key4', ''))] As you can see, every key processes differently. If any key will be missing, it will raise JSONEncodeError. If any value of any key will be in wrong format, it will raise TypeError. What is the most pythonic way of handling those? I tried putting this before the code above: for key in ['key1', 'key2', 'key3', 'key4']: if key not in normalize_data: raise serializers.ValidationError({'error': f'Field {key} is missing'}) try: json.loads(normalize_data[key]) except TypeError: raise serializers.ValidationError({'error': f'Wrong format of {key}'}) But I don't really like it. Thanks everybody. -
i am unable to login as an organization in django views
I have requirement to build a crm . In that i have 3 things 1 is super user who is there by default second organization in which i use a foreign key of user bcoz i dont want to create a custom user and re write a lot of things third agent who is user as foreign key and connected to an organization no i want to login as organization in the dashboard if i am using the super user as login credential it is telling me required organization instance if i am login using organization account it is giving error NoReverseMatch at /leads/login_handle here is my views.py login and sign up handle code def signup_handle(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') pass1 = request.POST.get('pass') pass2 = request.POST.get('re_pass') pass2 = request.POST.get('re_pass') check = request.POST.get('agree-term') if(pass1 != pass2): return HttpResponse("Babe your passwod does not matches please try again") else: x = User.objects.create(email = email,username = email,first_name = name,is_staff = False) # x = User.objects.create(name,email,pass1) x.set_password(pass1) x.save() y = Organization(user = x,name = name) y.save() # print(f"lets varify the data name = {name},{check}") return HttpResponse("Babe you have succesfully created your account") else: return HttpResponse("Babe something goes wrong") def … -
How to unit test a blanck field form in Django?
I spent quite a lot of time to set some unit test, and one of the issues was the setting of some fields that I defines to be nullable and blankable. Putting dummy values was not an issue, but I wonder: how to deal with fields that need to be blank, in particular for numbers? Let me write as an example an extract of my code. The model: class Company(models.Model): company_name = models.CharField("nom", max_length=200) comp_slug = models.SlugField("slug") street_num = models.IntegerField("N° de rue", null=True, blank=True) street_cplt = models.CharField("complément", max_length=50, null=True, blank=True) address = models.CharField("adresse", max_length=300) The form: class CompanyForm(forms.ModelForm): company_name = forms.CharField(label="Société", disabled=True) class Meta: model = Company exclude = [] The view: def adm_options(request, comp_slug): ''' Manage Company options ''' company = Company.get_company(comp_slug) comp_form = CompanyForm(request.POST or None, instance=company) if request.method == "POST": if comp_form.is_valid(): comp_form.save() return render(request, "polls/adm_options.html", locals()) A very simple unit test: def create_dummy_company(name): return Company.objects.create( company_name=name, comp_slug=slugify(name), street_num=1, street_cplt='', address='dummy address' ) def test_adm_options_update(self): self.company = create_dummy_company("Test company") url = reverse("polls:adm_options", args=[self.company.comp_slug]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.company.address = 'new address' response = self.client.post( reverse("polls:adm_options", args=[self.company.comp_slug]), self.company.__dict__, ) self.company.refresh_from_db() self.assertEqual(response.status_code, 200) Of course, the key part is posting the form after the update. The different cases … -
how can I get user of id when user.is_active=False in django
views.py User Register Class Base in views.py UserRegister need to get id of user when user.is_active = False views.py Verify function base -
Erroneous custom field of the one-to-one User model in the Admin Panel
I created the custom Subscriber one-to-one model to extend the existing Django's User model. (I know that it's better to use an AbstractUser, but I just wanted to try this out for the sake of learning) I can create a new User successfully through the shell, and I can edit (in the admin panel) the custom fields that User has after the creation. However, I can't create new users in the admin panel without the usage of shell, because of an error. I suppose there is something wrong with admin.py? Error: IntegrityError at /admin/auth/user/add/ UNIQUE constraint failed: app_subscriber.user_id models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Subscriber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def create_user_subscriber(sender, instance, created, **kwargs): if created: Subscriber.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_subscriber(sender, instance, **kwargs): instance.subscriber.save() admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from . import models # Define an inline admin descriptor for Subscriber model # which acts a bit like a singleton class SubscriberInline(admin.StackedInline): model = models.Subscriber can_delete = False verbose_name_plural = 'subscribers' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (SubscriberInline,) … -
Uploading generated PDF file from React to Django (without <input type="file">)
I'm trying to upload a generated PDF file from React to Django but it won't work. I tested my django end-point using postman and it works properly. I know how to do that with <input type="file"> but, in that case, the user doesn't provide any input because the file is generated as PDF by React. Here's my Django View: class quizPdfView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self,request): try: print(request.data) quizPDF.objects.create(user=request.user,pdf=request.data['pdf']) return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) And here's how i send the data from React (the file that i'm sending is just for test, i will change it later with the one that must be sended): const config = { header: {'Content-Type': 'multipart/form-data'} }; const URL = 'http://127.0.0.1:8000/api/uploadpdf/'; let formData = new FormData(); var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.addPage(); doc.text(20, 20, 'Do you like that?'); formData.append('pdf',doc) axios .post(URL,formData,config) .then((res) => { console.log(res.status) }) .catch((err) => console.log(err)); And, when i send the request, i get this error in django: <QueryDict: {'pdf': ['[object Object]']}> Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f47fe90c6d0>": "quizPDF.user" must be a "User" instance. Bad Request: /api/uploadpdf/ [17/Sep/2021 06:54:43] "POST /api/uploadpdf/ HTTP/1.1" 400 … -
Mypy Error : json.decoder.JSONDecodeError: Unterminated string starting at: line x column y (char z)
I am running mypy against my django project in a docker container. Using this command: mypy --install-types --non-interactive --config-file=../setup.cfg "$@" It has been working wonderfully for the past 6 months or so, but sometimes this error arise: Traceback (most recent call last): File "/usr/local/bin/mypy", line 11, in <module> sys.exit(console_entry()) File "/usr/local/lib/python3.6/dist-packages/mypy/__main__.py", line 11, in console_entry main(None, sys.stdout, sys.stderr) File "mypy/main.py", line 96, in main File "mypy/main.py", line 165, in run_build File "mypy/build.py", line 179, in build File "mypy/build.py", line 254, in _build File "mypy/build.py", line 2697, in dispatch File "mypy/build.py", line 3014, in process_graph File "mypy/build.py", line 3089, in process_fresh_modules File "mypy/build.py", line 1975, in load_tree File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 4925 (char 4924) ERROR: 1 All I could do to fix this issue is fully rebuild the container. Could it be I have misconfigured something ? -
Celery Beat Task Hangs With Out Any Errors
I have a Django app, and I'm using Celery Beat to run a task periodically. If I call the task when running Celery, it runs without errors: app/tasks.py ... @task(name='task1') def func(): # Some code func.run() ... If I then start Celery celery -A project worker -l info, the task runs without errors. The issue comes when I try to run that same task with Celery Beat, imagine I have this schedule: app.conf.beat_schedule = { 'some_task': { 'task': 'task1', 'schedule': crontab(minute=30, hour='22') } } This task should run every day on 22:30, and it does, the task starts but then hangs without logging anything, I cannot figure out the root of the issue, this is not a memory error, I have already checked that, and the task runs fine on my local machine using Celery Beat. I have also tried to use Celery Beat Daemon, but the task keeps hanging whenever it starts. I can't figure out what is happening, any suggestions?