Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to develop my simple booking system in django right
I really need help, can someone please guide me on how to develop a really really simple booking system in django? models.py class Listing(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=755) price = MoneyField(max_digits=5, decimal_places=3) # avail_days = models.ForeignKey(Days, on_delete=models.CASCADE) def __str__(self): return self.title class Booking(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) listing = models.OneToOneField(Listing, on_delete=models.CASCADE) # day = models.OneToOneField(Days, on_delete=models.CASCADE) date_booked = models.DateField(auto_now_add=True) def __str__(self): return self.user.username please can someone help me develop the views.py? how would this go? thanks, I'd appreciate it. -
Mailchimp bulk mail to audience from Django
I have a Mailchimp account with some audiences on it, my question is how can I send mail to all subscribers of a given audience using API from Django? I'm using mailchipm3 library to add subscribers to the audience and it works, I can even log into Mailchimp, create a campaign and send it to the audience, but I cannot find how to send a pre-elaborated mail to that audience via API Any help will be appreciated, thanks in advance! -
Django Chroniker disconnects with Database after continuous operation
Please checkout the stack trace below. This is a very weird problem. Chroniker is running as a command under 'supervisor script'. It needs a process restart after every 2-3 days to keep working else it freezes and starts throwing the below error. The database was completely operational at the time and used by other processes in the normal fashion. ` [2020-06-03 01:57:16] Running due jobs... Exception in thread Thread-5007: Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/hooks/database_dbapi2.py", line 101, in call *args, **kwargs), self._nr_dbapi2_module, (args, kwargs)) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "xxxxxxxxx.rds.amazonaws.com" to address: System error 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 "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/chroniker/management/commands/cronserver.py", line 19, in run call_command('cron') File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/core/management/init.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/packages/wrapt/wrappers.py", line 508, in call args, kwargs) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/newrelic/api/function_trace.py", line 104, in literal_wrapper return wrapped(*args, **kwargs) File "/home/ubuntu/.virtualenvs/C24Vajra/lib/python3.6/site-packages/chroniker/management/commands/cron.py", … -
Django webp converter tag static_webp not working
I installed the webp_converter package at documented Here {% load webp_converter %} This is not working which I want to add static_webp <img src="{% static_webp 'modelImage.url' %}"> This is working fine <img src="{{ modelImage.url }}"> From Official Doc says <img src="{% static_webp 'img/hello.jpg' %}"> -
Django REST framework - "Method \"GET\" not allowed." -
In creating Django REST framework, i'll get all the data using this code views.py @api_view(['GET', ]) def api_detail_educationlevel(request): if request.method == 'GET': educationlevel = EducationLevel.objects.all() serializer = EducationLevelSerializer(educationlevel, many=True) return Response(serializer.data) urls.py path('api/', views.api_detail_educationlevel), but when i add in my views.py like this @api_view(['PUT', ]) def api_update_educationlevel(request, pk): try: educationlevel = EducationLevel.objects.get(pk=pk) except EducationLevel.DoesNotExist: return HttpResponse(status=404) if request.method == 'PUT': serializer = EducationLevelSerializer(educationlevel, data=request.data) data = {} if serializer.is_valid(): serializer.save() data["success"] = "update successfull" return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE', ]) def api_delete_educationlevel(request, pk): try: educationlevel = EducationLevel.objects.get(pk=pk) except EducationLevel.DoesNotExist: return HttpResponse(status=404) if request.method == 'DELETE': operation = educationlevel.delete() data ={} if operation: data["success"] = "delete successfull" else: data["failure"] = "delete failed" return Response(data=data) @api_view(['POST', ]) def api_create_blog_view(request): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) and in my urls.py urlpatterns = [ path('api/', views.api_detail_educationlevel), path('api/update/', views.api_update_educationlevel), path('api/delete/', views.api_delete_educationlevel), path('api/create/', views.api_create_blog_view), ] urlpatterns = format_suffix_patterns(urlpatterns) I dont know why i am getting this message, in my path('api/update/', views.api_update_educationlevel), in my path('api/delete/', views.api_delete_educationlevel), in my path('api/create/', views.api_create_blog_view), any idea why i am getting this message? i just want functional rest framework that can … -
how to substract two dates in django?
i am trying to subtracts 'end time' of a ride from its 'start time'. starttime is fetched directly from database(models.py) and line 'start = n[0].driverStarttime' indicates that. Now i use current datetime as 'endtime' of a ride. Variable 'diff' is used to subtract end and start time. but it gives 'TypeError at /driver_panel/endtrip can't subtract offset-naive and offset-aware datetimes' error. here driver_panel is my application in project. Driverbooking table is used to fetch start time. DateTimeField is used for store start and endtime. here is the code... def endtrip(request): if request.method == 'GET': dbid = request.GET.get('driverBookID') if dbid: n = Driverbooking.objects.all().filter(driverBookID=dbid) name = n[0].customerID start = n[0].driverStartTime end = datetime.datetime.now() diff = end - start total = diff * 10 a = Driverbooking.objects.get(driverBookID=dbid) a.driverStatus = "end" a.driverEndTime = end a.driverAmount = total a.save() did = request.session['uid'] x = Driverside.objects.all().filter(driverID=did) rate = x[0].driverFPH d = Driverside.objects.get(driverID=did) d.driverIsAvailable = "yes" d.save() context = {"name":name,"start":start,"end":end,"rate":rate,"t":total} return render(request, "driverbill.html", context) return redirect('driverhome') -
Making django web application accessible from other machines without deploying to a cloud
I have a django web application and normally, it works on AWS but one of our customers wants to use this web application on localhost because of the security. Also he wants to use this application with more than one computer on the same host. How to make a roadmap for that without sharing source code? -
What is the right way to link up an app in Django?
I'm somewhat a beginner with Django and I'm wondering why ppl link up apps in settings.py in INSTALLED_APPS in 2 different ways. One is just the name of the application and the other one 'appname.apps.AppnameConfig'. What is the difference between the two? -
Django - Serializing a M2M intermediate model (for POST, PUT and GET requests)
I am trying to include the data from the intermediate model of my M2M field inside my api calls, such that I would get the data from the M2M field in my GET request, and also be able to POST and PUT for that intermediate model when I am doing a POST and PUT request for my base model. Here is my models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) history = HistoricalRecords() class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) customer_information = models.ManyToManyField('CustomerInformation', through='Project_Customer') history = HistoricalRecords() class Project_Customer(models.Model): project = models.ForeignKey('SalesProject', on_delete=models.SET_NULL, null=True) customer = models.ForeignKey('CustomerInformation', on_delete=models.SET_NULL, null=True) history = HistoricalRecords() I am using model viewsets and model serializers for my SalesProject, shown below class SalesProjectViewSet(viewsets.ModelViewSet): serializer_class = SalesProjectSerializer queryset = SalesProject.objects.all() class SalesProjectSerializer(serializers.ModelSerializer): class Meta: model = SalesProject fields = '__all__' How would I be able to get the details of the CustomerInformation tied to the SalesProject instance through the M2M field? When I use this to get data, the SalesProject data only shows the other fields, while missing out the customer field. Also, when I POST data, how can I send both the SalesProject data and the customer instances that I want to link M2M … -
Could Djando admin site build a scheduling system?
Good day! I am a student and I approached a project wrong. I was aiming for a pyhon django scheduling system but what i actually did was a website for only notifyiing a fiven email address for a request about an appointment. I dont have any clue how to integrate what i did to run a scheduling system. I searched any google but i really cannot find any solution. maybe I am asking the wrong question? Could anyone please help me try and resolve my problem? could i still salvage what i worked on? -
How to create a magnifying glass beside a form field in admin change form to run a script
I'd like to put a search icon (like magnifiying glass) beside a field in the admin change form to let the users to trigger a script to fill other fields on demand only. I have to avoid triggering any field event (blur, click, change etc) on this field because it has to be triggered under user request, according to what he/she need. Django has its own magnifying glass icon/link for raw_field foreign key selection popup. Is it possibble to do something similar, where I would trigger the script upon the magnifying glass click. It will be just a JQuery to call a webservice and return values to be filled up on some other fields. I found one working solution by putting a custom button as a field, but it is placed far from the field because its label (what I seems weird for my purpose). Let me know if this description is enough or additional information is needed. example here Tks. -
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.