Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: NOT NULL constraint failed: new__mainscrap_data.user_id
I'm a beginner in Django and building a login system but getting an error when passing the command python manage.py migrate The python manage.py makemigrations command is running successfully but doesn't know what happens to migrate command error I'm getting is django.db.utils.IntegrityError: NOT NULL constraint failed: new__mainscrap_data.user_id class Data(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) filename = models.CharField(max_length=40,blank=False) csv_file = models.FileField(upload_to='documents/',blank=False) def __str__(self): return self.filename -
How to access the index values in modal using Django
I am trying to access the values of data frame in the modal but the problem is that i am only be able to access the value 1st index in the modal . If I would click the modal of second or third index I am getting the value of first index. this is my code def form(request): #return HttpResponse("form") #x = sol_one() #file = pd.read_csv('C:/Users/yassa/djangoProjects/first_demo_project/PythonExport.csv') #z=file.to_html() if request.method == "POST": num1 = request.POST["num1"] #num2 = request.POST["num2"] res,destinations = bigdata(num1) soup = BeautifulSoup(res.to_html(), "html.parser") soup.find("thead").find('tr').append(BeautifulSoup('<td>Next Result</td>', 'html.parser')) for i in soup.find("tbody").find_all('tr'): temp = i.find('th').text i.append(BeautifulSoup('<td><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Open Modal</button><div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title">Modal Header</h4></div><div class="modal-body"><p></p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div></td>', 'html.parser')) #i.append(BeautifulSoup('<td><button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Open Modal</button><div class="modal fade" id="myModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h4 class="modal-title">Modal Header</h4></div><div class="modal-body"><p>'+str(destinations[int(temp)])+'</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div></div></div></td> i.find('th')[7].find('p')str(destinations[int(temp)]) print(destinations[int(temp)]) #return HttpResponse({"res":res},file.to_html()) #return HttpResponse(res.to_html()) #return HttpResponse(soup) return checking(request,soup) #return render(request,"checking.html",{'res':res}) else: return render(request,"form.html") although all the values are showing properly on console while clicking on the modal but it is repeating the value of first index on all clickable modal. this is the screenshot. -
How to search by both id and name
$input.typeahead({ minLength : 3, source: function(query, process) { return $.get("{% url 'dashboard:get-patient-list' %}", { query: query }, function (data) { console.log(data); return process(data); }); }, autoSelect: false }); $input.change(function() { // console.log($input); var current = $input.typeahead("getActive"); // console.log(current); // console.log(current.id); if (current) { // Some item from your model is active! if (current.name == $input.val()) { // This means the exact match is found. Use toLowerCase() if you want case insensitive match. } else { // This means it is only a partial match, you can either add a new item // or take the active if you don't want new items } } else { // Nothing is active so it is a new value (or maybe empty value) } }); I am using twitter bootstrap typeahead together with django. I want to make it searchable for both id and name. How can it be done? -
CSRF verification failed. Request aborted, Reason for failure is CSRF cookie not set
I want to realize a login for my site. I basically followed the online tutorial and followed the same exact way. However, I still get an error (CSRF verification failed. Request aborted.), when submitting my registration form. Can somebody tell me what raised this error and how to fix it? Here is my code: from django.shortcuts import render from rest_framework.status import ( HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND, HTTP_200_OK ) from rest_framework import status,views from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib.auth import authenticate,login,logout from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token from rest_framework.decorators import permission_classes from rest_framework.permissions import AllowAny @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): username = request.data.get("username") password = request.data.get("password") if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND) token, _ = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status=HTTP_200_OK) Getting output: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable … -
How can I read file from url?
I need to read the file that is located at this url - https://files.slack.com/files-pri/TNJHDBAGN-FNBC8EPJ5/wsgi_log.txt . How can i do this? I tried in two ways: without saving urllib.request.urlopen('https://files.slack.com/files-pri/TNJHDBAGN-FNBC8EPJ5/wsgi_log.txt').read() with conservation. with urllib.request.urlopen('https://files.slack.com/files-pri/TNJHDBAGN-FNBC8EPJ5/wsgi_log.txt') as response, open('wsgi_log.txt', 'wb') as out_file: shutil.copyfileobj(response, out_file) The result is the same - I get an html document of the following content. <!DOCTYPE html><html lang="en-US" class=""><head><script type="text/javascript" src="https://a.slack-edge.com/bv1-6-174f4d0/webpack.manifest.3e5c39dcc484c46f58ea.min.js" onload="window._cdn ? _cdn.ok(this, arguments) : null" onerror="window._cdn ? _cdn.failed(this, arguments) : null" crossorigin="anonymous"></script><script>window.ts_endpoint_url = "https:\/\/slack.com\/beacon\/timing";(function(e) { var n=Date.now?Date.now():+new Date,r=e.performance||{},t=[],a={},i=function(e,n){for(var r=0,a=t.length,i=[];a>r;r++)t[r][e]==n&&i.push(t[r]);return i},o=function(e,n){for(var r,a=t.length;a--;)r=t[a],r.entryType!=e||void 0!==n&&r.name!=n||t.splice(a,1)};r.now||(r.now=r.webkitNow||r.mozNow||r.msNow||function(){return(Date.now?Date.now():+new Date)-n}),r.mark||(r.mark=r.webkitMark||function(e){var n={name:e,entryType:"mark",startTime:r.now(),duration:0};t.push(n),a[e]=n}),r.measure||(r.measure=r.webkitMeasure||function(e,n,r){n=a[n].startTime,r=a[r].startTime,t.push({name:e,entryType:"measure",startTime:n,duration:r-n})}),r.getEntriesByType||(r.getEntriesByType=r.webkitGetEntriesByType||function(e){return i("entryType",e)}),r.getEntriesByName||(r.getEntriesByName=r.webkitGetEntriesByName||function(e){return i("name",e)}),r.clearMarks||(r.clearMarks=r.webkitClearMarks||function(e){o("mark",e)}),r.clearMeasures||(r.clearMeasures=r.webkitClearMeasures||function(e){o("measure",e)}),e.performance=r,"function"==typeof define&&(define.amd||define.ajs)&&define("performance",[],function(){return r}) // eslint-disable-line })(window);</script><script> (function() { window.TSMark = function(mark_label) { if (!window.performance || !window.performance.mark) return; performance.mark(mark_label); }; window.TSMark('start_load'); ... Will you really have to use selenium? Code where I get the file from the message in the slack class Events(APIView): def post(self, request, *args, **kwargs): slack_message = request.data if slack_message.get('event').get('type') == 'message': message = Message.objects.create( text=slack_message['event']['text'] ) if 'files' in slack_message['event']: message.filetype = slack_message['event']['files'][0]['filetype'] message.file_name = slack_message['event']['files'][0]['title'] message.file_link = slack_message['event']['files'][0]['url_private'] message.with_file = True message.save() https://dpaste.de/8ufT -
NoReverseMatch at /profile/preview/ when argument contains special character or space
Getting NoReverseMatch at /profile/preview/ only when argument contains special character or space. for argument without special character or space works fine return HttpResponseRedirect(reverse('profile-by-username', kwargs={'username': c.username})) url(r'^preview/(?P<id>\d+)/?$', views.preview, name='profile-preview') -
How one docker container can modify the file of another?
My docker-compose file is as follows: version: '3' services: db: image: mongo:4.2 container_name: mongo-db restart: always environment: MONGO_INITDB_DATABASE: VMcluster ports: - "16006:27017" volumes: - ./initdb.js:/docker-entrypoint-initdb.d/initdb.js web: build: context: . dockerfile: Dockerfile_Web command: python manage.py runserver 0.0.0.0:8000 container_name: cluster-monitor-web volumes: - .:/vmCluster_service ports: - "9900:8000" depends_on: - db cronjobs: build: context: . dockerfile: Dockerfile_Cron command: ["cron", "-f"] container_name: cluster-monitor-cron I want to implement a feature where the user should be able to update the crontab from the Django web. how can I make Django container to access the crontab container and update the crontab? -
How to read csv headers
So this is my uploading csv or excel file looks like. So my question is, when a csv file is selected using "upload file" then I want to see the "headers" of csv file and display it before the "submit" button so that users can select which "header" they want. Only after that "submit" the csv file to upload. -
Should I use mongoengine.Document or models.Model when Using mongodb but also django
Until now I worked with models.Model . But currently i need to work with Mongodb. Should I continue with models.Model or should I use mongoengine.Document? Any suggestions/(dis-)advantages you know? class ViewerRequestLog(mongoengine.Document): VS class ViewerRequestLog(models.Model): -
How to switch a boolean field when there is a change in another field in django?
I'm trying to switch a boolean feild (tagged) when there is a change in the manytomany feild(tag). How can i do that? I'm trying to switch a boolean feild (tagged) when there is a change in the manytomany feild(tag). How can i do that? class Tagger(models.Model): tagged = models.BooleanField(default = False) appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True) tag = models.ManyToManyField(Tag,blank=True) I expect the 'tagged' field to switch to True when there is an input in 'tag' and vice versa. -
display sum per user elegantly in django
trying to display the final mark per student. But instead of just showing the result of sum , it displays a chunk of query set: for example: Annie <QuerySet [{'studName': None, 'attendance__sum': 3}, {'studName': 1, 'attendance__sum': 2}, {'studName': 2, 'attendance__sum': 1}]> and same goes to the rest of the students. I would like to display it like : Annie 2 Benny 3 Charlie 4 My view: def attStudName(request): studentName = MarkAtt.objects.all() mark = MarkAtt.objects.values('studName').annotate(Sum('attendance')) context = { 'studentName' : studentName, 'mark' : mark } return render(request,'show-name.html',context) My template: {% for y in mark %} {% for x in studentName %} <p>{{x.studName}}</p> <p> {{mark}}</p> {% endfor %} {% endfor %} How do i display each student name with their own mark accordingly? And how do i display the mark without the Thank you in advance. -
OneToOne field is not saving?
Here Leave model has OneToOne relation with django User model.I am saving some leaves through my MakeLeaveForm and I tried like this but it is not saving staff. I have returned the form.erros and it is displaying staff. What i am doing wrong here? models.py class Leave(models.Model): staff = models.OneToOneField(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() day = models.IntegerField(default=0) is_viewed = models.BooleanField(default=False) is_accepted = models.BooleanField(default=False) forms.py class MakeLeaveForm(forms.ModelForm): class Meta: model = Leave fields = '__all__' views.py def send_leave_request(request): form = MakeLeaveForm() if request.method == 'POST': form = MakeLeaveForm(request.POST) if form.is_valid(): leave = form.save(commit=False) leave.staff= request.user # tried with request.user.pk leave.is_viewed = False leave.is_accepted = False leave.save() return redirect('organization:view_leaves') else: return HttpResponse(form.errors) return render(request,'organization/send_leaves.html',{'form':form}) -
django jquery scrolling does not activate
I have a jquery function that works when I run that as an event, but does not work when I try to get it to run when the document reloads. This is my element for the window to scroll to when the page refreshes. {% block content %} {% for poll in polls %} <button class="test" id="{{ poll.id }}">{{ poll.id }}</button> {% endfor %} {% endblock %} This code below works fine, it's attached to a click event. {% block jquery %} {# <script>#} testEvent(); // sending the poll id to report after the flag is clicked on function testEvent() { $(".test").click(function(event){ event.preventDefault(); var scrolltoid = document.getElementById('54') scrolltoid.scrollIntoView(true); window.scrollBy(0, -50); }); }; {# </script>#} {% endblock %} I need the code to work when the page refreshes. However, when the same code is inserted into document ready function to scroll the window to the specific element when the page refreshes, it is not working. {% block jquery %} {# <script>#} $(document).ready(function(){ var scrolltoid = document.getElementById('54') scrolltoid.scrollIntoView(false); }) {# </script>#} {% endblock %} I also tried running the alternative code below. I saw the scroll successful very quickly for just a split second, but when the page completely refreshes, my window … -
Which Database should be used for ReactJS & Flutter/React-Native & Django
I'm going to do my FYP and now a bit confused on which database should I use. I'm going to use ReactJS for web, either React-Native/Flutter for mobile, and Django REST for backend API. I did a bit of research and found several options such as MongoDB, Firebase, and PostgreSQL. Which one do you think is the most suitable database for my project? Or do you have any other recommendations? -
while using django-filter for filtering how to export the filtered values into csv file
I have used django-filter module for filtering. Want to export the results into CSV file. def bfs_version_filter(request): version_obj = bfs_versions.objects.all() filter_obj = version_filter(request.GET, queryset = version_obj) response = HttpResponse(content_type = 'text/csv') file_name = "version_filter"+str(date.today())+".csv" response['Content-Disposition'] = 'attachment; filename = "'+ file_name +'"' #edited by vennilam writer = csv.writer(response) for i in filter_obj: writer.writerow(i) return response Getting below error: TypeError at /bfslite/version_filter/ 'version_filter' object is not iterable -
How to fix error "invalid literal for int() with base 10: 'Independence' Django?
I am a newbie in Django and I am building a quiz application. I want to be able to import some questions from a CSV file in Django using the import_export.admin method on the admin site, When I try to import, the contents of my CSV file which contains the list of questions does not append to my existing list of questions, instead, it throws an error "invalid literal for int() with base 10: 'Independence'." I have tried changing the format of the CSV file I am uploading from comma-separated Values to CSV UTF-8(Comma-delimited). I also tried using integers in the 'Category' column, but it gives a 'Traceback (most recent call last) Category matching query does not exist' error. Any help? my admin.py file: class QuizAdmin(admin.ModelAdmin): form = QuizAdminForm list_display = ('title', 'category', ) list_filter = ('category',) search_fields = ('description', 'category', ) class CategoryAdmin(admin.ModelAdmin): search_fields = ('category', ) class MCQuestionAdmin(ImportExportModelAdmin): list_display = ('content', 'category', ) list_filter = ('category',) fields = ('content', 'category', 'figure', 'quiz', 'explanation', 'answer_order') search_fields = ('content', 'explanation') filter_horizontal = ('quiz',) inlines = [AnswerInline] my models.py file: class CategoryManager(models.Manager): def new_category(self, category): new_category = self.create(category=re.sub('\s+', '-', category).lower()) new_category.save() return new_category class Category(models.Model): category = models.CharField( verbose_name=_("Category"), max_length=250, blank=True, … -
Wtform FieldList rendering in Django Template
I have declared 2 form like this. class TripItemForm(Form): ..... class ShiftMainform(Form): trip_list = FieldList(FormField(TripItemForm),validators=[checking_time]) Now in django view class I have initialize this trip_list field like this class DjangoView(View): def get(self, request, id): form = ShiftMainform() form.trip_list = list_trips #here list_trips is the list of TripItemForm objects. context = { 'form': form, } return render(request, 'example.html', context) When the html file rendered it shows that form.trip_list is empty. Can anyone tell me why is this happen? What I've done wrong or what should be the right way to render FieldList field in django tempalte. Thanks in advance. -
NoReverseMatch error when returning Respose object in django rest framework
I am trying to build an Instagram clone. Clicking the follow button calls ajax. My view def post saves "follows" and returns the Response object whose data is true/false values for whether or not the user was previously followed. error message ‘django.urls.exceptions.NoReverseMatch: Reverse for 'profile' with arguments '('',)' not found. 2 pattern(s) tried’ views.py def post(self, request, *args, **kwargs): followed_user = get_object_or_404(USER, username=kwargs.get('username')) if request.user.is_authenticated: follower_user = request.user if followed_user == follower_user: raise PermissionError('Unable to follow yourself') else: if follower_user in followed_user.followers.all(): followed_user.followers.remove(follower_user) return Response({ 'follow_exist': False }) else: follower_user.follows.add(followed_user) return Response({ 'follow_exist': True }) else: return redirect('insta/login') urls.py path('<username>/', insta_profile, name='profile'), ajax $.ajax({ type: 'POST', url: '{% url 'insta:profile' username=target_user.username %}', data: {'csrfmiddlewaretoken': '{{ csrf_token }}'}, success: function (response) { if (response.follow_exist) { $this.attr('class', 'btn btn-outline-secondary'); $this.text('cancel follow') } else { $this.attr('class', 'btn btn-primary'); $this.text('follow') } }, error: function (response) { console.log(JSON.stringify(response)) } }); Could you tell me why this happens? Thank you in advance. -
how to setup image background for songs from albums user JS
I have base data in which have name song and image album . I want setup this image as background image with blur effect, but me need : 1) image for albums where have all song with of this album 2) after added song in favourite songs, after click on next song , need change image according with image album <div class="col"> <div id="container"> <div id="audio-img"> <img src="{{ album_id.image_album.url }}"> </div> <div id="audio-player"> <div id="audio-info"> <span class="artist"></span> - <span class="title"></span> </div> <input id="volume" type="range" min="0" max="10" value="5"> <br> <div id="audio-buttons"> <button id="prev"></button> <button id="play"></button> <button id="pause"></button> <button id="stop"></button> <button id="next"></button> </div> <div class="clearfix"></div> <div id="tracker"> <div id="progressbar"> <span id="progress"></span> </div> <span id="duration"></span> </div> <div class="clearfix"></div> <ul id="playlist"> {% for song in songs %} {% if song.album.id == album_id.id %} <li path="{% static 'music/'%}uploads/{{song.name_song.url}}" song="{{song.name_song}}.mp3" artist="{{ album.author_album }}"> {{ song.name_song }} {% if is_favourite %} <a href="{% url 'music:favourite' pk=song.id %}"> <i class="fas fa-heart"></i> </a> {% else %} <a href="{% url 'music:favourite' pk=song.id %}"> <i class="far fa-heart"></i> </a> {% endif %} </li> {% endif %} {% endfor %} </ul> </div> </div> </div> -
How to update information on html without refreshing in Django?
I would like to update html page without refreshing the page using views.py + ajax. Can someone help me? I already took a look at: Django: updating src on iframe without refreshing views.py def save_form(request): if request.method == 'POST' and 'calculate' in request.POST: lsection = [5] return JsonResponse({'lsection':lsection}) html + javascript <form method="post" action = "/myproject/save/" enctype="multipart/form-data"> {% csrf_token %} <label for="cost">{{request.lsection}}</label> <input type="submit" name ="calculate" value="Calculate"> </form> <script type="text/javascript"> function cost() { $.ajax({ method: "POST", url: "save_form", data: {}, success: function(data) { alert("test"); // Update $('label[for="cost"]').contents().last()[0].textContent=data.lsection } }) }; </script> When I click Calculate, what I get is "{"lsection": [5]}". Do you know how to update only the label? -
Show a specif data from a database table in django admin
my database model is like class Restaurant(models.Model): email_sent = models.BooleanField(null=True, default=False) rest_owner = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='rest_owner') is_approved = models.BooleanField(null=False, default=False) I want to create a separate table where I can show data of just fields where is_approved=0 . its simple in django Site. But I am unable to find a way to do this in djangoAdmin side. Or I have to make a custom admin for this ? -
How to show a specific content to specific user in Django
I'm a beginner at Django, I am building a login system in which I want to display the specific data to specific user like if a user uploads something to the database so only that user should be able to see that file. I am expecting a few codes to get an idea for the logic. -
How can I delete unapplied migrations?
I would like to delete only unapplied migrations, showmigrations gives: [X] 0011_auto_20190917_1522 [X] 0012_auto_20190917_1600 [ ] 0013_auto_20190917_1638 [ ] 0014_auto_20190917_1647 [ ] 0015_auto_20190917_1652 [ ] 0016_auto_20190917_1654 [ ] 0017_auto_20190917_1704 ... I have 21 unapplied migrations! The question is when migrations are unapplied, don't have any effect on database, right? Can I just delete them from "myapp" migrations folder and after that to do makemigrations and migrate again? -
django setup in pycharm
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: virtualenvwrapper-win in ./.local/lib/python2.7/site-packages (1.2.5) Requirement already satisfied: virtualenv in ./.local/lib/python2.7/site-packages (from virtualenvwrapper-win) (16.7.5) I am getting error while setting up Django in Pycharm using terminal. can anyone give me step by step tutorial for setting up Django in Pycharm.. Blockquote -
How to validate phone number in django?
I'm currently using phonenumbers package as a validation method to my django's UserCreationForm for its phone number field. In my current code I am using a get method to retrieve the phone number from its field and then do the validation. If the entered number does not exists, a form error is supposed to pop up and state that the number is not in a country's format (in this case i'm using singapore). Please tell me what changes should be made to my current code. I've tried using "from phonenumber_field.formfields import PhoneNumberField" for the phone number validation and it validates the number I've entered, the only problem is that the users will have to type their country code and I cannot have that. I'm using just the phonenumbers package so that users will not have to enter the country code. /* forms.py */ import phonenumbers from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from validate_email import validate_email from phonenumber_field.formfields import PhoneNumberField class UserRegisterForm(UserCreationForm): email = forms.EmailField() # phone_number = PhoneNumberField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email', 'phone_number'] def clean_email(self): email = self.cleaned_data.get("email") if not validate_email(email, verify=True): raise forms.ValidationError("Invalid email") return …