Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i figure out this thingy making other computer to visit my web
How can I make other computers to visit my flask web? any easy way to do that? -
What is difference between 2 package fcm-django and django-fcm
I'm so confuse between 2 package fcm-django and django-fcm. As i know, they are a firebase service to support notification in mobile type. But both of packages have syntax and import ways are difference. So i don't know what is benefit of them. Could you compare both of them, plz. Thanks -
Django ViewSet ModuleNotFoundError: No module named 'project name'
I'm trying to use the ModelViewSet to display Users, but for some reason Django does not seem to like the UserViewSet import in project/urls.py. Seems like a pretty silly error, but I've been stuck on this for a while and it's frustrating. I don't have any errors in the code as far as I know and the imports are fully functional. Am I missing something? Django version 2.2.13 project/urls.py from django_backend.user_profile.views import UserViewSet router = routers.DefaultRouter() router.register('user', UserViewSet) urlpatterns = [ path('accounts/', include(router.urls)), ] userprofile/views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all()#.order_by('-date_joined') serializer_class = UserSerializer Error from django_backend.user_profile.views import UserViewSet ModuleNotFoundError: No module named 'django_backend' Project structure -
formset in inlineformset can't be updated CBV
i want to update my formset , but it wont be updated , only the parent fields will be updated this is my UpdateView class MobileCustomerUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = MyModel form_class = MyModelForm template_name = 'template/template.html' def get_context_data(self,*args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['formset'] = MyUpdateInlineFormSet(self.request.POST,instance=self.object) data['formset'].full_clean() else: data['formset'] = MyUpdateInlineFormSet(instance=self.object) return data def form_valid(self,form): self.object = form.save() context = self.get_context_data() formset = context['formset'] with transaction.atomic(): if formset.is_valid() and form.is_valid() and formset.cleaned_data!={}: formset.instance = self.object formset.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('my_app:invoice',kwargs={'pk':self.object.pk}) and this is my inlineformset MyUpdateInlineFormSet= inlineformset_factory( MyModel,MyChild,form=MyChildForm,fields=( some fields ),extra=1) i much appreciate your helps ... -
Django admin, when I choose a category, brands are selected for this category only
please help me!! I have a problem: I have a model Category, Brand, Product. class Category(models.Model): name = ... class Brand(models.Model): name ... class Product(models.Model): name = ... category = models.Foreinkey(Category, ...) brand = models.Foreinkey(Brand, ...) price = ... I need: in Django admin, when I choose a category, brands are selected for this category only, for example: Phones - LG, Huawei ... etc. Laptops - Acer, Asus ... etc. if you know how to do it, please -
ValueError at /BlogHome/What-Is-Python
i want to show specific comment when user click on specific title, i got this error. Field 'id' expected a number but got 'NumPy and Pandas are very comprehensive, efficient, and flexible Python tools for data manipulation. An important concept for proficient users of these two libraries to understand is how data are referenced as shallow copies (views) and deep copies (or just copies). Pandas sometimes issues a SettingWithCopyWarning to warn the user of a potentially inappropriate use of views and copies.\r\n\r\nIn this article, you’ll learn:\r\n\r\nWhat views and copies are in NumPy and Pandas\r\nHow to properly work with views and copies in NumPy and Pandas\r\nWhy the SettingWithCopyWarning happens in Pandas\r\nHow to avoid getting a SettingWithCopyWarning in Pandas\r\nYou’ll first see a short explanation of what the SettingWithCopyWarning is and how to avoid it. You might find this enough for your needs, but you can also dig a bit deeper into the details of NumPy and Pandas to learn more about copies and views.\r\n\r\nPrerequisites\r\nTo follow the examples in this article, you’ll need Python 3.7 or 3.8, as well as the libraries NumPy and Pandas. This article is written for NumPy version 1.18.1 and Pandas version 1.0.3. You can install them with pip:\r\n\r\nIf … -
Function to create dymmy images in Django
I use following code found here in order co create dummy images for tests in Django. def generate_test_image() -> ContentFile: """ Generates simple test image. """ image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0)) file = BytesIO(image.tobytes()) file.name = 'test.png' file.seek(0) django_friendly_file = ContentFile(file.read(), 'test.png') return django_friendly_file It works fine and this file object returned by this function is accepted by ImageField and storage backend with no problems during tests. Recently I have decided to add image hash creation on each image during model instance creation. ( it is called on each new instance save()) Following function is in charge for doing this: def create_image_hash(image: BinaryIO, raise_errors: bool = False) -> Optional[imagehash.ImageHash]: """ Creates image hash on image file. """ try: image_hash = imagehash.average_hash(PIL.Image.open(image)) except PIL.UnidentifiedImageError as err: if raise_errors: raise err from err return None return image_hash as you can see it uses PILLOW to open file. Object type for image argument that this function receives during non-test regular save that issued by API is : 'django.db.models.fields.files.ImageFieldFile' And it also works fine but not in tests, becouse obviously in tests it would receive ContentFile instead of ImageFieldFile and PILLOW can’ deal with it. (PIL.UnidentifiedImageError exception) Question is - is … -
How to keep temporary instance of a model object
[Product model connects Order model via Foriegnkey. Order model has an order instance for product pen.Now if pen is deleted from product how to keep a temporary instance for product as long as the order isn't completed.][1] check the picture attached to see the models. https://i.stack.imgur.com/en7Cc.jpg -
Django login(request, user) return none
When i submit a valid username and password with login form it's redirected to same page with next URL and User not logged in. I have no idea why this is happening. :( Views.py code def sign_in(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): if form.user_cache is not None: user = form.user_cache if user.is_active: login(request, user) next_url = request.GET.get('next') if next_url: return HttpResponseRedirect(next_url) return HttpResponseRedirect('/user_dashboard_url/') else: messages.add_message( request, messages.ERROR, "Username or password is incorrect." ) return render(request, 'sign_in.html', {'form': form}) -
Custom function for API Django Framework
Working on custom API function that works on creating and updating Ratings when I try to test run the function on Postman I get the following error: IntegrityError at /api/movies/1/rate_movie/ UNIQUE constraint failed: API_rating.user_id, API_rating.movie_id so I do not know if the flaw could be on code or what here is the code below @action(detail=True, methods=['POST']) def rate_movie(self, request, pk=None): if 'stars' in request.data: movie = Movie.objects.get(id=pk) #user = request.user #Can not use now due to lack of auth, login user = User.objects.get(id=1) stars = request.data['stars'] try: rating = Rating.objects.get(user=user.id, movie=movie.id) rating.stars = stars rating.save() serializer = RatingSerializer response = {'message': 'Rating Updated', 'results': serializer.data} return Response(response, status=HTTP_200_OK) except: rating = Rating.objects.create(user=user, movie=movie, stars=stars) serializer = RatingSerializer response = {'message': 'Rating Created', 'results': serializer.data} return Response(response, status=HTTP_200_OK) else: response = {'message':'Stars not selected for rating'} return Response(response, status=HTTP_400_bad_request) Lastly here is a picture of the sample test I made when I got the error -
Django: Creat Serializer validation fields not used
Just a quick question about the Serializers in Django RestFramework. Especially about the create class. I thought that the CreateSerializer was about what was needed for the Object creation. For exemple my UserCreateSerializer: from rest_framework import serializers from django.contrib.auth import get_user_model from ..models.model_user import * class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_e', 'is_b', 'profile' ] extra_kwargs = { 'password': {'write_only': True}, 'id': {'read_only': True}, 'profile': {'read_only': True} } def create(self, validated_data): user = User( username=validated_data['username'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'], is_a=validated_data['is_a'], is_e=validated_data['is_e'], is_b=validated_data['is_b'] ) user.set_password(validated_data['password']) user.save() return user And so when in my Angular FrontEnd I POST a new user like so: ngOnInit(): void { this.registerForm = this.formBuilder.group({ username: [''], password: [''], first_name: [''], last_name: [''], email: [''], is_a: [null], is_e: [null], is_b: [null] }); } createUserOnSubmit() { this.http.post(this.ROOT_URL + 'users/', this.registerForm.value).subscribe( response => { console.log("yolo", response); console.log(response['id']); this.redirectUser(response['id']); }, error => { console.log("yolo-error", error); }); } redirectUser(userId: number) { this.router.navigate(['user/', userId]); } } I POST the new user without any id and profile (the profile being created upon user creation with an event listener in the BackEnd), it doesn't bother the BackEnd and the fact that I'm including the … -
Django debug=False but shows debug messages
I have set DEBUG=False in my production setup and yet it prints debug log messages if (hostname==Prod): DEBUG = False When I run somthing I can confirm DEBUG is set to False (Through a print message) but still the log.debug("Test") message gets printed DEBUG is set to False DEBUG is of <class 'bool'> [16/Jun/2020 11:02:30] [DEBUG] [Main -> Test.py -> runTest -> 5 -> test] -
Django simplejwt JWTAuthentication Permission
I'm using rest_framework_simplejwt.authentication.JWTAuthentication in Django to create tokens for our users. But some users have limited user permissions[in the admin panel]. For example they only allow to get articles and nothing else. But the token that simplejwt creates allow user to get all other data as well. Is there a way to adjust it? -
how to concurrently update one mongoDB document by multiple django thread
So, I have MongoDB collection namely cloud_quota which has a document of each project with its corresponding cloud quota values like how much instances are currently in usage, amount of storage disk used, etc. Now, there's API that subtracts the value of instance_usage based on the value requested for the project. and this API is hosted on Django. At a point, multiple other services can hit this API and request to update the instance_usage value of the same project. since Django works in threads, there can be chances that, 2 or multiple threads (API calls) are trying to update instance_usage at the same time and there's chances of dirty write or lost update. What can be done to avoid this issue? I want to overcome dirty read and dirty write. -
How can I improve this Django query?
I have this Django query which is taking several minutes to run. stat_type = 'Some String' obj = xxx # some brand object query = Q( Q(stat_type__icontains=stat_type) & Q(Q(brand=obj) | Q(organisation__in=obj.organisation_set.active()))) result = ViewStat.objects.filter(query).aggregate(one=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(1)))), \ three=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(3)))), twelve=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(12)))), all=Count('id', filter=Q(created__gte=timezone.now() - relativedelta(months=int(999))))) Models class Brand(models.Model): ... class Organisation(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) ... class ViewStat(models.Model): stat_type = models.CharField(max_length=21) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, blank=True, null=True) organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, blank=True, null=True) I have roughly 80k Organisations, 700 Brands and 10 million ViewStats. How can I improve query performance? -
How to convert png to jpeg with pillow in django?
I want that when users upload a png image it converts to jpeg before saving it into the database. if it is in another format then do not need to convert. I write this code but this not converting png to jpeg. from io import BytesIO from PIL import Image from django.core.files import File def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object if im.format == "RGB": iim = im.convert("RGB") iim.save(im_io,"JPEG", quality=70) else: im.save(im_io,im.format, quality=70) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image where I'm wrong. -
Django Error - django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
i get the following error: , line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. I'm not sure why this is happening. The variables created for the choices are created before calling them so I don't think its the order of the model classes. Can anyone please help? models.py from django.db import models from model_utils import Choices from datetime import date # Create your models here. class GeoChoice(models.Model): country = models.CharField(max_length=50) region = models.CharField(max_length=50) subRegion = models.CharField(max_length=50) class ChannelChoice(models.Model): channel = models.CharField(max_length=50) subChannel = models.CharField(max_length=50) class CreationConversionChoice(models.Model): creation_conversion = models.CharField(max_length=50) class SpendStatusChoice(models.Model): spendStatus = models.CharField(max_length=50) class SpendTypeChoice(models.Model): spendType = models.CharField(max_length=50) class Year(models.Model): year = models.IntegerField() REGION = [(i,i) for i in GeoChoice.objects.values_list('region', flat=True).distinct()] SUBREGION = [(i,i) for i in GeoChoice.objects.values_list('subRegion', flat=True).distinct()] COUNTRY = [(i,i) for i in GeoChoice.objects.values_list('country', flat=True).distinct()] CHANNEL = [(i,i) for i in ChannelChoice.objects.values_list('channel', flat=True).distinct()] SUBCHANNEL = [(i,i) for i in ChannelChoice.objects.values_list('subChannel', flat=True).distinct()] CREATION_CONVERSION = [(i,i) for i in CreationConversionChoice.objects.values_list('creation_conversion', flat=True).distinct()] SPENDSTATUS = [(i,i) for i in SpendStatusChoice.objects.values_list('spendStatus', flat=True).distinct()] SPENDTYPE = [(i,i) for i in SpendTypeChoice.objects.values_list('spendType', flat=True).distinct()] MONTHS = [(1, 'Jan'), (2, 'Feb'), (3, 'Mar'), (4, 'Apr'), (5, 'May'), (6, 'Jun') ,(7, 'Jul'), (8, 'Aug'), (9, 'Sep'), (10, 'Oct'), (11, 'Nov'), (12, 'Dec')] … -
Django/admin form: how to initialize data with username (access to request object)?
I want to cutsomize admin forms but I am lost below my code I want to initialize pro_log with username of user connected but failed to access request object Which method I should overide and how can I get request object I've read I should override save_model or save_form methods of Modeladmin that return object but how to do that to get access to user in ModelForm? class ProjetFormAdmin(forms.ModelForm): OUINON = Thesaurus.options_list(1,'fr') pro_nom = forms.CharField(label="Nom du projet") pro_log = forms.CharField(label="Log utilisateur", initial='') pro_act = forms.TypedChoiceField(label="Projet en cours ?", widget = forms.Select, choices = OUINON, required=False, empty_value=None) class ProjetAdmin(SimpleHistoryAdmin): list_display = ('pro_nom','pro_log', 'pro_act',) form = ProjetFormAdmin -
Django transactions: how to run lots of sql query in the save mehod
I want to save more them 100 rows in my MySQL database, I have seen that experienced people are saying to use Django transactions. I'm using Django 3, wanted to know how to rite it and any resource that can help. in my views.py I have used from Django.db import transaction D is small in the code @transaction.commit_manually def single_user_images(request, *args, **kwargs): if request.method == 'GET' and username: # I want to save the details here # Receive the data else: #code Please describe with an example if u have. Thanks. -
Django 2.0.13 -> 2.1 upgrade causes std library function to not find module (AttributeError)
Upgrading Django 2.0.13 -> 2.1.0 (or greater) causes the following error when calling runserver, migrate etc. On Django 2.0.13 (and any lower) does not throw this error. Traceback (most recent call last): File "/usr/lib/python3.6/logging/config.py", line 390, in resolve found = getattr(found, frag) AttributeError: module 'mysite' has no attribute 'mymodule' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/logging/config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib/python3.6/logging/config.py", line 715, in configure_handler klass = self.resolve(cname) File "/usr/lib/python3.6/logging/config.py", line 393, in resolve found = getattr(found, frag) AttributeError: module 'mysite' has no attribute 'mymodule' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/me/mysite/manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/home/me/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/me/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/me/venv/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/me/venv/lib/python3.6/site-packages/django/utils/log.py", line 76, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python3.6/logging/config.py", line 802, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python3.6/logging/config.py", line 573, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'console': module 'mysite' has no attribute 'mymodule' This error is thrown in class BaseConfigurator(object): The same issue is also with python3.8 Tracing the error to settings.py -> LOGGING LOGGING … -
django construct condition in save model
I have Contact model and I want to construct it to have only 1 record with field is_active=True. but I don't want to raise error, I want it to notify me and don't save the record if there is an contact record with is_active=True before. "Contact can't have more than 1 active contact at same time." class Contact(models.Model): name = models.CharField(max_length=30) is_active = models.BooleanField(blank=True) def save(self, *args, **kwargs): if self.is_active: if Contact.objects.filter(Q(is_active=True), ~Q(id=self.id)): // raise ValidationError("Contact can't have more than 1 active contact at same time.") return super(Contact, self).save(*args, **kwargs) -
How can I store my static files to some other github repo?
I am doing a Django Project and I want to store some files (which should be accessible from the project w,r) to some github project as I don't want to store the files and the projects in the same repo. Any suggestion of doing that? -
Django IntegrityError: Key is not present in table (but query of key works)
I have a strange problem with Django tests. The issue only occurs when I ran the test command python3 manage.py test. Background information: I have a subscription model with a custom save method which sends info mails, create bills and lessons and more. After the subscription is saved into the database with the super().save(using=using, *args, **kwargs) command, the method self.create_lessons() get's called and this method causes the IntegrityError on creation of the lessons, saying that the subscription doesn't exists in the table. To check if the subscription really doesn't exists in the subscription table I have added a query s = Subscription.objects.get(id=self.id) and printed it to the console print(s). The query and the print command are working fine, but i still get the integrity error. Whats really confusing, at least for me, is that the error only occurs when I run the python3 manage.py test command. When I run the webserver and create subscriptions with the admin panel or the shell everything is running like it should. Even stranger is that the error disappears for a while (2-3 successful executions of the test command) when I make a change to the code which doesn't really matter. For example a comment … -
Couldnt spawn debuggee: embedded null byte error
I'm developing a Django project. When I try to debug this project via VS Code, I get the following error. E+00000.046: /handling #1 request "launch" from Adapter/ Handler 'launch_request' (file '/Users/dervisoglu/.vscode/extensions/ms-python.python-2020.5.86806/pythonFiles/lib/python/debugpy/wheels/debugpy/launcher/../../debugpy/launcher/handlers.py', line 18) couldn't handle #1 request "launch" from Adapter: Couldn't spawn debuggee: embedded null byte How can I sollve this error ? -
Call popup delete modal using django DeleteView()
I am trying pop up delete message using bootstrap4 modal. But the page is loading as a normal page not a modal form.The modal is in employee_delete.html file and modal trigger button is in employee_list.html file. Somehow i think my javascript is not working. employee_list.html: the modal delete button is in this html file {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <!-- Table header--> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Department</th> <th>Designation</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Actions</th> </tr> </thead> <tbody> <!-- Loop for showing employee list in a table--> {% for employee in employees %} <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> <td>{{employee.e_id}}</td> <td>{{employee.first_name}}</td> <td>{{employee.last_name}}</td> <td>{{employee.department}}</td> <td>{{employee.designation}}</td> <td>{{employee.email}}</td> <td>{{employee.address}}</td> <td>{{employee.phone_number}}</td> <td> <a href="{% url 'employee:employee-update' employee.id %}" class="edit" data-toggle="modal"> <i class="material-icons" data-toggle="tooltip" title="Edit"></i> <span data-feather="edit-2"></span> </a> <a href="{% …