Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Accessing Django context variable from vue.js single file component [duplicate]
This question already has an answer here: How can I pass my context variables to a javascript file in Django? 3 answers I am trying to develop single file components in a vue project that I can build as a web component and then import into my django templates. I like the concept of having a web component that I can import and run on in any modern browser and will just work. The issue I am facing is while I started working on all of these single page components I forgot that I still have some reliance on some django context variables. For example - there are api endpoints I am calling in my vue component that are passed in via django context. My question is - is it possible to build a web component from my single page component that I can import into a django template and have it read the django context variable? using jinja in my django template, I would normally access the variable with {{ api_endpoint }} I know I can access this using a vue.js inline template and setting up custom delimiters, however I do not know if this is possible with a … -
How append image to serialize?
How can I add image_form to form at Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].files[0] var data = { form: form, } $.ajax({ headers: {'X-CSRFToken': '{{ csrf_token }}' }, type: 'POST', data: data, }) }) -
LoginRequiredMixin with redirect_field_name does not work
Using the LoginRequiredMixin it does not route to the 'redirect_field_name' I specify. Even though I see it appear in the url. I've tried putting both urls ('user/update/') and named urls ('accounts:profile-update') in 'redirect_field_name' with the 'LoginRequiredMixin' but neither seem to make the redirect work. I can get a redirect to work when I use the below, in src/settings.py LOGIN_REDIRECT_URL = '/user/' But I want to have custom redirects for different views. class ProfileUpdateView(LoginRequiredMixin, UpdateView): # http://127.0.0.1:8000/user/update/ login_url = '/login/' redirect_field_name = 'accounts:profile-update' # redirect_field_name = '/user/update/' # neither works above model = Profile fields = ['first_name', 'last_name', 'mobile_phone',] template_name = 'accounts/profile_update.html' success_url = reverse_lazy('accounts:my-profile-detail') # PK required in UpdateView, making context['object'] def get_object(self, queryset=None): if self.request.user.is_authenticated: queryset = Profile.objects.get(user=self.request.user) return queryset # accounts/urls.py app_name = 'accounts' urlpatterns = [ # ... some more urls ... path('update/', ProfileUpdateView.as_view(), name='profile-update'), ] # src/urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), path('user/', include('accounts.urls')), ] # src/settings.py # LOGIN_REDIRECT_URL = '/user/' # If I uncomment this, it works, but all my login's redirect only to this URL if I use LoginRequiredMixin :(``` -
About reset jwt token in django rest framework
I am using JWT in a React + Django DRF project (Rest Framework), for the requests.. with the following library. https://getblimp.github.io/django-rest-framework-jwt/#refresh-token The problem is that upon expiration .. the token does not work anymore and the api throws an "unauthorised error".. and I do not know what I can do from react to keep the session jwt if the user wants to enter the other day and continue working with the application. What do you think? How can I reset the expired token? Pd: The library does not send a token-refresh as others do. I can not find another similar JWT library for Django Rest Framework. -
Why do I get AttributeError when I try to create model instance with empty fields in admin panel?
I have a model where I added some custom validation (I overwrote clean method). Everything seems to work fine except I get a weird error. When I try to create model instance and leave fields blank, instead of getting standard error message sth like "You have to fill this field", I get AttributeError because of NoneType object. I spent already a lot of time trying to find answer to that. I think clean_fields() method is not called before my custom clean() method but I have no idea why? Interesting thing is if I have some existing ClassOccurrence instance, open it for editing and leave obligatory fields blank, it works correctly. I get get error message in admin panel. When I tried to write clean() method for another, small model I didn't have same problem as for this one (ClassOccurrence). Anybody can help? I'm not experienced in programming and I run out of ideas.. class ClassOccurrence(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name='nazwa kursu') date = models.DateField(verbose_name='data') start_time = models.TimeField(blank=True, verbose_name='godzina rozpoczęcia') end_time = models.TimeField(blank=True, verbose_name='godzina zakończenia') main_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True, related_name='main_teacher_set', verbose_name='instruktor') substitute_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True, related_name='substitute_teacher_set', verbose_name='zastępstwo') students = models.ManyToManyField(User, blank=True, verbose_name='uczestnicy') # class Meta, __str__(), properties … -
What am I not understanding about Django default sessions?
I am under the impression that if I set a session value in the following way: request.session['somekey'] = 'someval' that on subsequent requests the session attribute from the passed in request parameter should retain the value, correct? Well obviously I'm wrong somewhere here because no matter what I try this is not ever occurring. Here is about the most simple illustration I can give, spin up a new Django project according to the official tutorials, and in your app views.py add this method: def test_cookie(request): resp = HttpResponse() if request.method == 'GET': if request.session.test_cookie_worked(): request.session.delete_test_cookie() resp.content = "(GET)You're logged in." request.session['test'] = "foo" request.session.modified = True request.session.save() else: resp.content = "(GET)Please enable cookies and try again." request.session['test'] = "bar" request.session.modified = True request.session.save() request.session.set_test_cookie() try: resp.content = "{}<br>test val is {}".format(resp.content, request.session['test]'],) except KeyError: resp.content = "{}<br>never retained test val".format(resp.content,) return resp At no point do you ever get a value in request.session['test'] You do, however on the 2nd visit to the same endpoint, get indication that your test cookie worked just fine. So what am I doing wrong here such that the session is never being saved? For the record, the request.session.modified = True and request.session.save() I didn't think … -
How to display foreign key on Django 1.11 admin page?
I’m upgrading from Django 1.9 to 1.11 and getting "Error during template rendering" on admin portal. It happens only on change or add page and not when listing. It also only happens when model has a reference field. Here is my model (simplified a bit). User is a foreign key. If I exclude it with: exclude = ['user'], then the page displayed correctly (except displaying the user). What do i miss? class Task(models.Model): id = models.UUIDField( primary_key=True, editable=False) task_code = models.PositiveIntegerField() level = models.PositiveIntegerField(default=10) user = models.ForeignKey('account.User', blank=True, null=True, on_delete=models.CASCADE) @admin.register(Task, site=admin_site) class TaskAdmin(admin.ModelAdmin): list_display = ('task_code', 'user', 'start', 'end', 'level') list_filter = ('level', 'task_code') search_fields = ('id',) def start(self, obj): return obj.timespan.lower def end(self, obj): return obj.timespan.upper On admin page list entries looks OK, but when i proceed to change or add an entry i get this: -
How to solve the invalid literal for int() with base 10: 'testuser' error
I am trying to make a follower system in django and wanted to do it using a foreign key. I typed the following code but got an error saying invalid literal for int() with base 10: 'testuser' the code is as follows models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') image=models.ImageField(default='default.jpg',upload_to='profile_pics',blank=True) description=models.TextField(max_length=200, blank=True) def __str__(self): return f'{self.user.username} Profile' def saveimg(self): super().save() img=Image.open(self.image.path) if img.height>300 or img.width>300: output_size=(300,300) img.thumbnail(output_size) img.saveimg(self.image.path) class Follower(models.Model): follower = models.ForeignKey(User, related_name='following', on_delete=models.CASCADE) following = models.ForeignKey(User, related_name='followers', on_delete=models.CASCADE) class Meta: unique_together = ('follower', 'following') def __unicode__(self): return u'%s follows %s' % (self.follower, self.following) -
How do I access a dictionary value from my html file using a filter custom template?
I can't access a dictionary value declared in my views.py, from my .html file. I've been trying to use the several previous threads about this for hours and I just can't see it. I'm sure I'm doing something wrong. views.py def test(request): now = datetime.now() day = now.strftime("%Y-%m-%d") year = now.strftime("%Y") month = now.strftime("%m") context = { "content": [day,year,month], "object_list": queryset } return render(request, "test.html", context) filter.py from django.template.defaulttags import register @register.filter(name='get_item') def get_item(dictionary, key): return dictionary.get(key) test.html {% load filtres_dictionary %} {% with content.get_item.day as content.day %} <p>{{ content|get_item:content.day }}</p> {% endwith %} I am currently getting the following error message, and what I wanted to get is: 2019-06-13. Printed in my website. VariableDoesNotExist at /test/ Failed lookup for key [day] in ['2019-06-13', '2019', '06'] -
Why I get 403 POST request error at Django?
Why I get 403 POST request error? I do not understand what is wrong here ... $('#id_submit').click(function(e) { e.preventDefault(); var form = new FormData($('form')[0]) form.append("image", $("input#id_image")[0].files[0]) var data = { form: form, image_form: 123 } $.ajax({ headers: '{{ csrf_token }}', type: 'POST', data: data, processData: false, contentType: false }) }) -
How can I create my own app that works in different projects, like a contact form? (Conventions)
I want to outsource my own contactform in a django app, to reuse it in different projects without modifying to many lines of code. What do I have to do, to use this app like template. I created a new app called 'contact' where I put my template in. project/contact/templates/contact/contactForm.html, but this is static HTML with inputfields that are dynamic forms from Django. This isn't reusable without modifying the complete HTML code. -
Thread Safe Storage in Django
I'm customizing Django's Admin Email Handler, and adding some burst protection to it so that if several errors are brought up within a minute, only one error email is sent out. def burst_protection(self, lag=60): """ Prevents an unintended DoS attack. :param lag: :return: """ current_time = int(time.time()) global timestamp if current_time - timestamp > lag: timestamp = current_time enable_burst_protection = False else: enable_burst_protection = True return enable_burst_protection Originally, I implemented timestamp as a class variable, but this doesn't protect from message bursts in our production environment, because I'm assuming there are multiple threads or processes on the server accessing and writing to timestamp at the same time . Is there a thread and process safe way to store the time stamp value in Python/Django? I've heard that it's possible by storing the timestamp value in a database, but I would prefer to avoid accessing the database for this. -
Django TypeError __str__ returned non-string (type tuple)
I need help. I am noob :). I need to create Model in Django to save username and password. User name is OK. But password has problem. str returned non-string (type tuple) from django.db import models Create your models here. class User(models.Model): user_name = models.CharField(max_length=25, null=False, blank=False, default='User') user_password = models.CharField(max_length=10, null=False, blank=False, default='1234') def __str__(self): return self.user_name, self.user_password -
Forms showing and not showing based on different URL configurations for the same view
A simple homepage that uses crispy-forms to sign in, does not show them for different configuration of the URL. Link for all of the code: https://github.com/J-Kazama/rep1/tree/second (The relevant files are in proj1/urls and login/templates/login/sign) For path('home/', include('login.urls')) the homepage shows everything except the forms for writing credentionals, while path('home/', auth_views.LoginView.as_view(template_name='login/sign.html'), name='login-website') does show them in addition to the rest of the html. *I am new to django, and I am not certain if what I am talking about is URL configuration, but that's the most intuitive description I could've think of. -
Trying to connect to an API and opened MySQL port so it would work, but terminal just hangs
I'm trying to connect to the zcrmsdk python API by Zoho CRM. At first when I would try to connect the API would tell me that the MySQL database refused connection and couldn't connect on port 3306. Here's the error: File "/Users/hgducharme/Programming/Environments/SentriForceEnvironment/lib/python3.7/site-packages/mysql/connector/network.py", line 512, in open_connection errno=2003, values=(self.get_address(), _strioerror(err))) mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on '127.0.0.1:3306' (61 Connection refused) So next I opened up port 3306 on my localhost by running nc -l localhost 3306. Now when I send the command to connect to the API, my terminal just hangs. Here is my python code to connect with the API: from zcrmsdk import ZCRMRestClient, ZohoOAuth # Tell Zoho it's me config = { 'sandbox': 'False', 'applicationLogFilePath': './log', 'client_id': '1000.xxxxxxxxxxxxxxxx' 'client_secret': 'e9xxxxxxxxxxxxxxxxxxxxxxxxx', 'redirect_uri': 'http://localhost:8000/some_path', 'accounts_url': 'https://accounts.zoho.com', 'token_persistance_path': '.', 'currentUserEmail': 'email@gmail.com' } # Get an access token ZCRMRestClient.initialize(config) oauthClient = ZohoOAuth.get_client_instance() grantToken = "1000.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" oauthTokens = oauthClient.generate_access_token(grantToken) -
OTP verification for unregistered email id in DJango
I have a small DJango form where users can express interest and leave their contact details. Here I have an email field which I need to verify for its authenticity. The things is anyone can send in these interests and they need not be registered users. I have been trying to get some direction on implementing OTP and the most sought after answer is django-otp. But there is not clear example showing how to make it work without a user attached to it. I just need to grab the email id from the form, generate a time based otp with expiry and email it. The user should then enter this into a text box provided for it and click submit. The interest will be registered if the otp is valid else it should ask the user to input a valid otp. Kindly direct. -
How to fix "No file was submitted." when trying to upload a file with django Rest framework and REACT with Axios
I'm trying to simply upload a file (and the name of the file) with/Django rest framework and REACT/Axios and I do not understand what I'm doing wrong. I have this error: request.response: "{"my_file":["No file was submitted."]}" This is my REACT frontend: uploadFile = e => { e.preventDefault(); let formData = new FormData(); formData.append('my_file', e.target.files[0]); axios.post('http://127.0.0.1:8000/uploadFiles/', { formData, name: 'name', headers: { Accept: 'application/json, text/plain, */*', 'Content-Type': 'multipart/form-data' }, }) .then(() => { console.log('All Done',); }) .catch(error => { console.log('error.response: ', error.response); }); } render() { return ( <input type='file' onChange={this.uploadFile} /> ); } This is my Django REST backend with: models.py: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class File(models.Model): my_file = models.FileField(upload_to=user_directory_path) name = models.CharField(null=False, max_length=50) upload_date = models.DateTimeField(auto_now_add=True) serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ( 'id', 'my_file', 'name', 'upload_date', ) views.py class UploadFileView(views.APIView): parser_classes = (JSONParser, MultiPartParser, FormParser,) def post(self, request, *args, **kwargs): fileSerializer = FileSerializer(data=request.data) if fileSerializer.is_valid(): fileSerializer.save() return Response(fileSerializer.data, status=status.HTTP_201_CREATED) else: return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST) I've had a lot of difficulties to write this code and I think I'm close to the end but I can't figure why this file isn't submitted. -
How to update a field in the model later in the project with different form?
I created a model for registered users and added a field feedback in it. I need to allow logged in users to post feedback and to get it updated in the model, but it is not. Instead it is getting created as a new entry with a primary key. model for register class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') feedback = models.TextField(max_length=500,blank=True) verified =models.BooleanField(default = False,blank=True) def __str__(self): return self.user.username form for feedback: class FeedbackForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('feedback',) view for feedback: @login_required def feedback(request): if request.method == "POST": form = FeedbackForm(request.POST) else: form = FeedbackForm() if form.is_valid(): userprofile=form.save(request) userprofile.save() else: form = FeedbackForm() return render(request, 'NewApp/feedback.html',{'form':form}) -
Django rest framework POST many to many with extra fields
I am trying to create a model in Django that has a many-to-many relationship to another model with extra fields. I am using the rest framework to provide CRUD operations on these and am having a chicken-and-egg scenario I believe... The issue is that when I go to POST the new MainObject, it throws an error in the many-to-many part due to not having a MainObject id to point to. But I want it to point to the MainObject I am creating, which doesn't exist at time of POST'ing. I believe this to be an issue with the serializers, but am unsure of how to resolve it. I assume my assumptions might also be off in how I am formulating the POST data. I am using Django 2.1.8 Model Code class RelatedObject(models.Model): ... class MainObject(models.Model): related_objects = models.ManyToManyField(RelatedObject, through='ManyRelatedObject') class ManyRelatedObject(models.Model): main_object = models.ForeignKey(MainObject, on_delete=models.DO_NOTHING) related_object = models.ForeignKey(RelatedObject, on_delete=models.DO_NOTHING) other_attribute = models.BooleanField(...) Serializer Code class ManyRelatedObjectSerializer(serializers.ModelSerializer): main_object = serializers.PrimaryKeyRelatedField(queryset=MainObject.objects.all()) relates_object = serializers.PrimaryKeyRelatedField(queryset=RelatedObject.objects.all()) class Meta: model = ManyRelatedObject fields = '__all__' class MainObjectSerializer(serializers.ModelSerializer): related_object = ManyRelatedObjectSerializer(many=True) class Meta: model = MainObject fields = '__all__' POST Payload ( It is assumed that there exists a RelatedObject that has an id of 1) … -
how to build this landing page using ListView
So basiclly i am trying to build a landing page that looks somthing like Netflix. i want to represent my Movie object's that are based on a Movie model. so these object's will apear in the ListView page. i can't really understand how to inject using template coding and how to make it apear as blocks. i am aiming for somthing like this: enter image description here my models.py : class Movie(models.Model): ''' ''' name = models.CharField(max_length = 250,unique = True) director = models.CharField(max_length = 250) image = models.ImageField(upload_to='movies_pictures', blank =True) length = models.IntegerField() price = models.IntegerField() copies = models.IntegerField() trailer = models.URLField() def __str__(self): return self.name def get_absolute_url(self): ''' this will reverse you back to movie detail page ''' return reverse("movie_detail",kwargs={"pk":self.pk}) class Meta: ordering = ['name'] i want to understand how to build the html page using the django template injections. thank you from a head! -
Is there any way for filter a queryset in django based on two columns? for example abs of column x and y greater than a number
At the beginning, i am not very good at english. i am sorry. I want to filter my result based on absolute of two columns. abs(x - y). I tried so many ways but could not find any useful solution. # This is my model class Driver(models.Model): account = GenericRelation(Account, related_query_name='drivers') rating = models.FloatField() x = models.FloatField() y = models.FloatField() active = models.BooleanField(default=False) # I want filter based on two columns x and y But :( drivers = Driver.objects.filter(abs(Driver.y - 5) > 5 and abs(Driver.x - 10) > 5) -
How to include static image url inside js file?
I am using a template in django project. In that template i changed every static file location with jinja code. But there is hero.slider function in main.js which requests an icon which is in the static folder for which my server response with 404. is there anyway i could use jinja code and load that icon. main.js includes this function $('.hero-slider').owlCarousel({ loop: true, nav: true, dots: true, navText: ['', '<img src="img/icons/solid-right-arrow.png">'], mouseDrag: false, animateOut: 'fadeOut', animateIn: 'fadeIn', items: 1, //autoplay: true, autoplayTimeout: 10000, }); which creates a button on a slider window -
How to display a list of uploaded files with dynamic path in django
I want to upload files to my website in dynamic path, and list all of them, but I do not know how to call the files because they are in dynamic path. The problem is I allow the filefield to be blank, so when I use 'objects.all()' it will also list the blank value which I do not want it to be shown. from django.db import models from django.utils import timezone import datetime # Create your models here. def upload_to(instance, filename): return 'uploads/{id}/{fn}'.format(id=instance.pk,fn=filename) class Chemkin(models.Model): mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True) thermo_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True) transport_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True) surface_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True) timestamps = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return 'upload_to' def save(self, *args, **kwargs): """ The folder used to upload the files to, depends on the id (primary key) of the Chemkin object. If that is newly created and not yet saved, it doesn't have an id yet. So to save the Chemkin object and all its files, you need to save the Chemkin object first with no files if it has no id, before then saving it again with the files re-attached. This solution is based on john.don83 answer here https://stackoverflow.com/questions/9968532/django-admin-file-upload-with-current-model-id """ if … -
Proper ways to do MySQL multiple join
MySQL version : 5.7 Hello. I am working on a new django Project. For the meanwhile, I brought 2 tables. Auth(1st Table) is containing user data(like id, email, password, name, etc.) Paper(2st Table) is containing research paper information. The Paper table has 10 columns for user permission. The only 10 users can read the paper, so I have a model for the table like; class DocDetail(models.Model): no = models.AutoField(primary_key=True) doc_id = models.CharField(null=False, default="", max_length=255) doc_name = models.CharField(null=False, default="", max_length=255) doc_pw = models.CharField(null=False, default="", max_length=255) view_perm_1 = models.IntegerField(null=True) view_perm_2 = models.IntegerField(null=True) view_perm_3 = models.IntegerField(null=True) view_perm_4 = models.IntegerField(null=True) view_perm_5 = models.IntegerField(null=True) view_perm_6 = models.IntegerField(null=True) view_perm_7 = models.IntegerField(null=True) view_perm_8 = models.IntegerField(null=True) view_perm_9 = models.IntegerField(null=True) view_perm_10 = models.IntegerField(null=True) folder = models.CharField(null=False, default="", max_length=255) url = models.CharField(null=False, default="", max_length=255) status = models.IntegerField(null=True) action_exp = models.DateTimeField(null=True) date_updated = models.DateTimeField(null=True) view_perm columns are indicating Auth Table's user_id. I want to select all culumns of the Paper table and user data which linked to each view_perm column with 1 query. I think I am pretty much wrong with modeling. I can do select with 10 join, but it doesn't look right. Is there any better idea to make this works? I am pretty new to SQL, so please … -
PythonCalendar: Put time span between start and end date in variable
I'm developing a rental website for my university. I am displaying a calendar where the user can see whether a tool is rented, reserved or available. If it is rented or reserved the of the calendar should be displayed red. My problem is that I only managed to colorize the start date of the rented tool but not the days in between up to the end date. How can I achieve this? I use the Python Html Calendar and this is how my code for coloring the cells looks at the moment: def formatday(self, day, reservations): reservations_per_day = reservations.filter(start_time__day=day) d = '' for reservation in reservations_per_day: d += f'<li> {reservation.tool} </li>' d += f'<li> {reservation.reservation_status} </li>' d += f'<li> {reservation.start_time} </li>' d += f'<li> {reservation.end_time} </li>' if day != 0: for reservation in reservations_per_day: if reservation.reservation_status == 'reserved' or reservation.reservation_status == 'rent': return f"<td bgcolor='indianred'><span class='date'>{day}</span><ul> {d} </ul></td>" return f"<td ><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>'