Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
expected string or bytes-like object in Django save() method
I have Job Model that I can see list of them, create new one and see details of one of them. But when I want to edit objects of this model, I got this error: match = datetime_re.match(value) TypeError: expected string or bytes-like object And in Traceback this line be come bold: job_resume.save() This is my view: def edit_admin_job_resume(request, id): resume = get_object_or_404(JobRecord, id=id) if request.method == "POST": form = AddAdminJobForm(request.POST, request.FILES,instance=resume) if form.is_valid(): job_resume = form.save(commit=False) job_resume.upload_url = form.cleaned_data['upload_url'] job_resume.time_start = date_picker(date=request.POST['time-start-input']) job_resume.time_end = date_picker(date=request.POST['time-end-input']) job_resume.save() return redirect('administrator:view_admin_job_resume') else: form = AddAdminJobForm(instance=resume) template = 'administrator/resumes/add_edit_resume.html' context = {'form': form} return render(request, template, context) What is wrong with this codes? -
How to calculate unique IP's in Django (1 unique IP per day)?
** I'would like to calculate on many unique IP's have visited a page from my website, with maximum visit per IP per day = 1. ** I have a model with various fields. Two of them are : - date: created_at.strftime("%d-%m-%y, %H:%M") - ip: request_ip A example of these two informations would be : - 2019-07-15 17:43:09 - 127.0.0.1 I tried a combinaisons of various Django's methods like : values, distinct, filter, etc. But I can't get the result I want. Because I cannot change the format of my fields, the distinct method won't work because the date changes every second. It would have been nice to have a date format like ("%d-%m-%y) = without the seconds, minutes and hours. This is why the following example won't work. I have as a result, all the IPs in my database. Example : try: all_views = reward_views.objects.all().order_by('-updated_at') except: return HttpResponse(status=500) ip_number = reward_views.objects.values('request_ip', 'updated_at').distinct().count() So I tried to put the informations, IPs and dates, in lists in order to modify the date format and do better manipulations on it. try: all_views = reward_views.objects.all().order_by('-updated_at') except: return HttpResponse(status=500) all_dates = [] for view in all_views: all_dates.append({ 'reward_creation_date': view.created_at.strftime("%d-%m-%y"), 'user_ip': view.request_ip, }) print (all_dates) But … -
How to turn django's 'rest_framework.utils.serializer_helpers.ReturnList' to dict to compare get and post data with pytest correctly
I am trying to test an API with pytest. My idea is to create data with a post method and then make a get request and compare the created data with the get data. It works fine to post and get the data. Yet I can't compare using django's compare operators because - I think - I get different types back. Here is my test (with lots of print statements to debug) def test_auth_user_can_create_graph(self, client, user): """Test if an authenticated user can create a new graph. """ create_data = graph_data url = api_reverse('create-graph') graph_objects = Graph.objects.count() response = client.post(url, create_data, content_type='application/json') url_get_request = api_reverse('list-graph') response_get = client.get(url_get_request, content_type='application/json') # response_json = json.loads(response_get.data) # print(response_get.get_data(as_text=True)) print(type(response_get.data)) print(type(url_get_request)) print(response_get.data) print(graph_data) assert (response_get.data) == (graph_data) assert response.status_code == 200 The line assert (response_get.data) == (graph_data) throws me an assertion error. I guess that's because my get-data is of type <class 'rest_framework.utils.serializer_helpers.ReturnList'> and graph data is of type <class 'dict'> I tried serializing the get_data with my GraphSerializer. I also tried to dump my data with json.dumps and I tried comparing it turning both into sets. None of it worked for me. Is there a simple way of doing this without any extra dependencies? … -
How to create order in razorpay , And how to pass order_id to template in Django
I have been trying to implement Razorpay standard checkout in Django 2 ! As docs say i have tried to create order in my view.py but its not creating an order and if order is created how do i pass order_id to my template ? if request.method == 'POST': DATA = { 'amount': 50000, 'currency': 'INR', 'receipt': 'order_rcptid_11', 'payment_capture': 0, } client.order.create(data=DATA) -
Keras progress real time output to Django html page
How to show the progress of Keras model training on a Django web application in a real time? Something like this library which solves the problem within jupyter notebook: https://github.com/bstriner/keras-tqdm from keras_tqdm import TQDMNotebookCallback # keras, model definition... model.fit(X_train, Y_train, verbose=0, callbacks=[TQDMNotebookCallback()]) -
Use serializer of model having foreign key to do CRUD on parent table in Django Rest Framework
In my API, I have two models Question and Option as shown below class Question(models.Model): body = models.TextField() class Options(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.CharField(max_length=100) is_correct = models.SmallIntegerField() While creating a question it would be nicer the options can be created at the same time. And already existed question should not be created but the options can be changed if the options are different from previous. I am using ModelSerializer and ModelViewSet. I use different urls and views for Question and Option. serializers.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class OptionReadSerializer(serializers.ModelSerializer): question = QuestionSerializer(read_only=True) class Meta: model = Option fields = ('question', 'option', 'is_correct') class OptionWriteSerializer(serializer.ModelSerializer): class Meta: model = Option fields = ('question', 'option', 'is_correct') views.py class QuestionViewSet(ModelViewSet): seriaizer_class = QuestionSerializer queryset = Question.objects.all() class OptionViewSet(ModelViewSet): queryset = Option.objects.all() def get_serializer_class(self): if self.request.method == 'POST': return OptionWriteSerializer return OptionReadSerializer urls.py from django.urls import include from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('api/question', QuestionViewset, base_name='question') router.register('api/option', OptionViewSet, base_name='option') urlpatterns = [ path('', include(router.urls)) ] In this way, I always have to create questions first and then I can individually add the option for that question. But this is not a practical approach. It would … -
How i Can add my own Models and display them in Oscar Dashboard?
I want to create my own models and theme in Django Oscar, please let me know the process. Where I can add Models in Django Oscar and How I will Display that model in my Django Oscar Dashboard. I am Trying to do this from last 2 days but still did not find ant solution for this. -
check username already exists in django
I am a beginner in django web development.I want to submit a form in django and database used is sqllite.i want to student id in my form already exists in db or not without submitting form.Here i am not using Ajax in it.Can anyone help us? -
ConnectionRefusedError at /password-reset/ [WinError 10061] No connection could be made because the target machine actively refused it
When user enter email for password reset then error arise connection failure which is related to server failure error . -
How to update User model while getting existed info?
There is something wrong with my edit_profile code. I'm using "settings.AUTH_USER_MODEL". When I try to edit profile, it turned out that all the fill box was blank. I want the existing information to be there so the user would be editing their profile easier. Please help me. accounts/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=30,null=True,blank=True) last_name = models.CharField(max_length=30,null=True,blank=True) address_number = models.CharField(max_length=15,null=True,blank=True) road = models.CharField(max_length=30,null=True,blank=True) kwang = models.CharField(max_length=30,null=True,blank=True) ked = models.CharField(max_length=30,null=True,blank=True) province = models.CharField(max_length=30,null=True,blank=True) postal = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) def __str__(self): return str(self.user) accounts/views.py @login_required def profile(request): """Display User Profile""" user = request.user profile = get_object_or_404(UserProfile, user=user) return render(request, 'accounts/profile.html', { 'profile': profile }) @login_required def edit_profile(request,id): user = request.user form = ProfileForm(instance=user) if request.method == 'POST': form = ProfileForm(instance=user, data=request.POST) if form.is_valid(): form.save() messages.success(request, "Updated the Profile Successfully!") return HttpResponseRedirect(reverse('profile')) return render(request, 'accounts/edit_profile.html', { 'form': form }) -
Getting Error 405, while uploading a file through django web application
I have a simple ModelForm that allows the user to upload his/her resume through the HTML template. I've looked through some StackOverflow solutions some suggest to change URL pattern order or make some changes in the form action in HTML template. I'm afraid none of them worked. Though the same file upload is happening from the admin end. P.S.: There are user profiles created, therefore autofill was used. #models.py class Upload_Resume(models.Model): first_name = models.CharField(('First Name'),max_length= 20) last_name = models.CharField(max_length= 20) email = models.EmailField(max_length= 20) resume = models.FileField(upload_to='documents/', default = None) uploaded_at = models.DateTimeField(default = None) def __str__(self): return self.email class Meta: verbose_name = "Student's Resume" verbose_name_plural = "Student's Resume" #views.py @login_required def post_upload_resume(request): if request.method == 'POST': form = forms.Upload_Resume(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/home') else: form = forms.Resume_Upload() return auto_fill_form(request) def auto_fill_form(request): form = forms.Resume_Upload(initial=dict(first_name=request.user.first_name, last_name=request.user.last_name, email=request.user.email)) context = dict(form=form) return render(request, "registration/resume.html", context) #forms.py class Resume_Upload(forms.ModelForm): class Meta: model = Upload_Resume fields = '__all__' #urls.py urlpatterns = [ path('admin/', admin.site.urls), path('resume/', views.post_upload_resume, name='resume'), path('home/', views.HomePage.as_view(), name='home'), ] #registration/resume.html {% extends 'base.html' %} {% load bootstrap3 %} {% block content %} <h3>Upload Resume</h3> <h3>Hey {{user.first_name}} {{user.last_name}} upload your resume.</h3> <div class="container"> <form form action="." role="form", method="POST"> {% bootstrap_form … -
Working with multiple input forms in Django
I'm working on a web app that allows users to critically appraise medical articles. The common entry into the user input is entering a PubMed url and an article type (publication_type, e.g. cohort, RCT, etc). There are 10 types of article they could choose, and each will have different required input fields. My question is: there being so many input forms and associated fields, how is it best to split this up? For example, as a beginner my first thought was to define all of the input fields in same model class, and display the input form and output using {% if publication_type == .....%}, {% elif .... %}, etc, but I wondered if there is a better way of doing it? Another way might be to create different models for each with ForeignKeys, but wouldn't that get a bit messy? Hope that makes sense? Thanks in advance -
return a list of file_id based on some list of file_type provided
so I was trying to find the best way to return a list of file_id. file_id is basically the uuid or the primary key of the file. Now i have new_file_type = 'google' and old_file_type = ['google', 'linkdin', 'twitter']. Note that the only difference between new_file_type andn old_file_type is new_file_type is a string and old_file_type is a list contains more than one items. So i have the following implementation which returns the list of file_id based on the job_id and the new_file_type. Now how could i go with the old_file_type, i know , i have to loop. But how to go efficiently ? def fetch_file_meta(job_id=None,new_file_type =None,old_file_types=[], **kwargs) -> list: """Fetch file meta data if to run batch files process. :param job_id: job id to merge files :param kwargs: :return: <list> a file ids to be merged into one file and the job meta """ LOGGER.info(f"fetch files for job: {job_id}") file_data = None job_meta = {} file_id_list = [] file_store_url = f"{FILESTORE_PATH}/attributes/attributes/" if job_id: cleaned_filter_params = {'meta__job_id': job_id, 'file_type': new_file_type} LOGGER.info(f"cleaned filter params: {cleaned_filter_params}") for old_file_types in old_file_types: try: response = old_file_types.requests.get(file_store_url, params=cleaned_filter_params) filestore_file_meta_response = old_file_types.response.text LOGGER.info(filestore_file_meta_response) # can retrieve multiple files, just use the first index. old_file_types.file_data = json.loads(filestore_file_meta_response) LOGGER.info(f"file_data: … -
Django: `RunPython` outside of migration?
The RunPython runs code in historical context, that is, recreating the model classes as they were at the time of the migration. Can that command be used outside of a migration script? That is, is it possible in some external script, to write something like RunPython(migration_number=12, forward_code, reverse_code) -
How to modify the form filed data based on another field?
I have a model: class PastStudy(Model): grade_average = FloatField(null=True) I have a modelform as below: class PastStudyForm(ModelForm): class Meta: model = PastStudy fields = ('grade_average', ) What I have in view: if request.POST: past_study_form = PastStudyForm(request.POST) if past_study_form.is_valid(): return HttpResponse(past_study_form.cleaned_data['grade_average']) What I need is that I want to write a clean method for PastStudyForm so that in case I entered 90 as grade average, HttpResponse converts it two 0-20 grading scheme and returns 18. I tried this and I was still getting 90 not 18 class PastStudyForm(ModelForm): class Meta: model = PastStudy fields = ('grade_average', ) def clean(self): cleaned_data = super().clean() grade_average = self.cleaned_data['grade_average'] self.cleaned_data['grade_average'] = grade_average/20 return cleaned_data However, I still get 90. I also have tried a few other methods but I still was getting 90 in HttpResponse The real code is huge and I have summarized it in here and other aspects of the problem are not explained in here. That is why I prefer and expect to get a response in which I am advised how to it in the form definition, not other methods such as converting it in the view. -
How can i confirm a database entry in django admin?
I have been working around this problem. I have a user submitting a HTML form lets say to list their hotel on my website. I need to review this form before i add it into my hotels model to be published. One approach i have worked on is to use a requests model where this form can be stored and later using django admin action write a custom action to add/remove the request. In case of acceptance i copy the details to my hotels model else it sends an email or a notification back to user. Second approach is simply using django action on hotels model where the request is sent to approve it or reject it. In this case i want to know if thats possible where a data point doesn't get written to database until it's been accepted by admin. If yes how can i do that? Finally, these details are displayed on my main page and search page for users to book these places. If there is a better and effective way to do it. Please share that. Thanks in advance. If something isn't clear i can answer your specific questions in the comments below 😊. Have … -
Validate pk as int in drf viewset retrieve url
Code looks as follows: class UserViewSet(ViewSet): # ... Many other actions def list(self): # list implementation def retrieve(self, request, pk): # manual pk int validation router = DefaultRouter() router.register(r"users", UserViewSet, basename="users") urlpatterns = router.urls Right now pk is not validated as int therefore a request to db is made, which I want to avoid. Is there any way I can add that type of validation in urls? I can achieve that without using router like this: urlpatterns = [ url(r'^users/(?P<pk>\d+)/$', UserViewSet.as_view({'get': 'retrieve'}), # many other actions have to be added seperately ] But I have many actions in my viewset and all of them have to be added separately. Is there a cleaner way to do so or a package? -
Where can I find all the django's curly brackets functions?
I'm working with django and I'm new in it. I would like to know where I can find a list of all the {} function please ? like {% if user.is_authenticated %} and all of them ? Thanks, -
Make custom form manually in Django based on a model
I am making a basic attendance record system with following models in my models.py file : Department, Employee, Absence. Absence model is as below: class Absences(models.Model): emp_id = models.ForeignKey(Employees, on_delete=models.CASCADE, null=False) leave_date = models.DateField(null=False) leave_type = models.ForeignKey(LeaveTypes, on_delete=models.CASCADE) absence_added = models.DateTimeField(auto_now_add=True) absence_updated = models.DateTimeField(auto_now=True) Now I want to create a form that lets you select date (that will be inserted in leave_date column) and a list of all employees with a dropdown (populated with leave_type) and submit button (which once clicked with save absences to database based on Absences model above. How do I do this? -
Django Heroku users_customuser table can't migrate
I have a Django project I've been developing locally for a while. It works fine on my local machine, and I am using a customuser setup so that my login auth only needs email / password, as opposed to the default Django user table which needs email / username / password. I just got my project hosted on Heroku, and can see the webpage UI get loaded fine. But I'm getting Django errors when clicking any links, and think its connected to an issue when I try to run heroku run python manage.py migrate I'm trying to run this on heroku to setup the DB, but when I do so I get an error saying: Running python manage.py migrate on ⬢ songsweeper... up, run.1353 (Free) Operations to perform: Apply all migrations: account, admin, auth, contenttypes, playlist, sessions, sites Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", … -
non_field_errors, Invalid data. DRF
when I post nested serializers in Postman it gives me following error "profile": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } but when I make the GET request it shows like that "email": null, "phone_number": null, "profile": { "first_name": "Jane", "last_name": "Doe", "interestlist_set": [ { "interest_list": [ 2, 1 ], "user": 1, "category": 1 } ] and I am posting as the same as above one more thing here interest_list is ManyToManyField it may be problem but I cannot solve this here is my model models.py class InterestName(TimeModel): name = models.CharField(max_length=255) class InterestList(models.Model): interest_list = models.ManyToManyField(InterestName) user = models.ForeignKey(Profile, on_delete=models.CASCADE) category = models.ForeignKey(ListOfInterestCategory, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) serializers.py class ProfileSerializer(serializers.ModelSerializer): interestlist_set = InterestListSerializer(many=True) class Meta: model = Profile fields = ['first_name', 'last_name', 'interestlist_set',] class UserRegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = CustomUser fields = ['email', 'phone_number','profile'] def create(self, validated_data): profiles_data = validated_data.pop('profile') user = CustomUser.objects.create(**validated_data) for profile_data in profiles_data: Profile.objects.create(user=user, **profile_data) return user here what I have tried so far I cannot make POST request in Postman how can I solve this issue? Thanks in advance! -
date-format not working on html page with datepicker
First, I'm relatively new to Django. I've seen my question addressed here with answers that I've tried to implement without success. Using a date picker that formats the date differently then how its stored and returned on the form initially. forms.py .... start_date = forms.Datefield(widget=forms.DateInput(format='%m/%d/%Y'), input_formats=['%m/%d/%Y']) queries.html .... <div class="col-4"> <label for="start_date" style="font-weight: bold;">Start Date</label> <div class="input-group date" data-provide="datepicker"> <input type="text" name="start_date" id="start_date" value="{{queryform.start_date.value}}" class="form-control"> <div class="input-group-addon"><span class="glyphicon glyphicon-th"></span></div> </div> </div> .... <form method="post"> {% csrf_token %} <script> $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, dateFormat: 'mm/dd/yyyy', changeYear: true, yearRange: "2010:2025" }); }); </script> url.py path('editqueries/<id>', views.editqueries, name='editqueries'), views.py def editqueries(request, id): query_data = get_object_or_404(Query, pk=id) if request.method == "POST": query_form = QueryForm(request.POST, instance=query_data) if query_form.is_valid(): the_query_name = query_form.cleaned_data["query_name"] # get the hidden field from the html page (but not on the # Django form) current_query_name = request.POST["currentqueryname"] # test to be sure if the names are not the same that changing # the name doesn't create a duplicate query_name if not the_query_name == current_query_name: try: test_query = Query.objects.get(query_name=the_query_name) except Query.DoesNotExist: # this is allowed. Named changed does not create a # duplicate query_form.save() query = Query.objects.all() query_flag = "None" context = {'queries': query, 'query_flag': query_flag} return render(request, 'seakerUI/queries.html', context) … -
Why JSON.stringify() return undefined and produce auth.js:65 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined?
I'm trying to login in my django application using axois and react-redux. My problem is when I entered wrong login information then the LOGIN_FAIL action is work fine but when entered correct login information the LOGIN_SUCCESS action is not work and produce the following error "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined". I have debugged my code and this line const body = JSON.stringify({ username, password }); returns undefined even username and password data is successfully received. Is the problem happened this reason? I am confused!! I have also tried to login using postman and it's working fine. How can I solve this problem? Can anyone solve my problem? Thanks in advance. Here is my action code: import axios from "axios"; import { errorMessage } from "./messages"; import { USER_LOADING, USER_LOADED, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL } from "./types"; // Login User export const login = (username, password) => dispatch => { // Headers const config = { headers: { "content-type": "application/json" } } // Request body const body = JSON.stringify({ username, password }); axios.post("/api/auth/login", body, config) .then(res => { dispatch({ action: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { dispatch(errorMessage(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL }); }); } Here is … -
How to show ForeignKey obj name on add data admin mode
How to show detail about foreignkey link pic : https://sv1.picz.in.th/images/2019/08/05/KLGvi9.png and my code in below. class Address(models.Model): line1 = models.CharField(max_length=150) line2 = models.CharField(max_length=150) postalcode = models.CharField(max_length=10) city = models.CharField(max_length=150) country = models.CharField(max_length=150) class Anniversary(models.Model): date = models.DateField() class Person(models.Model): name = models.CharField(max_length=50) birthday = models.DateField() anniversary = models.ForeignKey(Anniversary, on_delete=models.CASCADE) address = models.ForeignKey( Address, on_delete=models.CASCADE) -
How to run third party js script in Django / run client side js in server side
In my current project I have an external js script, which have some methods, I can access these methods, I also pass data to those methods & they give me output as well. Normally it works in client side. Now I am trying to do the same process in server side. For example: I've an js file which have some methods to change format of an image, I will give the image file and the expected image format as parameter then the method returns the output image. Where the process works in client side. Now I'm trying to make an REST api by using django. How can I solve my problem.. ?? Please help me. Any type of help will be appreciated. Thanks