Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File "manage.py", line 16 ) from exc (( SOLVED ))
IF enter image description here In case of anyone having the same trouble as me with ur dajngo stop working, i found out: it was because i install NodeJS recently, and it installed a python 2.7 and changed the python path. So, if run a "python manage.py runserver" it will first look at 2.7 path. (if i run "python --version" it shows 2.7) To solve it, first go to your "C:\Users(your username)\AppData\Local\Programs\Python\Python38-32(or latest)" copy it, go to ur System Properties -> Environment variables -> PATH -> add(python path) or move it up to be the first one. Open CMD, run "python --version", it should now shows the latest version. Done! -
504 Gateway Time-out GraphQL django in development side error
I'm trying to build a graphql API using django. As it exists on the documentation, I added the following line to <project>/urls: from graphene_django.views import GraphQLView urlpatterns = [ ... path('graphql', GraphQLView.as_view(graphiql=True)), ] It worked well for a while, but after a short period of time I faced to 504 Gateway Time-out. PS I also have insomnia app and it works fine. but I don't know what is the problem with this one? -
Table first row becomes huge when few rows to display
I'm creating a bootstrap table (or just a regular table, I stripped all bootstrap classes and still have the same issue). The Problem In one set of data, where I pass 16 elements the sizing is fine. It expands when the screen height increases which I'm not a huge fan of but figured I'd mention incase it helps find a solution. But in the other case where I pass 8 elements to the table, the first row becomes absolutely massive see this link https://imgur.com/a/o3jR9IB. What I've tried I've tried clearing every class and every style within the table and its elements yet the problem persists. I've tried nesting the td's within div's that have a set height, overflow hidden, and white-space nowrap, and the problem persists. Same thing if I just put raw text into the td's. I've tried to clear all margins and padding within the table and the problem persists. Setting the style on my table to 'table-layout: fixed;' also did nothing. Code example (latest try; includes Django templates) <div class='mx-5'> <div class='table-responsive'> <table class="table table-striped table-dark shadow"> <thead class='text-center'> <tr> <th class='p-0 m-0' scope='col'>Rank</th> {% for header in headers %} <th class='p-0 m-0' scope='col'>{{header}}</th> {% endfor %} … -
I'm trying to do uploading data to database using ajax Django,But it does't work properly
I'm a beginner in Django. I have to upload data to the database using ajax. For that, I'm trying some code but it doesn't work properly. I can't upload data using these codes. Is this right way of ajax coding models.py class Notifications(models.Model): owner = models.ForeignKey(User, null=True, blank=True,on_delete=models.CASCADE) property = models.ForeignKey(Property, null=True, blank=True,on_delete=models.CASCADE) notification = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str_(self): return self.notification views.py def notification(request): user = request.user if request.method == 'POST': property_id = request.POST['property_id'] owner = request.POST['owner_id'] property_object = Property.objects.get(id=property_id) owner_object = User.objects.all().get(username=owner) notification = user, "have intrested in your property", property_object.headline property_object.notify.add(user) notifications = Notifications.objects.create(notification=notification, property=property_object, owner=owner_object) notifications.save() return JsonResponse({'msg':'success'}) ajax <form action="{% url 'like_post' %}" method="post" id="notify_form" > {% csrf_token %} <input type="hidden" name="owner_id" value="{{ accomodation.owner }}"> <button id="request-btn" name="property_id" value="{{ accomodation.id }}" class="btn btn-primary">Contact info:</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript">` $(document).ready(function(e){ $(document).on('submit','#request-btn',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'notification' %}", data:$('#notify_form').serialize(), dataType:'Json', success:function(data){ if(data,msg == "success"){ alert('data submitted') } } }); }); }); ` -
Why can't I upload images to Django app running on Ubuntu server?
So I'm trying to upload images to my Django application running on Ubuntu server. I have everything that is required, but somehow when I post it, I don't see any images saved. I've checked the Admin, but the field is empty. The thing is, I DON'T GET ANY ERROR MESSAGES. The whole process works fine, except that the field remains empty. Let me show you my code first.models.py class NewEvent(models.Model): objects = models.Manager() img1 = models.ImageField(null=True, blank=True, upload_to="everyday_img") ... forms.py class NewEventForm(forms.ModelForm): ... img1 = forms.ImageField(required=False) ... views.py def inputNew(request): form = NewEventForm(initial={'authuser':request.user}) if request.method == 'POST': form = NewEventForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.authuser = request.user instance.img1 = request.FILES.get('img1') instance.save() ... And the template for uploading image. <form method="post" class="form-group" enctype="multipart/form-data">{% csrf_token %} <div class="row"> <div class="col"> <div class="everyday-img-input">{{form.img1|as_crispy_field}}</div> </div> </div> </form> I've also tried the chmod command, and taken care of the permission. There's nothing wrong there. What do you think is the problem? Thank you very much in advance. :) -
How does django handle cached_property invalidation in a request/response cycle?
Say I have a model with a cached property: class MyModel(models.Model): name = fields.Charfield() @cached_property def count_friends(self): return self.friends_set.count() Django states that: The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned. How does this means cached_property works in the request/response cycle? For example, if I only use object.count_friends in a template, will it be refreshed each time the view is called (assuming browser cache is cleared!)? Have I understood this correctly? E.g. each time I make a call to the DB, I assume it's refreshed? In what practical circumstances would it not be refreshed? -
Cannot import my application in url.py file in Django
I am completely new in Django and currently learning django from Udemy course. First, I created my django project and then created my application. I have inserted my application on settings.py in INSTALLED_APPS of project folder and then re run the the server as well. Now, I have created a view in my application folder and want to use that in url.py of project folder. I could not able to import it as its showing that package not found. Please see my program structure below File structure I have written the code on pycharm IDE. My code in url.py is below from django.contrib import admin from django.urls import path from firstApp import views urlpatterns = [ path('^$', views.index, name='index'), path('admin/', admin.site.urls), ] Please help me out here. thanks in advance. -
how to display results(dataframe) from a python script in django
class TweetAnalyzer(): """" Class for tweet analysis """ def tweet_to_data_frame(self, tweets): df = pd.DataFrame(data=[tweet.text for tweet in tweets ], columns=['tweets']) df['id']= np.array([tweet.id for tweet in tweets]) df['len'] = np.array([len(tweet.text) for tweet in tweets]) return df #this is the python script class views.py from Filmatory.tweetstream import TweetAnalyzer def tweetsPageView(request): object = TweetAnalyzer() x = object.tweet_to_data_frame('pandas.txt') return render(request,'tweets.html',{'x':x.to_html}) -
Ajax refresh browser to return page with the JSON data (Django)
I'm trying to make a simple todo page in my app, and I tried to use ajax for a better user experience. However, when I submit data I get a page with the data in JSON form instead of appending new data ( i use Django). views.py: from django.shortcuts import render, redirect from django.http import JsonResponse from django.forms.models import model_to_dict from django.contrib import messages from .forms import TodoForm def create_todo(request): if request.method == 'POST': form = TodoForm(request.POST) todo = form.save(commit=False) todo.user = request.user todo.save() messages.success(request, 'Creted Todo, Good Luck!') return JsonResponse({'todo': model_to_dict(todo)}, status=200) the todo form in base.html: <div class="modal fade" id="createtodo" tabindex="-1" role="dialog" aria-labelledby="createtodoLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="createtodoLabel">Create Todo</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="{% url 'production:create_todo' %}" method="post" id="todoForm" data-url = "{% url 'home' %}"> {{todo_form|crispy}} {% csrf_token %} </div> <div class="modal-footer"> <input type="submit" value="Add" class="btn btn-success"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#todos"> Todos </button> </form> </div> </div> </div> </div> Ajax Script in base.html <script> $('#todoForm').submit(function (event) { event.preventDefault() let data = $('#todoForm').serialize() $.ajax({ url: $('#todoForm').data('url'), data = data, type = 'post', success: function (response) { $('#todosList').append(`<div class="card"> <div class="card-body todoItem" id=""> <input type="checkbox" name="" … -
DJANGO RESTFRAMEWORK WITHOUT ORM METHOD [closed]
Is there any tutorials or book for django rest framework without using orm method ? please suggest me -
Accessing account information in Django Allauth confirmation email
I am using a custom e-mail message by overriding the default confirmation email of Django Allauth email_confirmation_message.txt I have a custom signup form that also collects first and last name so I would like to access the first name that they have given during signup, in my e-mail confirmation. So you can address someone with his first name. This is what the default template looks like: {% load account %} {% user_display user as user_display %} {% load i18n %} {% autoescape off %} Dear {{ first name given at registration here }} ... {{ activate_url }} ... {% endautoescape %} It uses {% user_display user as user_display %} to display the username. So there must be a way to access the first name as well? How can I access the first name in this e-mail? Or is this not possible without completely writing a custom confirmation e-mail? -
'bytes' object has no attribute 'objects'
def searchfromimage(request): image_file = request.FILES['file'] os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'home/ServiceAccountToken.json' client = vision.ImageAnnotatorClient() content = image_file.read() image = vision.types.Image(content=content) response = client.document_text_detection(image=image) docText = response.full_text_annotation.text docText.replace('\n',' ') searchquery = docText allposts = content.objects.filter(title__icontains=searchquery) context = {'allposts':allposts} return render(request,'searchpage.html',context) when I am trying to print docText it gives the desired output but I am not able to use it to search it showing the error 'bytes' object has no attribute 'objects' I have tried to decode 'utf-8' but it is giving 'str' object has no attribute 'decode' error and I also tried with base64 and ASCII but nothing is working -
validate if instance exists django
I am building a REST Api on DRF. I have a ModelViewSet endpoint from rest_framework.viewsets. I have a Post and a Comment model. Each comment belongs to a post. So I have defined 2 endpoints, sort of: 1) router.register(r"posts", views.PostView 2) router.register(r"(?P<pk>[^/.]+)/comments", views.CommentView Both of them inherit from ModelViewSet so I can perform CRUD operations on them. I have a question regarding the second endpoint. Since we create comments to posts, I am getting a post pk from posts/int:pk/comments. But the problem is when I do a GET request on this endpoint it'll return the list of all comments, but I need those to belong to a post (id in url). When I try make a POST request on this endpoint if the post does not exist it raises DoesNotExist error which is logical. What I have done so far is: redefined a get_queryset() to retrieve only objects belonging to a particular post. If the post does not exist it returns an empty list (though I think it should raise 404) redefined validate() in my serializer to check if the post exists. Returns 404 if it does not But when I check PUT, DELETE, PATCH methods on posts/int:pk/comments/int:pk it won't … -
How do I check for the existence of a specific record in Django?
If I retrieve a QuerySet from a Django model (using filter(), for example), I can use the QuerySet methods exists() or count() to determine if the result will be void or not: if myModel.objects.filter(id__lte=100).exists(): # Do something... However, if I want to retrieve a specific record (using get(), for example) myModel.objects.get(id=100) the record object returned has no exists() or count() method. Moreover, if this record doesn't exist, instead of doing the expected thing and returning None, Django flips its crap entirely and breaks with a DoesNotExist exception, so I can't even test for the record's existence in the normal Pythonic way: # This throws a DoesNotExist exception if not myModel.objects.get(id=100): # Do something else... How do I test for the existence of a specific record (an element of a QuerySet, not a QuerySet itself) so that the app doesn't break? (Django 3.0) -
Profile Model in django not saving new update
i trying to create update profile, but its doesnt work i think its because instance(?) but i cant fix it, please help to solve my problem this is my views.py post_update def post_update(request, pk): instance = User.objects.get(pk=pk) instance2 = Profile.objects.get(pk=pk) user_form = PasswordChangeForm(user = request.user , data=request.POST) profile_form = ProfileForm(request.POST, instance=instance2) postingan = Profile.objects.filter(id=pk) postingan2 = User.objects.filter(id=pk) if user_form.is_valid(): instance = user_form.save(commit=False) instance.save() return render(request, 'pengurusan/index.html') if profile_form.is_valid(): instance2 = profile_form.save(commit=False) instance2.save() return render(request, 'pengurusan/index.html') context={ "user_form" : user_form, "profile_form" : profile_form, "instance2" : instance2, "postingan" : postingan, "instance" : instance, "postingan2" : postingan2, } return render(request, 'pengurusan/update-form.html', context) and this is my forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['nama', 'nik', 'email', 'nomor_hp'] widgets = { 'nama': forms.TextInput(attrs={ 'id' : 'exampleFirstName', 'placeholder' : 'Name'}), 'nik' : forms.NumberInput(attrs={'id' : 'exampleLastName', 'placeholder' : 'Nomor Identitas Penduduk'}), 'email' : forms.EmailInput(attrs={'id' : 'exampleInputEmail', 'placeholder' : 'Email Address', 'name' : 'email'}), 'nomor_hp' : forms.NumberInput(attrs={'size':'4', 'maxlength':'12', 'class':'phone', 'placeholder' : 'Nomor Handphone'}), } and this is my models.py userr = User() class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) nama = models.CharField(max_length=30, blank=True) nik = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=75, blank=True) nomor_hp = models.TextField(max_length=15, blank=True) def __str__(self): return self.user def create_profile(sender, instance, created, … -
Is there any way to run manage.py collectstatic command in CPANEL?
I tried to host my app in CPANEL. Everything works fine but when I try to collect static files through python manage.py collectstatic, It shows error. python manage.py collectstatic File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax The python app on my cpanel is version 3.7.3 and I have also completed my app in Python version 3.7.3 -
Why do I have to keep all django applications in root folder?
Topic explains everything by itself. In all other web-frameworks (Symfony etc.) there is a clear separation of the folder structure logic. It is more logical and easier to observe and maintain. Why it isn't so in Django, why is it so messy? Yes, I have seen that solution, but it still seems strange... -
Validate get_queryset GET parameters
I am building an application that allows user to view certain records from the database. Since I want the users to be able to filter the number of records per page via the paginate_by attribute I also want to validate that input. Here is a snipped of my code. def get_queryset(self): q = self.request.GET.get('paginate_by') if q is None: return Syslog.objects.all() elif ( int(q) > 0): return Syslog.objects.all() else: raise PermissionDenied Firstly I am getting the queryset and more specifically the paginate_by parameter and I am trying to validate it. When a user provide a positive integer or the home page the view returns the queryset. If the user provide a negative number a PermissionDenied is returned. The problem is that when the user provide a string, it throws a 500 Server Error. What I am trying to do is to check if the provided GET parameter is positive integer or None (for home page), and if it is not to render a custom error template. Regards, Jordan -
ModelChoiceField: remove empty option and select default value
I'm using the default form field for a models.ForeignKey field, which is a ModelChoiceField using the Select widget. The related model in question is a Weekday, and the field was made nullable so that it didn't force a default value on hundreds of existing entries. However, in practice, our default should be Sunday, which is Weekday.objects.get(day_of_week=6). By default the select widget for a nullable field when rendered displays the null option. How can I discard this option and have a default value instead? If I set a initial value, that one is selected by default on a new form: self.fields['start_weekday'].initial = Weekday.objects.get(day_of_week=6) But the empty value is still listed. I tried overriding the widget choices: self.fields['start_weekday'].widget.choices = [(wd.day_of_week, wd.name) for wd in Weekday.objects.all()] However now Sunday isn't selected by default. I thought maybe I need to use the option value as the initial one but that didn't work either: self.fields['start_weekday'].initial = Weekday.objects.get(day_of_week=6).pk In short: how can I remove the empty option in a nullable model field and select a default instead? -
Pyodbc - Invalid connection String- Login failed for user
Im getting this error, trying to connect an external SQL Server from Django through VPN i tried different ways of formatting the string, but doesnt work. '28000', "[28000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Login failed for user 'sa'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver Manager] Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Login failed for user 'sa'. (18456)") The code: from django.http import HttpResponse from django.shortcuts import render from django.template import loader import pyodbc def stock(request): #ConDB password='eUHf?+adF6;w' server='tcp:10.10.45.1,1433' database='master' username='sa' cnxn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() template = loader.get_template('polls/stocks.html') return HttpResponse(template.render({}, request)) Thank you in advance. -
In Django, how can I load images based on screen size?
Apologies for not having specific broken code here. I already know that what I would try won't work from a different question here, and I have a vague idea of something that might work, but is likely not the best way to do it. I'm building a website for a photographer, so it's important that I'm loading the best looking photos that the user is capable of seeing. The starting file size for the images is a few MB, but the model uses Pillow to save down-scaled copies. There are times when I want a full-screen image at high resolution, but I want to serve a smaller image if the user is on mobile, for example. What I would have done was load the images from CSS background-image with media queries, but I understand that I can't use template tags in css. My next guess would be to build two separate versions of each template, and have the views render a different template based on the user-agent of the request, but that strikes me as probably not a great solution to put that much trust in the request headers, and the functionality could break as easily as a new browser … -
I am getting an Attribute Error when attempting POST request to API - Django
im using Django and DRF to make a very basic API, however when i use a POST request, i get an error i cant solve for some time now. This is the Views.py def user_list(request): """ List all code users, or create a new user. """ if request.method == 'GET': users = Users.users.all() serializer = UserSerializer(users, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request.body) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) This is the traceback Internal Server Error: /users/ Traceback (most recent call last): File "C:\Users\35988\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\35988\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\35988\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\35988\Desktop\GitHubRepos\DjangoSalesPlatform\SalesPlatform\Sales\views.py", line 36, in user_list data = JSONParser().parse(request.body) File "C:\Users\35988\anaconda3\lib\site-packages\rest_framework\parsers.py", line 65, in parse return json.load(decoded_stream, parse_constant=parse_constant) File "C:\Users\35988\anaconda3\lib\site-packages\rest_framework\utils\json.py", line 31, in load return json.load(*args, **kwargs) File "C:\Users\35988\anaconda3\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "C:\Users\35988\anaconda3\lib\codecs.py", line 496, in read newdata = self.stream.read() AttributeError: 'bytes' object has no attribute 'read' [30/Jul/2020 14:16:43] "POST /users/ HTTP/1.1" 500 87662 -
Adding extra field with Many to many relationship in DRF
I have scenario where I need to add the extra field with the ManytoMany relationship. But when I am trying to do so I am getting the error. My model class is as: class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): quantity = models.IntegerField() members = models.ForeignKey(Person,on_delete=models.CASCADE) class Membership(models.Model): code = models.CharField(max_length=64) group = models.ManyToManyField(Person, through='Group') date_joined = models.DateField() invite_reason = models.CharField(max_length=64) What I am looking here is in a Membership modal I want my code to be unique and in group I want the multiple person with quantity but something I am doing wrong and I am getting the error and my error is : The model is used as an intermediate model by 'oss.Membership.group', but it does not have a foreign key to 'Membership' or 'Person'. Any suggestions will be of great help. Thanks in advance -
How to do GET request from Jquery-confirm dialog to django view and show results inside dialog?
I am trying to make an app from Django(version 3.0) and Python 3.7 and also involves the use of Jquery(version 3.5) and jquery-confirm (version 3.3.4). I am using jquery-confirm dialog to display content to my users like this, In the Custom Javascript File for Project- var showRecipeToEnterButton = $('#show-recipe-to-enter'); showRecipeToEnterButton.click(function(){ showRecipeToEnterButton = $(this); var accTypeInput = showRecipeToEnterButton.parent().children("#acc_type")[0]; var accType = accTypeInput.value; var userInput = showRecipeToEnterButton.parent().children("#user_pk")[0]; var userPk = userInput.value; var contestInput = showRecipeToEnterButton.parent().children("#contest_pk")[0]; var conPk = contestInput.value; $.dialog({ title: 'Select '+accType, content: "url:/contest/get/user/?&pk="+userPk+"&cpk="+conPk+"&at="+accType, theme:'modern', animation: 'scale', columnClass: 'large', closeAnimation: 'scale', backgroundDismiss: true, draggable: false, }); }); The content field in the $.dialog() function is a url and it leads to this function in my views.py: def contest_select_recipe_foodpost(request): data = request.GET user = data.get('pk') acc_type = data.get('at') cpk = data.get('cpk') if cpk is None or user is None or acc_type is None: return HttpResponse('<h4>Insufficient Data!</h4>') contest = Contest.objects.get(pk=cpk) qs = None if acc_type == 'Food Recipe': qs = Recipe.objects.filter(user__pk=user) if acc_type == 'Food Post': qs = FoodPost.objects.filter(user__pk=user) if not qs.exists(): qs = None context = { 'qs': qs, 'contest': contest, 'cpk': cpk, 'at': acc_type, } return render(request, 'contest/entry_filter_foodpost.html', context=context) This is the contest/entry_filter_foodpost.html {% load static %} {% if qs == … -
Run django jupyter note book in custom server and port
Script i am using to run jupyter. python manage.py shell_plus --notebook Using this script it runs on localhost thats fine, But i can is run it inside server with custom port python manage.py shell_plus --notebook 0.0.0.0:8000 When m running like thism getting error usage: manage.py shell_plus [-h] [--bpython | --idle | --ipython | --lab | --kernel | --notebook | --plain | --ptipython | --ptpython] [--connection-file CONNECTION_FILE] [--no-startup] [--use-pythonrc] [--print-sql] [--print-sql-location] [--dont-load DONT_LOAD] [--quiet-load] [--vi] [--no-browser] [-c COMMAND] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] manage.py shell_plus: error: unrecognized arguments: 0.0.0.0:8000 PLease have a look