Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to use JQuery to fill out a form
I am working on a django project that shows a list of meals on the home page. Below each meal I want to include an order button that pulls up a popup field to enter the amount of orders for that meal you would like to place and then on clicking 'OK' submits a form that creates an order object. Image of List of Meals Currently, if you click on the button it creates an order where the number of meals ordered is 1. View def add_order(request, meal_slug, meal_restaurant, amount): meal = Meal.objects.get(slug=meal_slug, restaurant_slug=meal_restaurant) user = UserProfile.objects.get(user=request.user) order = Order.objects.create(meal=meal, customer=user, amount=amount, date=datetime.now()) order.save() return index(request) Html <ul class="list-group"> <li class="list-group-item">{{ meal.meal_name }}</li> <li class="list-group-item">{{ meal.description }}</li> <button class="order"><a href="{% url 'food_cloud:add_order' meal.slug meal.restaurant_slug %}">Order</a></button> </ul> JQuery $(document).ready(function() { $(".order").click(function() { var amount = parseInt(prompt("Please enter amount of orders" ,"0")) if (amount <= 0) { alert("Please enter integer greater than 0") } else { $.ajax({ url: "{% url 'food_cloud:add_order' meal.slug meal.restaurant_slug amount %}", type: "POST", }) } }) }) -
Uploading a signature with Django
I'm trying to create a signature field that will relate back to a model in django. I scoured everywhere and was finally able to get a jquery signature canvas within my project. But being that I know very little about jquery, I'm not sure how to get the created signature instance to tie to the model and upload directly to the media cdn. Right now I can upload a file, and I can save a signature to my local machine. But I can't do them together. Current html output GUI with form and signature class SigninForm(forms.ModelForm): class Meta: model = Attendance fields = ('schedule', 'time_punch', 'signature', ) // using <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script> var clockinSignature = "{{ schedule.date|date:"ydm"}}{{ schedule.kid.account }}{{ schedule.kid|cut:" " }}-in.jpg" var clockoutSignature = "{{ schedule.date|date:"ydm"}}{{ schedule.kid.account }}{{ schedule.kid|cut:" " }}-out.jpg" var wrapper = document.getElementById("signature-pad"); var clearButton = wrapper.querySelector("[data-action=clear]"); var saveJPGButton = wrapper.querySelector("[data-action=save-jpg]"); var canvas = wrapper.querySelector("canvas"); var signaturePad = new SignaturePad(canvas, { backgroundColor: 'rgb(255, 255, 255)' }); function resizeCanvas() { var ratio = Math.max(window.devicePixelRatio || 1, 1); canvas.width = canvas.offsetWidth * ratio; canvas.height = canvas.offsetHeight * ratio; canvas.getContext("2d").scale(ratio, ratio); signaturePad.clear(); } window.onresize = resizeCanvas; resizeCanvas(); function download(dataURL, filename) { if (navigator.userAgent.indexOf("Safari") > -1 && navigator.userAgent.indexOf("Chrome") === -1) { window.open(dataURL); … -
Error loading psycopg2 module: No module named 'psycopg2'
I am working on window 10. enter image description hereI am facing "psycopg2 module finding error" I install "pip install psycopg2" and "pip install psycopg2_binary" But when i run server i got this error "Error loading psycopg2 module: No module named 'psycopg2'" -
Python - How can we speed this up without modifying the body of the get_resource_identifier function
Suppose the get_resource_identifier function interrogates some cloud infrastructure to resolve the resource identifier from its name. Note that it takes a long time for the call to finish resolving the name. Now imagine that we need to resolve the resource by its name multiple times during deployment of infrastructure. How can we speed this up without modifying the body of the get_resource_identifier function? Remember, you have no control over how quickly the cloud provider can respond to your API call. import time def get_resource_identifier(name): time.sleep(1)#simulate the delay if name is 'foo': return 'L9UKvnomjq' if name is 'bar': return '7U9eyOv7M' return 'Not found' for _ in range(0,100): print(get_resource_identifier('foo')) print(get_resource_identifier('bar')) print(get_resource_identifier('foo')) print(get_resource_identifier('zoo')) print(get_resource_identifier('bar')) -
Django Rest FrameWork Add Model With User Foreign Key
I'm using Django version 3 and the Rest Framework, i have a model with a user foreignkey. so every time a model is saved the user also need to be saved. To be able to add or to edit a model via rest you need to be authenticated using token authentication. I'm using ClassBasedViews, the problem is that i can't find a way to add a model because in my serializer the field user is excluded because i don't want it to be editable. models.py: class Chambre(models.Model): local_id=models.PositiveIntegerField(unique=True) nom=models.CharField(max_length=255) user=models.ForeignKey(User,on_delete=models.CASCADE,blank='true') class Meta: unique_together = ('local_id', 'user',) serializers.py: class ChambreSerializer(serializers.ModelSerializer): class Meta: model = Chambre exclude =['user',] views.py: class ChambreListApi(APIView): """ List all chambres, or create a new chambre. """ authentication_classes=(TokenAuthentication,) permission_classes=(IsAuthenticated,) def get(self, request, format=None): chambres = Chambre.objects.filter(user=request.user) serializer = ChambreSerializer(chambres, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ChambreSerializer(data=request.data) if serializer.is_valid(): serializer.save(commit=False) serializer.user=request.user serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Email for verification before login or create a new account
I need help with a django code that I am developing for django webapp. I need to create a code so that on the login page a box appears where we put the email and it sends an account verification email before logging in or a new registration. Does anyone have any idea how this code is developed? Below I send an example that I try to explain what I need. thanks enter image description here -
I get "TypeError: __init__() got an unexpected keyword argument 'attrs' " when I execute the below code
I get a type error when my form tries to execute username = forms.CharField(label='User name', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(widget=forms.EmailField(attrs={'class': "form-control my-input"}), label="Enter Email") password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control my-input"}), label="Enter Password",) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': "form-control my-input"}), label="Confirm Password") -
Displaying objects by categories in Django
I'm building an ecommerce app and I'd like to make a section that shows some featured items by category. I'm using three sliders that display those items; Each slider is a featured category and each item in the slider is a featured item. The problem is that I can't figure out how to assign the item to the proper slider. For example: I want to assign a JeansJacket to "Clothes and accesories" and display it. I tried this: {% for cat in categories %} <h1>{{ cat.cat_name }}</h1> <!--(carousel code in between)--> <div class="carousel-inner" role="listbox"> {% for item in featured_items %} {% if item.Categoría in cat.cat_name %} {{ item }} {% endif %} This is a simplified version of what I have, without the rest of the content. I just can't figure out how to iterate though the featured items and display them in the corresponding category. -
how can i slice a list with override save models.py [:2]
how can i slice a list with override save models.py i also used this code in models.py field this code is working but slicing [:2] def save(self, *args, **kwargs): if self.featured == True: Article.status_objects.filter(featured=True).update(featured=False) self.featured = True super(Article, self).save(*args, **kwargs) when i try to slice list with override save method my server get error 'int' object is not subscriptable i want something like this models.py def save(self, *args, **kwargs): if self.featured == True: Article.status_objects.filter(featured=True).update(featured=False)[:2] self.featured = True super(Article, self).save(*args, **kwargs) views.py articles = Article.status_objects.filter(tags__exact='1', featured=True)[:2] articleslist = Article.status_objects.filter(tags__exact='1').exclude(featured=True)[:4] -
Adding a user through Django Admin: "Please correct the error below" validation error on the E-mail field
I have tried the solutions in the other 2 questions that I found on stackoverflow, but they did not work, so I have to post the same questions again with my code: admin.py from django.contrib.auth.admin import UserAdmin as BaseUserAdmin class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserProfileChangeForm add_form = UserProfileForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'is_admin', 'is_staff',) list_filter = ('englishinterest_id', 'planchoice_id', 'is_staff',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, {'fields': ('email', 'password1', 'password2')}), ('Personal Information', {'fields': ( 'is_active', 'english_interest', 'plan_choices', 'first_name', 'last_name', 'age', 'location')}), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () Managers.py class UserProfileManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def _create_user(self, email, password, **extra_fields): """ Create and save a user with the given email, and password. """ if not email: raise ValueError('The given email must be … -
Django Firebase check if user is logged in
I'm trying to check if the user is logged into firebase in Django by requesting the session_uid in the home.html file. Which seems not to be working. How can I check if the firebase user is logged in? def login(request): if request.method == 'POST': form = UserLoginForm(request.POST) if form.is_valid(): # form.save() email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = auth.sign_in_with_email_and_password(email, password) session_id = user['idToken'] request.session['uid'] = str(session_id) messages.success(request, f'Account created for {email}!') return redirect(request, 'blog-home') else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form, 'title': 'Login'}) home.html {% extends "home/base.html" %} --> {% block content %} {% if request.session.session_id %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted }}</small> </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% else %} <h2>You need to login</h2> {% endif %} {% endblock content %} -
Uploading files in Django using jQuery
I am trying to upload multiple files for a blog post object, however, it seems that my Ajax form is not working properly and I cannot see the files uploading. Since there is no post object at the time of creating the images, I am trying to upload the files then get them in my view and after saving the post I am trying to save those files by assigning the id of that post to them. Currently, my issue is it seems my files are not uploading and I cannot get them at all. I am not getting any error and therefore, I cannot find an issue. Below is my file upload and post create view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for image in request.FILES.getlist('file'): instance = Images(post=Post.objects.get(post.id),image=image) instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) class PostImageUpload(LoginRequiredMixin, View): def get(self, request): images = Images.objects.all() return render(self.request, 'home/posts/post_create.html', {'images':images} ) def post(self, request): data = dict() … -
How to modify an uploaded file in a django model
I have a model that accepts a file to upload. I need to do some processing on the file before it is saved: 1. generate a thumbnail image and save that in another file field 2. create an image of a certain size and type and save that image in another file field 3. optionally save the original image in a third file field I have accomplished 1 & 2, but not 3, and I get an unexpected result. My model: class Document(Model): document_id = models.AutoField(primary_key=True) storage_file_name = models.FileField('File name', upload_to=unique_file_path_2) thumb_file = models.FileField("thumb", upload_to=settings.DOCUMENT_FOLDER_THUMB, default=settings.DEFAULT_THUMBNAIL) xxxlarge_file = models.FileField('xxxlarge', upload_to=settings.DOCUMENT_FOLDER_XXXLARGE, default=settings.DEFAULT_THUMBNAIL) and the upload_to function: def unique_file_path_2(instance, filename): temp_image = BytesIO() image = None default_thumb = None default_file = None f = None try: #fred = 3/0 # to test the exception path pages = wImage(blob = instance.storage_file_name) first_page = pages.sequence[0] image = wImage(first_page) image.transform(resize=settings.DOCUMENT_XXXLARGE_WIDTH.split("px")[0]) image.format = "png" image.save(temp_image) temp_image.seek(0) file_name, extension = os.path.splitext(filename) instance.xxxlarge_file.save(file_name + ".png", ContentFile(temp_image.read()), save=False) # make a thumbnail image_processing_utils.make_thumb(instance, filename) except: # save default images instead of the uploaded image logger.exception("unique_file_path_2 Exception") default_image = settings.DEFAULT_IMAGE_NAME.replace("size", "xxxlarge") default_image_path = os.path.join(settings.DEFAULT_IMAGE_PATH, default_image) f = open(default_image_path, 'r+b') default_file = File(f) instance.xxxlarge_file.save(default_image, default_file, save=False) f = open(settings.DEFAULT_THUMBNAIL, 'r+b') default_thumb … -
Loop Through API with Djano
I am trying to loop through this data via Django. The data was able to show using {{ globaldata.data }} in my Django Template. By then, I can view details as per the Date. data.json {"data":[{"1/22/20":{"confirmed":555,"deaths":17,"recovered":28}},{"1/23/20":{"confirmed":654,"deaths":18,"recovered":30}},{"1/24/20":{"confirmed":941,"deaths":26,"recovered":36}},{"1/25/20":{"confirmed":1434,"deaths":42,"recovered":39}},{"1/26/20":{"confirmed":2118,"deaths":56,"recovered":52}},{"1/27/20":{"confirmed":2927,"deaths":82,"recovered":61}},{"1/28/20":{"confirmed":5578,"deaths":131,"recovered":107}},{"1/29/20":{"confirmed":6166,"deaths":133,"recovered":126}},{"1/30/20":{"confirmed":8234,"deaths":171,"recovered":143}},{"1/31/20":{"confirmed":9927,"deaths":213,"recovered":222}},{"2/1/20":{"confirmed":12038,"deaths":259,"recovered":284}},{"2/2/20":{"confirmed":16787,"deaths":362,"recovered":472}},{"2/3/20":{"confirmed":19881,"deaths":426,"recovered":623}},{"2/4/20":{"confirmed":23892,"deaths":492,"recovered":852}},{"2/5/20":{"confirmed":27635,"deaths":564,"recovered":1124}},{"2/6/20":{"confirmed":30794,"deaths":634,"recovered":1487}},{"2/7/20":{"confirmed":34391,"deaths":719,"recovered":2011}},{"2/8/20":{"confirmed":37120,"deaths":806,"recovered":2616}},{"2/9/20":{"confirmed":40150,"deaths":906,"recovered":3244}},{"2/10/20":{"confirmed":42762,"deaths":1013,"recovered":3946}},{"2/11/20":{"confirmed":44802,"deaths":1113,"recovered":4683}},{"2/12/20":{"confirmed":45221,"deaths":1118,"recovered":5150}},{"2/13/20":{"confirmed":60368,"deaths":1371,"recovered":6295}},{"2/14/20":{"confirmed":66885,"deaths":1523,"recovered":8058}},{"2/15/20":{"confirmed":69030,"deaths":1666,"recovered":9395}},{"2/16/20":{"confirmed":71224,"deaths":1770,"recovered":10865}},{"2/17/20":{"confirmed":73258,"deaths":1868,"recovered":12583}},{"2/18/20":{"confirmed":75136,"deaths":2007,"recovered":14352}},{"2/19/20":{"confirmed":75639,"deaths":2122,"recovered":16121}},{"2/20/20":{"confirmed":76197,"deaths":2247,"recovered":18177}},{"2/21/20":{"confirmed":76819,"deaths":2251,"recovered":18890}},{"2/22/20":{"confirmed":78572,"deaths":2458,"recovered":22886}},{"2/23/20":{"confirmed":78958,"deaths":2469,"recovered":23394}},{"2/24/20":{"confirmed":79561,"deaths":2629,"recovered":25227}},{"2/25/20":{"confirmed":80406,"deaths":2708,"recovered":27905}},{"2/26/20":{"confirmed":81388,"deaths":2770,"recovered":30384}},{"2/27/20":{"confirmed":82746,"deaths":2814,"recovered":33277}},{"2/28/20":{"confirmed":84112,"deaths":2872,"recovered":36711}},{"2/29/20":{"confirmed":86011,"deaths":2941,"recovered":39782}},{"3/1/20":{"confirmed":88369,"deaths":2996,"recovered":42716}},{"3/2/20":{"confirmed":90306,"deaths":3085,"recovered":45602}},{"3/3/20":{"confirmed":92840,"deaths":3160,"recovered":48228}},{"3/4/20":{"confirmed":95120,"deaths":3254,"recovered":51170}},{"3/5/20":{"confirmed":97886,"deaths":3348,"recovered":53796}},{"3/6/20":{"confirmed":101801,"deaths":3460,"recovered":55865}},{"3/7/20":{"confirmed":105847,"deaths":3558,"recovered":58358}},{"3/8/20":{"confirmed":109821,"deaths":3802,"recovered":60694}},{"3/9/20":{"confirmed":113590,"deaths":3988,"recovered":62494}},{"3/10/20":{"confirmed":118620,"deaths":4262,"recovered":64404}},{"3/11/20":{"confirmed":125875,"deaths":4615,"recovered":67003}},{"3/12/20":{"confirmed":128352,"deaths":4720,"recovered":68324}},{"3/13/20":{"confirmed":145205,"deaths":5404,"recovered":70251}},{"3/14/20":{"confirmed":156101,"deaths":5819,"recovered":72624}},{"3/15/20":{"confirmed":167454,"deaths":6440,"recovered":76034}},{"3/16/20":{"confirmed":181574,"deaths":7126,"recovered":78088}},{"3/17/20":{"confirmed":197102,"deaths":7905,"recovered":80840}},{"3/18/20":{"confirmed":214821,"deaths":8733,"recovered":83312}},{"3/19/20":{"confirmed":242500,"deaths":9867,"recovered":84975}},{"3/20/20":{"confirmed":272035,"deaths":11299,"recovered":87420}},{"3/21/20":{"confirmed":304396,"deaths":12973,"recovered":91692}},{"3/22/20":{"confirmed":336953,"deaths":14651,"recovered":97899}},{"3/23/20":{"confirmed":378235,"deaths":16505,"recovered":98351}},{"3/24/20":{"confirmed":418045,"deaths":18625,"recovered":108000}},{"3/25/20":{"confirmed":467653,"deaths":21181,"recovered":113787}},{"3/26/20":{"confirmed":529591,"deaths":23970,"recovered":122150}},{"3/27/20":{"confirmed":593291,"deaths":27198,"recovered":130915}},{"3/28/20":{"confirmed":660706,"deaths":30652,"recovered":139415}},{"3/29/20":{"confirmed":720117,"deaths":33925,"recovered":149082}},{"3/30/20":{"confirmed":782365,"deaths":37582,"recovered":164566}}],"dt":"2020-03-30 22:58:55","ts":1585609135.0} -
Django send_mail raising error " 'ascii' codec can't encode characters"
Created web app with Django and one of the functions is to send notifications through email to people who pass the test.So in my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'did****@gmail.com' DEFAULT_FROM_EMAIL = 'did****gmail.com' EMAIL_HOST_PASSWORD = '*************' EMAIL_USE_TLS = True Here in my views.py I have a method for sending notifications through email def recrutesdetails(request, id, Pid): ... if request.method == "POST": sith.resrutesShadowing.add(recruter) sith.save() message = 'duck' subject = 'duck' safe_str = smart_str(message) safe_sub = smart_str(subject) recipientlist = smart_str(recruter.planetRecruteEmail) send_mail(safe_sub, safe_str, from_email = smart_str(settings.DEFAULT_FROM_EMAIL),recipient_list=[recipientlist,] , fail_silently=False) return HttpResponseRedirect(reverse( 'recruters', args=[Pid])) return render(request,'app/recrutdetail.html', {'recruter': recruter, 'recrList': recrList, 'wrongList': wrongList}); I've tried to encode messages and email adresses with: message.encode("ascii", errors="ignore") message.encode('utf-8') smart_str() But nothing seems to work and error raised by my send_mail() function which envokes other django lib functions: C:\Users\user..\__init__.py in send_mail return mail.send() ... C:\Users\user...\message.py in send return self.get_connection(fail_silently).send_messages([self]) ... C:\Users\user...\smtp.py in send_messages new_conn_created = self.open() ... C:\Users\user...\smtp.py in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) ... C:\Users\user...\smtplib.py in starttls self.ehlo_or_helo_if_needed() ... C:\Users\user...lib\smtplib.py in ehlo_or_helo_if_needed if not (200 <= self.ehlo()[0] <= 299): ... C:\Users\user..\lib\smtplib.py in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) ... C:\Users\..\Python\Python35\lib\smtplib.py in putcmd self.send(str) ... and I tracked it till: C:\Users\user\AppData\Local\Programs\Python\Python35\lib\smtplib.py in send **s = s.encode(self.command_encoding) … -
Django formset creates multiple inputs for multiple image upload
I am trying to create a simple post sharing form like this one. I'm using formset for image upload. But this gives me multiple input as you can see. Also each input can choose single image. But I'm trying to upload multiple image with single input. views.py def share(request): ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=3) # 'extra' means the number of photos that you can upload ^ if request.method == 'POST': postForm = PostForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if postForm.is_valid() and formset.is_valid(): post = postForm.save(commit=False) post.author = request.user post.save() for form in formset.cleaned_data: # this helps to not crash if the user # do not upload all the photos if form: image = form['image'] photo = Images(post=post, image=image) photo.save() return redirect("index") else: print(postForm.errors, formset.errors) else: postForm = PostForm() formset = ImageFormSet(queryset=Images.objects.none()) return render(request, "share.html", {"postForm": postForm, 'formset': formset}) share.html <form method="POST" id="post-form" class="post-form js-post-form" enctype="multipart/form-data"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} </form> if you need, forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content"] def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'input'}) self.fields['content'].widget.attrs.update({'class': 'textarea'}) class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Images … -
Is there a way to test Django project creation with pytest/Django test suite?
I created a Django plugin system which creates some boilerplate code. It can be used in any Django project (GDAPS), and provides a few management commands. What is the best way to test this whole suite? I mean, I can create bash scripts that setup fake Django projects which include my project, and then call all the management commands like makemigrations, migrate etc. to set it up fully, call my special commands (./manage.py initfrontend) and check if the results created the right files correctly. Now bash scripts are not my favourite testing suite, I'd keep with python and pytest if possible. Is there a way to test things like that? How can I start here - I can't wrap my head around this. I have already written plenty of unit tests for various features of the framework, but these tests are alike integration tests. Thanks for your help. -
Django WSGI Apache/WAMP on Windows - ACCESS DENIED
I am facing a strange 403 while accesing my app, [authz_core:error] [pid 11736:tid 1328] [client ::1:55552] AH01630: client denied by server configuration: .../mysite/mysite/wsgi_windows.py, referer: http://localhost/mescarator. My conf quite straight forward; ServerName localhost DocumentRoot "D:/DevRoot/py/MescaratorReconcilator/mysite" WSGIPassAuthorization Off ErrorLog "D:/DevRoot/py/MescaratorReconcilator/mysite/apache.error.log" CustomLog "D:/DevRoot/py/MescaratorReconcilator/mysite/apache.access.log" combined WSGIScriptAlias / "D:/DevRoot/py/MescaratorReconcilator/mysite/mysite/wsgi_windows.py" Require all granted I am surely missing something basic, tried disabling auth from apache. But without any sucess. Thank you for your help/ BR Es/ -
When I try to migrate I get this : django.db.utils.DataError: integer out of range ? Django 1.11.28
I did makemigrations in my Django project then tried to migrate. I got this. I don't know where it is coming from. Applying shop.0002_auto_20200302_2309... OK Applying shop.0003_auto_20200304_1458... OK Applying shop.0004_auto_20200331_1522...Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 88, in database_forwards field, File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 445, in add_field self.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 136, in execute cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.DataError: integer out of range I don't know how to solve this error. Anyone? -
uWSGI and Django setup error: No module name Django
I have developed a Django RestFramework API which is basically a GET request to get a prediction from an already saved ML model. For deployment, I thought of using Ngnix and uWSGI. I have never used these 2 tools before and I was having some difficulty in installing uWSGI through pip as it doesn't support windows. The solution is to install it through 'Cygwin'. When I am running standalone Django application it's running fine. But when I am trying through uWSGI I am getting the following error: Traceback (most recent call last): File "C:/VirtualEnvs/predenv/Predictor/Predictor/wsgi.py", line 12, in from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' The command I am using is: uwsgi --http :8070 --chdir C:/VirtualEnvs/predenv/Predictor/Predictor --wsgi-file C:/VirtualEnvs/predenv/Predictor/Predictor/wsgi.py --virtualenv C:/VirtualEnvs/predenv -
Django / Getting incorrect pk for comment
I want to redirect to my post-detail page after entering the comment. In my code it redirects not to Post's pk, but to Comment's pk. Therefore the path brings me to an incorrect place and the page does not exist. models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.content def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) views.py class CommentCreateView(LoginRequiredMixin,CreateView): model = Comment fields = ['content'] def form_valid(self,form): form.instance.author = self.request.user form.instance.post = Post.objects.get(pk=self.kwargs['pk']) return super().form_valid(form) urls.py path('post/new/', PostCreateView.as_view(), name="post-create"), path('post/<int:pk>/', views.post_detail, name="post-detail"), ... -
Ajax xhr onload not being called within django app
I have a Django app with user posts. I am trying to add a 'like' / voting system. I had done this through complete page refreshes through a redirect where the vote was made then redirected back to the same page with the new vote / like total updates. I then was reading about ajax and how I could update part of a page without a full reload. let up_vote = document.getElementById("up-vote").addEventListener('click', () => { console.log("clicked"); let xhr = new XMLHttpRequest(); xhr.open('GET', "{% url 'up-vote' %}", true); console.log(xhr); xhr.onload = () => { console.log("inside"); }; console.log("outside"); }); So far my js looks like this. When I click on "up-vote", "clicked" is printed along with the xhr object. However, onload appears to never be called as "inside" is never printed but instead passes straight over to "outside". I have a feeling that the issue is to do with the URL path but I don't know how to get path properly. The basic file structure of this app is: app |-static/app |-scripts/*this js file*/ |-images |-styles |-templates/app |-html files |-views.py *where the request is being made* |-urls.py urls.py contains, urlpatterns = [ ... path('post/<int:pk>/up/', up_vote, name='up-vote'), ... ] and the views.py contain, … -
How to sum data from an annotated query
I'm trying to create a report that shows the number of males, females, and total customers in a given day by hour. The data is inserted into the database as a transaction whenever somebody enters the building. It stores their gender there. The query to gather the data looks as follows: initial_query = EventTransactions.objects.using('reportsdb') .filter(building_id=id, actualdatetime__lte=end_date, actualdatetime__gte=beg_date) From there, I annotate the query to extract the date: ordered_query = initial_query.annotate( year=ExtractYear('actualdatetime'), month=ExtractMonth('actualdatetime'), day=ExtractDay('actualdatetime'), hour=ExtractHour('actualdatetime'), male=Coalesce(Sum(Case(When(customer_gender='M', then=1)), output_field=IntegerField()), Value(0)), female=Coalesce(Sum(Case(When(customer_gender='F', then=1)), output_field=IntegerField()), Value(0)) ).values( 'year', 'month', 'day', 'hour', 'male', 'female' ) How do I then sum the male customers and female customers by hour? I'd be happy to provide more information if necessary. Thank you! -
How to define permissions based on a model field in Django 2.2/Python 3.5
I have a custom user model with a field that defined the user level. I'd like to use this field to restrict certain views/API endpoints and other functionality. I.e. for Class-Based views or URL routes, how can I use this property i.e. if user is logged in and is_end_user, then don't allow access to CBV 1, and similar logic? The roles here, i.e. Admin are not the same as a superuser, so none of these have access to the Django admin backend, but I want to make separate "admin" views/panels for different user groups - also the API should only be accessible by users that are id_end_user == True. I'm using Django 2.2 and Python 3.5 Model definition: class AppUser(AbstractBaseUser, PermissionsMixin): [...] USER_TYPE_CHOICES = ( (1, 'appuser'), (2, 'moderator'), (3, 'intern'), (4, 'admin'), ) [...] def _get_user_type(self): return self.user_type @property def is_end_user(self): if (self._get_user_type() is 1): return True else: return False [...] -
Django decorator_from_middle type_error
I am trying to exclude middle ware from some of the views in Django and I got the problem. This is the class of middleware class JWTAuthorisation(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # before view token = request.headers.get('x-auth-token') if not token: return HttpResponse("No access token provided", status=401) response = self.get_response(request) return response I am using this @ to exclude the view @decorator_from_middleware(JWTAuthorisation) def register(request): if request.method == "POST": This is the error File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\LoreProject\users\urls.py", line 3, in <module> from users import views File "E:\LoreProject\users\views.py", line 75, in <module> @decorator_from_middleware(JWTAuthorisation) File "E:\LoreProject\venv\lib\site-packages\django\utils\decorators.py", line 111, in decorator_from_middleware return make_middleware_decorator(middleware_class)() File "E:\LoreProject\venv\lib\site-packages\django\utils\decorators.py", line 116, in _make_decorator middleware = middleware_class(*m_args, **m_kwargs) TypeError: __init__() missing 1 required positional argument: 'get_response'