Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zappa async task not being async
I'm adding a function to send emails from my zappa serverless application The sending mail process can run over the 30 seconds limit of AWS Api Gateway, giving the user a 504 response. So, following the approach on Zappa documentation, I have tried to set an asynchronous execution The code seems to be very simple from zappa.asynchronous import task from django.core.mail import send_mail as django_send_mail @task def send_mail(subject, body, from_email, to_emails): django_send_mail( subject, body, from_email, to_emails, fail_silently=False, ) Then in my function I just call the async function: send_mail( 'My Subject', 'My email body', 'noreply@mydomain.com', [user.email], ) Still, get a 504 I have tried setting it as sns, added to zappa_settings.json then "async_source": "sns", And then on the code: from zappa.asynchronous import task_sns @task_sns def send_mail(subject, body, from_email, to_emails): django_send_mail( subject, body, from_email, to_emails, fail_silently=False, ) Same error Last, I have tried invoking it directly with from django.core.mail import send_mail as django_send_mail enter code herefrom zappa.asynchronous import run def send_mail(subject, body, from_email, to_emails): run( django_send_mail, (subject, body, from_email, to_emails), {'fail_silently': False}, service='sns', ) I also tried removing the service parameter It seems that for some reason, Zappa doesn't understand that this is a lambda environment and run it synchronous? -
concat two {{}} interpoled values
have a valuesthat is sent hidden in a form like this <input class="form-control {% if form.title.errors %}is-invalid{% endif %}" name="name" size="16" type="hidden" value="{{post.user.name}}" > now want to contact two values in the value field value field value="{{post.user.name}}" > and value="{{post.user.lastname}}" > already tried tried with |concat and also tried to merge the strings with + but it didn´t work how i can concat those two string and add a space in the middle ? -
Python django Foreign Key Relationships problem
I am working on an online school project, where I got classes, and in the classes I have different subjects, I added a one-to-many(ForeignKey) Relation between "Classes" and "Subjects", but when it comes the view theme on the HTML page Subjects from 2.Class comes to show on 1.Class one page(all Subjects are showed in one class) How to Fix this problem?? (How to keep 2.Class Subjects in the 2.Class page as well for 1.Class?) MY CODE viws.py def classes(request): classes = Class.objects context={ 'class':classes } return render(request, "templates/Classes.html", context) def subjects(request, sub_id): classes=get_object_or_404(Class, pk=sub_id) subject=Subject.objects.all() context={ 'classes':classes, 'subject':subject } return render(request, "templates/Subjects.html", context) Models.py class Class(models.Model): title=models.CharField(max_length=200) image=models.ImageField(upload_to="images") class Subject(models.Model): title=models.CharField(max_length=2000) Class=models.ForeignKey(Class, on_delete=models.CASCADE) Webpage {%for subject in subject.all%} <div class="cardrow"> <div class="cardcolumn"> <a href="#"> <div class="card"> <h1>{{subject.title}}</h1> </div> </a> </div> </div> {%endfor%} So again all subjects are showing in one class. tho I added a Foreign Key relationship Thanks -
Work with a Django model (table) with an external python script
I am working with django and I have created some models (tables). Working directly on my django project all is ok, I can visualize and modify data with no problems. But when I want to work directly with a Python script out of my Django project, it can't access to the tables, because it says the table doesn't exist. Below I show from the PostgreSQL dashboard one of my tables. How I have to do it, to work with it, in a independent python script? I have done something like this, import psycopg2 # Trabajar con PostgreSQL def bbdd_connect(): con = psycopg2.connect( host = '127.0.0.1', database = 'lorawan_platform_app', user = 'XXX', password = 'XXX', port = 5432 ) # Cursor cur = con.cursor() return con, cur def bbdd_desconnect(con, cur): cur.close() con.close() def add_new_data(): # Establecer conexión con BBDD y generar cursor con, cur = bbdd_connect() # Query - Obtenemos el id mayor junto con su fecha. query = "SELECT data_id, data_timestamp FROM Platform_App_dataerror WHERE data_id = (SELECT MAX(data_id) FROM Platform_App_dataerror);" cur.execute(query) cosa = cur.fetchall() # MIRAR LO DEL DUPLICADO if len(cosa) == 0: params = {'from':'2020-01-01 00:00'} else: params = {'uplink_id_start':cosa[0][0]} # Finalizamos la conexión con la bbdd bbdd_desconnect(con, cur) … -
Any drawbacks to a foreign key pointing to a person, not a user account?
I have a Django application that uses two simple database tables to represent users (I've simplified these a little for brevity): class Person: first_name = models.CharField() last_name = models.CharField() email = models.CharField() class User: person = models.OneToOneField('Person') last_login = models.DateTimeField(blank=True, null=True) roles = models.ManyToManyField('Role', blank=True) I pre-populate the Person table with entries from my corporate Active Directory instance, so that I can quickly reference people in our organization. User model instances are created on an as-needed basis (not every person will necessarily have a User account). This application also has various resources that need an owner (via an "owner" column in the respective tables). For example: class SomeResource: owner = models.ForeignKey('User') # ... [other fields here] ... As you can see in the example, the owner column points at the User model. I would like for the users of my application to be able to assign these resources to the necessary individual, and there is a very-real possibility that that Person's User account has not yet been created. I'm wondering: are there any general drawbacks to pointing ownership columns to the Person model instead? I realize that a few alternatives exist: Create User accounts for all Person records, whether they … -
Django create POST intermediate model
I'm using DRM v3.9.4 and have the following models: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... users = models.ManyToManyField("User", related_name="books", through="BookUser") class BookUser(models.Model): id = models.UUIDField(primary_key=True, editable=False) user = models.ForeignKey("User", on_delete=models.CASCADE) book = models.ForeignKey("Book", on_delete=models.CASCADE) permission = models.CharField(...) class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... with the following serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ( "id", ... ) class BookUserSerializer(ModelSerializer): class Meta: model = BookUser fields = ('user', 'permission') class BookSerializer(ModelSerializer): users = BookUserSerializer(source='bookuser_set', many=True) class Meta: model = Book fields = ( "id", "users", ... ) extra_kwargs = { "users": {"allow_empty": True}, } When reading (GET) a Book everything is fine: { id: ..., users: [ { user: 'some-uuid', permission: 'read-only' }, ... ] } but when trying to POST using the same payload: { id: ..., users: [ { user: 'some-uuid', permission: 'read-only' }, ... ] } I get an error: KeyError: 'users' looking at the api-guide (https://www.django-rest-framework.org/api-guide/relations/) seems that by default nested serializers are read-only, but I can't make it work. BTW, IMPORTANT: all the users are (and should) already exist, so I expect this POST call to add a record in the intermediate BookUser table, and ofcourse the Book itself, … -
Data not inserting in Django Database using Form DTL
Here is my model.py file class TestData(models.Model): test_date = models.DateField(blank=True) test_name = models.CharField(max_length=255) result = models.IntegerField() And here is my forms.py file class TestDataForm(forms.ModelForm): class Meta: model = TestData fields = ['test_date','test_name','result'] And here is my views.py file def photo_single(request): if request.POST: form = TestDataForm(request.POST) if form.is_valid(): if form.save(): return redirect('/', messages.success(request, 'Order was successfully created.', 'alert-success')) else: return redirect('/', messages.error(request, 'Data is not saved', 'alert-danger')) else: return redirect('/', messages.error(request, 'Form is not valid', 'alert-danger')) else: form = TestDataForm() return render(request, 'photo_single.html', {'form':form}) and here is my photo_single.html file <form>{% csrf_token %} <div class="form-row"> <div class="form-group col-md-6"> <label for="date">Date</label> {{ form.test_date | add_class:'form-control' | attr:'type:date' }} </div> <div class="form-group col-md-6"> <label for="test_name">Test Name</label> {{ form.test_name | add_class:'form-control' }} </div> <div class="form-group col-md-6"> <label for="result">Result</label> {{ form.result | add_class:'form-control' }} </div> </div> <button type="submit" class="btn btn-primary" name="data">Submit</button> </form> When I'm submitting value from form to databasw, I'm getting this in url http://127.0.0.1:8000/photo/?test_date=2020-03-13&test_name=SUGAR&result=23&data= and data is not saving in database. Can anyone help me out why ? I'm messed in this. Am I missed something here ? Thanks -
django upload a file from other python script
I want to save file from the client to the django project server's database from a script. I've tried to do this using a model and a view in the django project, and post request in the other python script, but it keeps return 403 error and not save the file and the data to the database. models.py: class ScreenRecord(models.Model): record = models.FileField(default='output.avi', upload_to='records') writeTime = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) views.py: def getscreenrecords(request): user = User.objects.filter(username=request.POST.get('user')).first() k = ScreenRecord(record=request.FILES.get('record'), user=user) k.save() return HttpResponse('success ' + request.GET.__getitem__('user')) python script to send the file: url = 'http://127.0.0.1:8000/send/screenrecords/' files = {'record': open('output.avi','rb')} values = {'user': 'newUser'} r = requests.post(url, files=files, data=values) print(r) what's wrong in my code or is there a way to do this better? -
Django + React : How to connect them for deployment?
I am running an app with Django+DRF, CELERY+REDIS ,ReactJs+REDUX & JWT, and i am having a hard time connecting backend with the frontend for deployment. i have used create-react-app to generate React code; and npm run build to generate the production build. i have been looking around but i can't find a tutorial on how to link them together. if you guys have any link in your pocket that i can follow i'll be thankful to you. -
Import category CSV data django model with child category
class Category(models.Model): parent_category = models.ForeignKey('self',related_name='child_category_list',on_delete=models.SET_NULL,blank=True,null=True) name = models.CharField(max_length=255) cat_id = models.CharField(max_length=255,null=True,blank=True) path = models.TextField(null=True,blank=True) I have category model and numerous category names and ids in csv.Is there any way to import csv data with parent category? Structure is like: -Computers, Tablets & Network Hardware --Computer Parts ---motherboard --laptops ---hp ---dell -
How to extend the reach of the select_related function of Django Queryset so it includes the table related to a table related to the original table
This is what my models.py looks like class Branches(models.Model): def __str__(self): return self.location location = models.CharField(max_length=256, unique=True) class Daily_Infos(models.Model): class Meta: unique_together = ["date", "branch_id"] def __str__(self): return str(self.date) + " " + str(self.branch_id) branch_id = models.ForeignKey(Branches, related_name='daily_info', on_delete=models.CASCADE) date = models.DateField() class Branch_Prices(models.Model): def __str__(self): return str(self.branch_id) + " " + str(self.menu_item_id) + " " + str(self.price) branch_id = models.ForeignKey(Branches, related_name='prices', on_delete=models.CASCADE) menu_item_id = models.ForeignKey(Menu_Items, related_name='prices', on_delete=models.CASCADE) price = models.FloatField() class Sold_Menu_Items(models.Model): def __str__(self): return str(self.branch_price_id) + " " + str(self.daily_info_id) + " " + str(self.quantity) daily_info_id = models.ForeignKey(Daily_Infos, related_name='sold_menu_items', on_delete=models.CASCADE) branch_price_id = models.ForeignKey(Branch_Prices, related_name='sold_menu_items', on_delete=models.CASCADE) quantity = models.IntegerField() class Menu_Items(models.Model): def __str__(self): return str(self.name) + " " + str(self.size) name = models.CharField(max_length=256) size = models.CharField(max_length=64) start_date = models.DateField() is_active = models.BooleanField() In my views.py, I have this function: def view_sold_items_all(request): sold_menu_items = Sold_Menu_Items.objects.select_related('branch_price_id','daily_info_id') refined_sold_menu_items = [] for smi in raw_sold_menu_items: menu_item = [] menu_item.append(smi.daily_info_id.date) menu_item.append(smi.quantity) menu_item.append(smi.branch_price_id.branch_id.location) menu_item.append(smi.branch_price_id.menu_item_id.name) menu_item.append(smi.branch_price_id.menu_item_id.size) refined_sold_menu_items.append(menu_item) return render(request, 'view_all.html', { 'sold_items':refined_sold_menu_items }) Based on my understanding, the code below (which is in my views.py file) will allow Django to query my database only once. sold_menu_items = Sold_Menu_Items.objects.select_related('branch_price_id','daily_info_id') During the for loop, it will not keep querying the database for the two lines: menu_item.append(smi.daily_info_id.date) menu_item.append(smi.quantity) However, … -
Django ORM filter records between last month 15th date to current month 15th date
I want to filter the queryset records from the previous month's 15th date to the current month 15th. Does someone have any idea how to do it? Models.py class Book(models.Model): name = models.CharField(max_length=100, null=True) author = models.CharField(max_length=100, null=True) created_on = models.DateTimeField(auto_now_add=True) Views.py class BookView(View): def get(self, *args, **kwags): start_date = '15th_of_previous_month' end_date = '15th_of_current_month' qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date) ... -
Django how go get all products for the logged in user only?
i have the following code, and when the page is displayed the table shows all products for all users no matter which user is logged in. I want to show in the table only the products that was created by the logged in user only, not from all users. Any help with my issue ? Thank you in advance. views.py @login_required def eadmin(request): transactions = Product.objects return render(request, 'accounts/index.html', {'transactions': transactions}) models.py class Product(models.Model): details = models.CharField(max_length=1000) opname = models.CharField(max_length=100) pub_date = models.DateTimeField() amount = models.IntegerField() contactemail = models.TextField() purpose = models.TextField() poster = models.ForeignKey(User, on_delete=models.CASCADE) transactionid = models.CharField(max_length=6) def __str__(self): return self.transactionid In the html template: <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">XXXXX</th> <th scope="col">Amount €</th> <th scope="col">Transaction ID</th> </tr> </thead> {% for transaction in transactions.all %} <tbody> <tr> <th scope="row">-</th> <td>{{ transaction.opname }}</td> <td>{{ transaction.amount }}</td> <td>{{ transaction.transactionid }}</td> </tr> </tbody> {% endfor %} </table> -
Django Ajax Form submit reloads after "success"
extending from my previous post containing problems with django and ajax (Django Ajax Image submit), I came, as mentioned in the EDIT, to the following situation: My jquery/ajax call: <script> $(document).ready(function () { // This jquery changes the appearance of the django { form_image } var imgElement = $('#id_image'); imgElement.css('visibility', 'hidden'); console.log($('#id_image').attr('type')) // This function triggers the hidden submit, // which triggers the ajax image request imgElement.on({ change: function () { $('#hidden-submit-img').click(); }, }); }); // This jquery is for the ajax post of the image // Doing it with submit, the image wont get saved, but the request is "success" // $('#image_form').submit(function (event) { // Doing it with change, the image gets saved successfully, but the respond loads a new page $('#image_form').change(function (event) { event.preventDefault(); $.ajax({ data: { image: $('#id_image').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, enctype: $(this).attr('enctype'), type: $(this).attr('method'), url: $(this).attr('action'), success: function () { console.log(1); }, error: function () { console.log(0); } }); }); </script> As described in the comments there is this strange behaviour, either the page wont get reloaded but the image doesnt get saved, or the image gets saved but the page renders to a white page only containing "success". I can see, that the … -
Django: Message appearing twice
I've came across an issue where message is displayed twice even though its called only once. Sometimes only one message is displayed however, most of the time 2 messages are. My view: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Account created has been creted! You can log-in now.') return redirect('login') else: if request.user.is_authenticated: messages.error(request, 'You are loged-in and in order to registrate you must be loged-out.') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form,'title':'Register Page'}) And here is my template Base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title> Django blog - {{ title }}</title> {% else %} <title> Django blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if … -
Query Django models two levels down foreign key relations
I am building a dictionary application using Django. The main models in this app are Expressions, Definitions, and Citys. The logic is that each Expression has one or more Definitions, and each Definition is associated with one City. Here is my problem: I want to query all the Citys associated with an Expression, from the Expression level. For example, I would like to do an_expression.cities and get all the Citys associated with (each Definition of) an_expression. Here are my models: class City(models.Model): city = models.CharField() class Expression(models.Model): expression = models.CharField() cities = models.ManyToManyField(City, related_name="expressions") class Definition(models.Model): city = models.ForeignKey(City, related_name="definitions") expression = models.ForeignKey(Expression, related_name="definitions") This code now works. However, every time I add a Definition I need to add the City to both the Expression --AND-- the Definition itself. Here is my question: Is there a way to only add the City to the Definition, and then somehow be able to query an_expression.cities and get all cities (basically getting rid of the cities field in the Expression model)? -
Handling data as well as response in AJAX success
I am handling submit through ajax using django in backend: Here is ajax code: $.ajax({ data: $(this).serialize(), // get the form data type: $(this).attr('method'), // GET or POST url: $(this).attr('action'), success: function(response,data) { if(data.frame_width_absent){ Alert.render('Please enter frame-width'); } else if(data.frame_height_absent){ Alert.render('Please enter frame-height'); } else if(data.frame_fps_absent){ Alert.render('Please Enter frame-fps'); } else if(data.bit_rate_absent){ Alert.render('Please Enter Bit-Rate'); } else if(data.bit_depth_absent){ Alert.render('Please Enter bit-depth'); } else if(data.container_absent){ Alert.render('Please Enter container'); } else if(data.duration_absent){ Alert.render('Please Enter container'); } else if(data.HRD_support){ Alert.render('HDR10 and HDR10+ content generation is not supported'); } else{ $('#frame').html(response); } } }); //Alert.render('Success If generation fails you will receive an email'); return false; }); The problem is if response is my first parameter in success the response is displayed optimally while alert is not displayed(when all required parameters are not entered). If the data is my first part parameter in success Alert is displayed optimally(when certain parameters in form are not entered) but unable to display response part(when all parameters in form required are entered). Back-End code views.py def generate(request): global frame_width,frame_height,frame_fps,video_codec,bit_rate,container,scan_type,profile,bit_depth,count if video_codec!='HEVC' and video_codec!='VP9': bit_depth='8' print("inside_tasks") #print(type(bit_depth)) if not frame_width: data = { 'frame_width_absent': True } return JsonResponse(data) elif not frame_height: data = { 'frame_height_absent': True } return JsonResponse(data) #return … -
Showing a rtsp stream on React Frontend
I need to show a video stream on a react component with a Python+Django backend. CURRENT SITUATION: I'm using opencv library to get the stream: import cv2 [...] def read_data(): cap = cv2.VideoCapture("rtsp://user:password/bla bla bla") while(cap.isOpened()): ret, frame = cap.read() retval, buffer = cv2.imencode('.jpg', frame) image_result_base64 = base64.b64encode(buffer) return HttpResponse(image_result_base64, 200) On React, where this.state.response_data is the content responseText of the backend call: render () { const img_data ="data:image/png;base64," + this.state.response_data; return <img id="overView" class="overView" alt="Stream" src={ img_data} width="90%" /> } This approach works and on frontend I see the frame in my component. Unfortunally to create some sort of stream, I need to call backend at least 10 times every second to have 10fps. This is heavy to backend. I read about StreamingHttpResponse but I don't know if fits my needs. -
Markdownx does not render math formulas
i'm new here. For one month ago i have started to learn Django. My goal was to make a web app: a pool of mathematical questions. User can create new questions and filter questions with respect to topic and level of difficulty. Yesterday, i decided to include a preview for textarea like the preview for example in stackoverflow. After searching in google i have found markdownx. It renders the text and all html-tags but not mathematical formulas (see picture).example of the issue I use mathjax to render mathematical formulas. If i put for example x^2 between \( ... \) it disappears. Same problem with $$...$$. Does anybody know how fix this problem? Below you can find my settings.py, models.py and the template. settings.py INSTALLED_APPS = [ 'question.apps.QuestionConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'multiselectfield', 'latexify', 'django_filters', 'mathpool', 'rest_framework', 'markdownx', 'markdown', ] MARKDOWNX_MARKDOWNIFY_FUNCTION = 'markdownx.utils.markdownify' MARKDOWNX_MARKDOWN_EXTENSIONS = [ 'markdown.extensions.extra', 'mdx_math', 'markdown.extensions.sane_lists', 'markdown.extensions.nl2br', ] models.py from django.db import models from multiselectfield import MultiSelectField from django.contrib.auth import get_user_model from django.urls import reverse from markdownx.models import MarkdownxField YEARS = ( (3, '3'), (4, '4'), (5,'5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), ) POINTS = [ ('1', '1'), ('2', '2'), ('3','3'), … -
Making password required for admins, but unusable for users
I am trying to implement a Django backend for a mobile app where users authenticate through their mobile numbers only. When the user tries to login, the backend will send him an OTP so that he can login. For this use case, I think I don't need a password field. However, I think I need a password for superusers. I am thinking of a solution but I don't know whether it is a suitable solution. models.py: class UserManager(BaseUserManager): def create_user(self, email, phone_number, password=None): user = self.model(email=email, phone_number=phone_number) user.set_password(password) user.save() return user def create_superuser(self, email, phone_number, password=None): user = self.create_user(email, phone_number, password) user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(blank=False, null=False, unique=True) phone_number = PhoneNumberField(blank=False, null=False, unique=True) is_staff = models.BooleanField(default=False, blank=False, null=False) objects = UserManager() USERNAME_FIELD = 'phone_number' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] def __str__(self): return self.phone_number Will the code above do the job? -
'str' object has no attribute 'get' Django Middleware [closed]
I am currently new to django framework and I am making a Middleware for authentic redirection of pages within a website. So if the user is guest user I want to always make him redirect to login page. But I came with this error. I have tried HttpResponse and return redirect but it didn't worked for me. I am getting this Attribute error at all the pages I am accessing to This shows me along with the error "'str' object has no attribute 'get'" My MiddleWare Code is: import re from django.shortcuts import redirect from django.conf import settings from django.contrib.auth import logout from django.urls import reverse from django.http import HttpResponse EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') print(path) #if not request.user.is_authenticated: # if not any(url.match(path) for url in EXEMPT_URLS): # return redirect(settings.LOGIN_URL) url_is_exempt = any(url.match(path) for url in EXEMPT_URLS) if path == reverse('logout').lstrip('/'): logout(request) return redirect('/accounts/') if request.user.is_authenticated and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated or url_is_exempt: return None else: return(settings.LOGIN_URL) This is my link of the … -
Make Custom Filter to iterate each field and check condition to return
I am making Custom Filter. It should check the each JSONField of model and pick up rows depending on conditions. These are the code what I want. How can I solve this?? class MyText(models.Model): myJson = JSONField() class MyTextFilter(filters.FilterSet): post_date = filters.DateTimeFilter(method="post_date_filter") def post_date_filter(self, queryset, name, value): for mt in MyText: jsonObj = json.loads(mt.myJson) if jsonObj['postdate'] > value: #do something here???? #return something here????? class Meta: model = MyText -
how can i get request.PUT or PATCH method body or data In Django Request
i am working on django request response log middleware i can't get request.PUT or PATCH but when i have a post request or get request i can have the data also i have request.body but it is empty as well in form of byte string. this is my code class RequestResponseLogger(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) request_body= request.PUT, response_body=response_body, method=request.method.lower(), status_code=response.status_code, return response any help is appropriated! -
URL available in urls.py still getting 404 in Django 2
I wrote a function in views.py as follows def removeinvoices(request,invoiceID,creatorID,deletorid,typeofchange): form = invoicestorageForm() form.invoiceid = invoiceID form.creatorid = creatorID form.deletorid = deletorid form.typeofchange = typeofchange form.save() thatInvoice = taxInvoice.objects.filter(invoiceid=invoiceID).first() thatInvoice.delete() messages.success(request, "Invoice ID "+ invoiceID +" removed Successfully !") return redirect("vieweinvoices") and wrote in urls.py as follows: path("removeinvoices/<int:invoiceID>/<int:creatorID/><int:deletorid>/<str:typeofchange>", views.removeinvoices, name="removeinvoices",), and I'm generation the href in JS dynamically, I'm able to get all variables coorectly, but is still says 404 error, when I click on href I'm able to work fine with all other urls mentioned in image. Not sure where I'm going wrong! -
How to extract csv file from a zip and save it to disk in python?
I have a zip file that I receive from the user. The zip file contains a csv file which I need to save to a directory in my server. I am using django in my backend and this is what I do from zipfile import ZipFile from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def store_file(request): if request.method == "POST": user_id = request.POST.get("user_id") client_file = request.FILES['attachment'] file_path = "/home/sr/uploads/" try: with ZipFile(client_file, 'r') as zip_ref: csv_file = zip_ref.infolist()[0] with open(file_path + '%s' % csv_file, 'wb+') as dest: for chunk in csv_file.chunks(): dest.write(chunk) # return success message return HttpResponse(0) except Exception as e: # return error message return HttpResponse(1) But I get this error message Traceback (most recent call last): File "/home/sr/scripts/interact.py", line 2364, in store_file for chunk in csv_file.chunks(): AttributeError: 'ZipInfo' object has no attribute 'chunks' Now this is how I usually store a csv file when it comes to me as just a csv file. But now in this case, the csv file is inside a zip and so even after pulling the csv file from the zip, I can't save it in my server. What am I doing wrong?