Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to download Django 2.7 in windows 10
DISCLAIMER - I am new to the world of Django and Python. If the question sounds stupid, please bear with me. OS - Windows 10 Python Version Installed - 3.7 In the windows command prompt, I am trying the following command to download django on my system. pip install django pip3 install django Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError(': Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))': /simple/django/ Could not find a version that satisfies the requirement django (from versions: ) No matching … -
AttributeError at /api/list/ 'NoneType' object has no attribute 'delete'
class StatusListSearchApi(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, ListAPIView): # queryset=status.objects.all() serializer_class=statusSerializer lookup_field='id' # return Response(serializer.datax) def get_queryset(self): request=self.request qs=status.objects.all() query=request.GET.get('q') if query is not None: qs=qs.filter(content__icontains=query) return qs def get_object(self): request=self.request passed_id=request.GET.get('id',None) queryset=self.get_queryset() obj=None if passed_id is not None: obj=get_object_or_404(queryset,id=passed_id) self.check_object_permissions(request,obj) def get(self,request,*args,**kwargs): passed_id=request.GET.get('id',None) if passed_id is not None: return self.retrieve(request,*args,**kwargs) return super().get(request,*args,**kwargs) def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) def put(self,request,*args,**kwargs): return self.update(request,*args,**kwargs) def patch(self,request,*args,**kwargs): return self.update(request,*args,**kwargs) def delete(self,request,*args,**kwargs): return self.destroy(request,*args,**kwargs) guys i have tried to use the mixin serializer to serialize but when i tried to use delete in my browsable api i have strucked with an error AttributeError at /api/list/ 'NoneType' object has no attribute 'delete' creating and retriev is working but update ,delete isn't working i dont know what's the issue any kind of help is appreciated -
Django : count foreign key and display
Suppose I have two table in my database, booktable which have 3 attributes (id, book_name, writer_id(foreignkey)) writertable which have 2 attributes (id, writer_name) I want to display writer name and how many books have that writer by calculate booktable book table --------------------------------------- | id | book_name | writer_id | |-------------------------------------| | 1 | abc | 2 | | 2 | bcd | 1 | | 3 | efg | 1 | | 4 | htj | 2 | | 5 | klm | 1 | | 6 | nop | 3 | |-------------------------------------| Writer table ---------------------------- | id | writer_name | |--------------------------- | 1 | xyz | | 2 | bcb | | 3 | eld | | 4 | ccb | |--------------------------- so, id 1 = 3 books 2 = 3 books 4 = 0 books How can I display in html template. Here is my code, models.py class book(models.Model): book_name = models.CharField(max_length = 100) writer = models.ForeignKey(writer, on_delete = models.CASCADE) class writer(models.Model): writer_name = models.CharField(max_length = 100) def __str__(self): return self.writer_name view.py def getwriters(request): wrt = writer.objects.all() return render(request, "writers.html", {"wrt":wrt}) writers.html {% for p in wrt %} <tr> <td>{{ p.writer_name }}</td> <td>{{**Should display how many books have … -
Choicefield empty string and null
I have Django a model that has a different meaning between a null value and a blank value. When I create a choicefield with the following CHOICES: CHOICES = [ (None, 'Null'), ('', 'Blank'), ('foo', 'Foo'), ('bar', 'Bar') ] The admin form generates this: <select name='my_field'> <option value>Null</option> <option value>Blank</option> <option value='foo'>Foo</option> <option value='bar'>Bar</option> </select> So that when you submit the form with "blank" selected, the database saves the null value. Is there a way to make Django distinguish within the admin form blank from null? -
Login django User without request
I am implementing oauth. I successfully did everything and finally I need to login user using login function. But the problem here is I didn't have any request to provide to login function. So, I made a request by importing requests. But that is not working properly. Can anyone please specify how to make a request so that I can login user perfectly. Is there any way to login user without request ?? If not can anyone make a perfect request for login ?? This is my request to the login function s = requests.session() data = { 'username': user.username, 'password': user.password} s.post(url_path,data=data, verify=False) login(s, user) verify=false // to prevent SSL error but I am still receiving it and what about url_path ?? How actually to configure it?? -
Access current schema context
Let's say we have such situation: from django_tenants.utils import schema_context def do_something(context): print("do_something") def my_callable(): tenant = "db_tenant" with schema_context(tenant): context = {"a": 1, "b": 2} do_something(context) my_callable() And question is: It's possible to access current tenant name in do_something function without passing it as parameter or store it as global variable -
How to pickle a SqlAlchemy BinaryExpression object
I wanted to use pickle or dill to pickle an SqlAlchemy BinaryExpression object in order to retrieve it later to update my cache (dogpile.cache). With pickle, in every process i get a different error which have nothing in common. But with dill i get the error below. The ProjectElement object (or the Project object precised in the error) is a Django model. Is it possible to pickle this BinaryExpression object, i see that an object should have a __getstate__ and __setstate__ methods in order to be pickled and unpickled. How can i implement it to my use case or is there a better solution to this issue. Here is my code: binary = ProjectElement.project_id == 16 and ProjectElement.project_element_id== 399 with open('/home/mustafasencer/Documents/redis.txt', 'wb') as file: dill.dump(binary, file)` Error Traceback: sqlalchemy.exc.InvalidRequestError: Class <class 'cerebro_data.models.Project'> does not have a mapped column named '__getstate__' -
Block content for passing variables from python to HTML
I'm trying to send some data from my python code to the HTML script. This is my python code. I use lists to send the data. def extractMetaData(request): pdfDir = "C:/PythonPrograms/pdf/" if pdfDir == "": pdfDir = os.getcwd() + "\\" pdf_title = [] pdf_author = [] pdf_creationdate = [] pdf_creator = [] pdf_Keywords = [] pdf_producer = [] for pdf in os.listdir(pdfDir): fileExtension = pdf.split(".")[-1] if fileExtension == "pdf": pdfFilename = pdfDir + pdf pdf_toread = PdfFileReader(open(pdfFilename, "rb")) pdf_title.append(pdf_toread.getDocumentInfo().title) pdf_author.append(pdf_toread.getDocumentInfo().author) pdf_creationdate.append(pdf_toread.getDocumentInfo()['/CreationDate']) pdf_creator.append(pdf_toread.getDocumentInfo()['/Creator']) pdf_Keywords.append(pdf_toread.getDocumentInfo()['/Keywords']) pdf_producer.append(pdf_toread.getDocumentInfo().producer) return render(request,'personal/extract.html',{'content':[str(pdf_title),str(pdf_author),str(pdf_creationdate), str(pdf_creator),str(pdf_Keywords), str(pdf_producer)]}) In HTML I use the following code. {% block content %} {% for c in content%} <p>{{c}}</p> {% endfor%} {% endblock %} But this prints all the items of the first list and then all items of second list and so on.. I want it to print the first item of the first list, first item of the second list and so on. Then start with second item of every list.. how can do this in jinja? -
setting up django-admin project using cmd
C:\Users\Lenovo Thinkpad\Desktop\manage> django-admin startproject cruxlore 'django-admin' is not recognized as an internal or external command, operable program or batch file. Please how do I set up my Django environment for new projects, I have tried out different resources but have not gotten a positive result -
Allow Django Admin to change whether a field is required
I'd like to be able to change whether the email field is required or not, depending on whether I'm showing a friend or a customer, without having to push to git every time and redeploy. I have set up a Configuration model for other settings in Django which is configurable from the admin, but unfortunately I'm not able to use any of these settings in other Models or Model Fields, as it causes database errors on migration. This is my code (it fails because of the migration issue) class UserForm(forms.ModelForm): stake = StakeField() email = forms.EmailField(required=getConfig(ConfigData.USER_EMAIL_REQUIRED)) class Meta: model = User fields = '__all__' Is there another way to set the required/blank setting in either the model, modelform or form which won't cause this issue? -
How can I fix PostgreSQL canceling statement error on Google SQL?
We have PostgreSQL instances (1 master + 1 read replica) on Google SQL. Our Django (1.11.12) application uses these databases via PostGIS engine. When we try to use the database, we saw this error message: django.db.utils.OperationalError: canceling statement due to conflict with recovery DETAIL: User query might have needed to see row versions that must be removed. When I search for a solution, they generally say that I need to change hot_standby_feedback flag. But as you know Google SQL service has some restrictions about settings. I can't set the flag. How can I fix this? -
How to pass data toTaggableManager django
In my Django model have TaggableManager field, I want to store data in database, in which format I need to pass data to TaggableManager field. tags=TaggableManager(through=Tags) -
Clone all object permissions in django-guardian / inherit from ForeignKey
I have an app with model hierarchy in which I need underlying objects to have the same permissions as the parent object (not only their definitions/codenames, but also per-user and per-group rights). Django-guardian seems to have only functions allowing to check for specific user/group permissions. Is there any canonical approach to clone all the permissions from one object to another or force the inheritance? -
Android Java file upload to Django backend
I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend. The file I am trying to upload is a wav audio file which is stored on the phone. I am trying to mix to sets of code. The Android code I am using is this the following code taken from How to upload a WAV file using URLConnection. public class curlAudioToWatson extends AsyncTask<String, Void, String> { String asrJsonString=""; @Override protected String doInBackground(String... params) { String result = ""; try { Log.d("Msg","**** UPLOADING .WAV to ASR..."); URL obj = new URL(ASR_URL); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); //conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df"); conn.setRequestProperty("Content-Type", "audio/wav"); conn.setRequestProperty("enctype", "multipart/form-data"); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); String wavpath=mRcordFilePath; File wavfile = new File(wavpath); boolean success = true; if (wavfile.exists()) { Log.d("Msg","**** audio.wav DETECTED: "+wavfile); } else{ Log.d("Msg","**** audio.wav MISSING: " +wavfile); } String charset="UTF-8"; String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. OutputStream output=null; PrintWriter writer=null; try { output = conn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, charset), true); byte [] music=new byte[(int) wavfile.length()];//size & length of the file InputStream is = new FileInputStream (wavfile); BufferedInputStream bis = new BufferedInputStream (is, 16000); DataInputStream … -
How can I fetch Intercom users using Python API with a particular filter?
How to fetch users from Intercom Python API using the tag last seen less than 2 days ago or else creating the segment in UI for the same will it be possible to fetch all users in Segment which I have created with filter 'last seen less than 2 days ago'? -
invalid link in reset password django
I am new in Django and I wanna to write a custom user in it. I have a problem with the reset password. I use the URLs below for urls.py url(r'^reset_password_confirm/(?P<uidb64>[0-9A-Za-z_\-\']+)-(?P<token>[0-9A-Za-z\-\']+)/$', PasswordResetConfirmView.as_view() , name='reset_password_confirm'), url(r'^reset_password', ResetPasswordRequestView.as_view()) and this is my view for reset password and confirm it class ResetPasswordRequestView(FormView): # User = get_user_model() template_name = "test_template.html" #code for template is given below the view's code success_url = 'reset_password' form_class = PasswordResetRequestForm @staticmethod def validate_email_address(email): try: validate_email(email) return True except ValidationError: return False def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): data= form.cleaned_data["email_or_username"] if self.validate_email_address(data) is True: #uses the method written above ''' If the input is an valid email address, then the following code will lookup for users associated with that email address. If found then an email will be sent to the address, else an error message will be printed on the screen. ''' associated_users= User.objects.filter(Q(email=data)|Q(username=data)) if associated_users.exists(): for user in associated_users: c = { 'email': user.email, 'domain': request.META['HTTP_HOST'], 'site_name': 'your site', 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } subject_template_name='password_reset_subject.txt' # copied from django/contrib/admin/templates/registration/password_reset_subject.txt to templates directory email_template_name='password_reset_email.html' # copied from django/contrib/admin/templates/registration/password_reset_email.html to templates directory subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain … -
How to break Vertical line in a checkbox list
I have this Checkbox list and I want to break it into many lines using CSS or attrs in Django forms ..mainly it is a CheckboxSelectMultiple here is the code of forms.py: town = forms.ModelMultipleChoiceField(Town.objects.all(), widget=forms.CheckboxSelectMultiple( attrs={ 'style': 'vertical-align: middle;white-space: nowrap;display: block;float: left;padding-right: 10px;text-indent: -22px;' } ) ) and that is how it looks like now : everytime i add more choices it keep increasing int he same vertical line -
Djongo return empty QuerySet when exasing next page
This only happens when I made a model to have 2 inheritance from the same model: class Word(models.Model): cuvint = models.ForeignKey(KeyWordsMapping, on_delete=models.CASCADE, related_name="%(class)s_cuvint") frequency = models.IntegerField() is_stem = models.BooleanField() score_nr = models.ForeignKey(KeyWordsMapping, on_delete=models.CASCADE, related_name="%(class)s_score_nr") department_id = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True, null=True) seniority_id = models.ForeignKey(Seniority, on_delete=models.CASCADE, blank=True, null=True) Everything works fine, but accessing the second page gives me an empty array: First page: { "count": 311, "next": "http://127.0.0.1:8000/api/words?limit=1&offset=1", "previous": null, "results": [ { "cuvint": "QA", "frequency": 4, "is_stem": false, "score_nr": 100, "department_id": "Quality Assurance", "seniority_id": null } ] } Second page: { "count": 311, "next": "http://127.0.0.1:8000/api/words?limit=1&offset=2", "previous": "http://127.0.0.1:8000/api/words?limit=1", "results": [] } I also looked in the admin panel and the same problem persists. -
Flask sqlalchemy : Mysql connection
I have the following connection code : app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql:/uBrands:uBrands2018B@127.0.0.1/ubrands' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = 'some-secret-string' The log says : OperationalError: (_mysql_exceptions.OperationalError) (1045, "Access denied for user 'root'@'localhost' (using passwod: YES)") (Background on this error at: http://sqlalche.me/e/e3q8) I have checked the username password, Database name, Everything is fine, Also the log says Access denied for user 'root'@'localhost' but the username is not root its uBrands, Why it says root@loclhost Note: The uBrands user have full access means to all the databases What can be the problem ? -
django celery not working on elastic beanstalk
I'm trying to use celery and sqs along with django on aws eb, It's working as expected in my local however when I deploy to AWS Elastic Beanstalk It doesn't work, I'm sharing log messages and config files in below, can anyone help me about this issue? It has been a real pain to run celery on aws eb, I examined many code snippets and help posts, but still I couldn't figure it out. AWS Log File ------------------------------------- /opt/python/log/supervisord.log ------------------------------------- 2018-07-20 10:42:13,676 INFO spawned: 'celeryd' with pid 32280 2018-07-20 10:42:14,087 INFO exited: celeryd (exit status 2; not expected) 2018-07-20 10:42:15,090 INFO spawned: 'celeryd' with pid 32285 2018-07-20 10:42:15,493 INFO exited: celeryd (exit status 2; not expected) 2018-07-20 10:42:17,736 INFO spawned: 'celeryd' with pid 32321 2018-07-20 10:42:18,567 INFO exited: celeryd (exit status 2; not expected) 2018-07-20 10:42:20,975 INFO stopped: httpd (exit status 0) 2018-07-20 10:42:21,977 INFO spawned: 'celeryd' with pid 32375 2018-07-20 10:42:21,982 INFO spawned: 'httpd' with pid 32376 2018-07-20 10:42:22,475 INFO exited: celeryd (exit status 2; not expected) 2018-07-20 10:42:23,477 INFO gave up: celeryd entered FATAL state, too many start retries too quickly 2018-07-20 10:42:23,477 INFO success: httpd entered RUNNING state, process has stayed up for > than 1 seconds … -
Django form returning blank to next template
My form seems to never be returning the input from one template to the other and I am having a hard time understanding why. forms.py: class textForm(forms.Form): message = forms.CharField(widget=forms.Textarea) views.py: def article(Request): if Request.method == 'POST': form = textForm(Request.POST) if form.is_valid(): message = form.cleaned_data['message'] return render(Request, 'index/article.html', {'message': message}) else: form = textForm() return render(Request, 'index/article.html', {'form': form}) HTLM where the form is: <form action="/article" method="post"> {% csrf_token %} {{ form }} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" required /> <input type="submit" value="Submit" /> </form> HTML where I'd like to return the value from the form: <div class="card border border-dark" style = "padding-left: 0px;"> <div class="card-body" style="margin-top: -10px; margin-bottom: -10px; margin-left: -10px;"> <p class="card-title"><strong>Welcome:</strong> </p> <p class="card-text"> {{message}} </p> </div> </div> -
Custom UserChangeForm in Django
I'm trying to set a page for allowing users to change their first name and their last name. The problem is that I don't want to include the password in the form but if I don't include it, the user can't update the information. I have created my own form from UserChangeForm to include only first name, last name and password: class UserForm(UserChangeForm): password = auth_forms.ReadOnlyPasswordHashField(label="Password", help_text="Para cambiar la contraseña por favor pulsa " "<a href=\"change-password/\">en este link</a>.") class Meta: model = User fields = ( 'first_name', 'last_name', 'password' ) My HTML is a simple one: <form method="post" > {% csrf_token %} {{ user_form.as_p }} <button type="submit">Actualizar</button> </form> I thought about including in the HTML only the inputs with something like: > <div class="form-group"> > <input type="text" class="form-control" name="first_name" id="inputFirstName" placeholder="First_name"> > </div> but then it doesn't show the current value of the first name. What can I do? Many thanks -
how to fetch time with every message in angular?
I create one real-time chat application with websocket so, frontEnd is angular5 and backnd is django and i create websocket server in purepython. I just wanted to do is that i want to fetch time with every message send and receive. here is my chat service: export class ChatService { messages: Subject<ChatMessage>; constructor(private ws: WebsocketService) { this.messages = <Subject<ChatMessage>>this.ws .connect(chatUrl) .map((response: MessageEvent): ChatMessage => { const data = JSON.parse(response.data) as ChatMessage; return data; }); } send(name: string, message: string): void { this.messages.next(this.createMessage(name, message)); } private createMessage(name: string, message: string): ChatMessage { return new ChatMessage(name, message); } } chat component: export class ChatComponent implements OnInit, OnDestroy { Name : string; name : string; messages = []; constructor(private chat: ChatService , private router: ActivatedRoute) { } ngOnInit() { this.router.queryParams.forEach((params: Params) => { this.name = params['name']; }); this.chat.messages.subscribe(msg => { this.messages.push(new ChatModel( msg.name, msg.text)); }); this.Name = this.router.snapshot.params['name']; console.log(this.Name); } sendMessage(message: string){ this.chat.send(this.name, message); } ngOnDestroy() { } } class ChatModel { name: string; text: string; constructor(name: string, text: string) { this.name = name; this.text = text; } } chat.html: <div id="chatDisplay" style=" margin-top: 0px;"> <div *ngFor = "let msg of messages"> <b>{{msg.name}}</b>:{{msg.text}} </div> </div> <div id="chatInput"> <div class="col-sm-10" style=" margin-top: -30px;"> <input … -
“submit is not a funtion" in javascript with a django form
I wrote a Django form: class EditTaskForm(forms.Form): taskContent = forms.CharField(label="内容", widget=forms.Textarea(attrs={'id': 'code'})) And here's my JavaScript code in a html file: <script type="text/javascript"> button = document.getElementById("login"); button.onclick = function(){ var f = document.getElementById("code"); f.submit(); } </script> But something went wrong and the error says "f.submit is not a function". There's some solutions saying that maybe the method submit() is overrided, but I checked the whole html file, this is the only place the word "submit" is used. And now I've got no idea what's going on... -
how to associate a continent to a country using any django package?
I tried django-countries but it only uses countries and does not have continents, so how do I add the continents so that I can associate them with the countries something like how a foreign key works any help will be appreciated thank you.