Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fadeToggle corresponding div with regex in django
I am displaying small content(id=showmore_ and with the forloop counter) (30 words) of the comment initially. I want to hide it and show all the content of id more_content_ of same loop counter. HTML: <div class="comment"> Comments ({{discuss.get_comments|length}}): {% for comment in discuss.get_comments %} <div id="showmore_{{ forloop.counter }}"> {{ comment.commenter.get_full_name }} - {{ comment.body|truncatewords:30 }}... <em>Read More</em> </div> <div id="more_content_{{ forloop.counter }}" style="display: none;"> {{ comment.body }} </div> <div> {% for subcomment in comment.get_subcomments %} <div>{{ subcomment.body|truncatewords:30 }</div> {% endfor %} </div> {% endfor %} </div> jQuery: $(document).ready(function(){ $('div[id^="showmore_"]').click(function(){ $('div[id^="more_content_"]').fadeToggle(); }); }); When I give same id to all( eg. showmore or more_content), every element gets hidden or shown. What do I do? -
How to use OAuth token to connect to ejabberd in browser?
I want to develop a chat app in django using ejabberd. Following are the use-case :- Registration When user register with my app, I'll create a new user in ejabberd, using same username and password. Login For login, I am going to provide django-based login form. Based on the successful login, I'll log user into ejabberd from my app, so that ejabberd remain transparent to user. Here, I am planning to use OAuth based authentication to log user into ejabberd. Once OAuth token is obtained from ejabberd, I'll pass it to client(browser). Client will save the token. User will make connection directly will ejabberd, using that OAuth2 token received. From thereon, browser will directly communicate with ejabberd. Logout For logout, User will send request to my app. My app will logout user from ejabberd. I am able to perform steps 1 and 2 successfully. But I am facing issue in connecting to ejabberd from browser using OAuth token. I am not aware about how to do so in strophe.js. Is there any way to achieve this ? Is there any alternative library exists, which help in achieving this at client side ? Moreover, Any example or suggestion regarding improvement/problem in … -
Docker + Django + MySQL - End of list of non-natively partitioned tables
I am trying to use Docker with Django and MySQL database but unfortunately during docker-compose up at some point it stops on End of list of non-natively partitioned tables and my server is not starting. When I am using my app without Docker it works. Any suggestions what is wrong? My docker-compose.yml: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" links: - db db: image: mysql environment: - MYSQL_ALLOW_EMPTY_PASSWORD=yes - MYSQL_USER=root - MYSQL_DATABASE=pri Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ -
Best python framework for working with FB Api & Angular? [on hold]
I am quite new to web development and know only javascript. I am trying to connect my angular web page to the facebook python sdk. I do not know where to start. I tried looking at django and flask but I am also using nodejs as a backend and don't want to tie up my templates/views. What is the best way to connect my angular/node stack to the python sdk with minimal learning? Thank you. I really appreciate your help. -
Error loading bootstrap3 from windows 8.1 in django
I tried installing bootstrap using pip install bootstrap3 then i got the error that the satisfied version was not found, so I tried pip install django-bootstrap3 the bootstrap installed and is in the INSTALLED_APPS folder , but i still get an error trying to load it. Here is the error please any suggestions would be helpful -
Web faction hosting. how to implement a virtual env on a django application?
I want to use a virtual env but web faction is using apache like webserver, and i wanto know how to configure apache on webfaction. -
Split by certain pattern in python
Hi everyone i have a pattern (using django) [[u'13'], [u'12', u'23'], [u'30', u'31']] and i want to spilt this and want to append into a list like [13,12,23,30,31] I know this can be done using regular expression but unable to make regualr expression for that. Please help into this Thanks in advance. -
Save in databaseb and save image in django
I have a app to save image and add their name to db(sqlite).but when i put this code : def handle_uploaded_file(request,types): file_name = uuid.uuid4().hex.upper() path = 'mrdoorbeen/images/' + file_name + types f = open( path , 'wb+') for chunk in request.FILES['image'].chunks(): f.write(chunk) f.close() imagesave = Image(name =request.FILES['image'].name, link = file_name, owner =request.session['username']) imagesave.save() i have a error like this on cmd: path = 'mrdoorbeen/images/' + file_name + types ^ IndentationError: unindent does not match any outer indentation level but when i write in this way it will work : def handle_uploaded_file(request,types): path = 'mrdoorbeen/images/' + uuid.uuid4().hex.upper() + types f = open( path , 'wb+') for chunk in request.FILES['image'].chunks(): f.write(chunk) f.close() imagesave = Image(name =request.FILES['image'].name, link = path, owner =request.session['username']) imagesave.save() note : in types we have .jpg or .png i want to save in db just file name not full path .if you can help me .please help me! -
DRF api filtering room that has not reservation
i have this scenario. User will reserve room in date range(E.g from 2017-06-08 - to 2017-07-09) Also user can choose private room or shared room. The thing is shared room should be in date range so that user can choose shared room with someone. Now i am doing queryset function with this class Room(models.Model): number = models.CharField(max_length=8, null=True) category = models.ForeignKey(RoomCategory, related_name="rooms") beds = models.PositiveIntegerField(null=True) description = models.TextField(blank=True) size = models.CharField(max_length=2, blank=True) bed = models.PositiveIntegerField(null=True) toilet = models.BooleanField(default=False) guest_section = models.BooleanField(default=False) building_type = models.CharField(max_length=50, null=True) tv = models.BooleanField(default=False) wifi = models.BooleanField(default=False) shower = models.BooleanField(default=False) heat = models.BooleanField(default=False) fridge = models.BooleanField(default=False) microwave = models.BooleanField(default=False) wardrobe = models.BooleanField(default=False) sofa = models.BooleanField(default=False) towel = models.BooleanField(default=False) liquid_soap = models.BooleanField(default=False) socket = models.BooleanField(default=False) sun_side_window = models.BooleanField(default=False) block = models.BooleanField(default=False) def __unicode__(self): return self.number class Reservation(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) transport_type = models.CharField(max_length=8, blank=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) total_days = models.PositiveIntegerField(null=True, blank=True) arrival_date = models.DateField(null=True, blank=True) customer_count = models.PositiveIntegerField(null=True) user = models.ForeignKey(User, related_name="zahialagch") service = models.ForeignKey(Service, related_name="reservation_services", null=True, blank=True, editable=False) room = models.ForeignKey(Room, related_name="reservations") bus_seat_departure = models.ForeignKey(BusSeat, related_name="reservation_bus_seat_dep", null=True, blank=True) bus_seat_arrival = models.ForeignKey(BusSeat, related_name="reservations_bus_seat_arr", null=True, blank=True) total_payment = models.PositiveIntegerField(null=True, blank=True) total_paid = models.PositiveIntegerField(null=True, blank=True) reservation_group = models.ForeignKey(ReservationGroup, related_name="reservation_groups", null=True) # reservation_serial = models.CharField(max_length=10, default=zerofill, … -
some troubles with CreateView in the Dkango
class Biochemical_analysis_of_blood(CreateView): model = BiochemicalAnalysisOfBlood form_class = BiochemicalAnalysisOfBloodForm template_name = "biochemical_analysis_of_blood.html" success_url = reverse_lazy("patients") def get_context_data(self, **kwargs): context = super(Biochemical_analysis_of_blood, self).get_context_data(**kwargs) patient = Patient.objects.get(id=1) context["patient"] = patient return context def post(self, request, *args, **kwargs): analysis = Analyzes() sid = transaction.savepoint() analysis.name = request.POST["name"] analysis.patient_id = Patient.objects.get(id=1) analysis.who_send = request.POST["who_send"] analysis.who_is_doctor = request.POST["who_is_doctor"] analysis.lab_user_id = Doctor.objects.get(id=request.POST["lab_user_id"]) analysis.additional_lab_user = request.POST["lab_user_add"] analysis.date = '2017-06-18' analysis.type = 3 analysis.date_analysis = '2017-06-18' analysis.save() return super(Biochemical_analysis_of_blood, self).post(request, *args, **kwargs) I have next algorithm: render BiochemicalAnalysisOfBloodForm to the user when he fills fields and presses button "save" I create a new instance of Analyzes() and fill it programmatically and when in the post method I call super().post() then users data will be written to the model BiochemicalAnalysisOfBlood automatically? But I have next error "NOT NULL constraint failed: laboratory_biochemicalanalysisofblood.analysis_id". How can I in hand mode add to the model to the field "analysis" the early created instance of Analyzes()? I don't understand this class to the end where I can find information about all it's opportunities -
Overriding clean() method of Parent django form in child/inherited form
I am really having a hard time figuring this out. The bottom problem is that I need to somehow either set initial value for password field or override the way the method validate_member is called. I have this form, which is called when a member needs to register to the system directly: class NewMemberForm(forms.Form): ''' Called when user wants to register with our system from web/mobile. Ask password here ''' firstName=forms.CharField(max_length=25,required=True,widget=forms.TextInput()) lastName=forms.CharField(max_length=25,required=True,widget=forms.TextInput()) birthdate=forms.DateField(required=True) gender=forms.ChoiceField(choices=Profile.GENDER,required=True) idnumber=forms.CharField(required=False,max_length=25) phone=forms.IntegerField(required=True) email=forms.EmailField(required=True) password=forms.CharField(max_length=16,widget=forms.PasswordInput()) memberType=forms.ChoiceField(choices=Profile.TYPE_OF_MEMBER,widget=forms.Select()) maritalStatus=forms.ChoiceField(choices=Profile.MARITAL_STATUS,widget=forms.Select()) def clean(self): ''' Grouped cleaning ''' self.cleaned_data=super(NewMemberForm,self).clean() validate_member_form=validate_member(self.cleaned_data,False) #do we have error messages now? if len(validate_member_form[0])>0: #yes we have error messages raise forms.ValidationError(_(validate_member_form[0]),code='invalid') return validate_member_form[1] the validate_member function is used during editing and adding information, thus cleaned the clean() to keep things DRY. Now, I have another scenario in which a member could be registered by another member (with some rights). In that case, the password and membertype fields are not needed with one new field added to the form named role; so I decided to inherit the form: class MemberAddForm(NewMemberForm): #memberType=forms.CharField(initial='Individual',required=False,widget=forms.Select()) #iignored: here to simple override the Required declaraton in memberform #password=forms.CharField(max_length=16,widget=forms.PasswordInput(),required=False,initial='111111') #note pwd is ignored during saving and a new is generated role=forms.ModelChoiceField(widget=forms.Select(),required=True,queryset=Activity.objects.filter(active='Active').only('id','name'),empty_label=None) def __init__(self,*args,**kwargs): super(MemberAddForm,self).__init__(*args,**kwargs) self.fields['password'].initial='123456' #note … -
Can't get or filter object by some parameter(parametr As a string), how to fix?
We need to get the object from the database, by slug, "slug" we get from the ajax request, and it's like a string, but the get method and the filter method give an error, ostensibly there is no such record, although it exists, how to solve this problem? for this function using ajax request def mark_and_unmark_this_episode(request): return_dict = {} data = request.POST serial_slug = data.get('serial_slug') season_slug = data.get('season_slug') series_slug = data.get('series_slug') is_delete = data.get('is_delete') serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) print(serie) user = request.user watched_serial = seriess.serial_of_this_series watched_serie = seriess minutes_of_series = seriess full traceback with method GET (series = Series.objects.get(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)) self.model._meta.object_name serials.models.DoesNotExist: Series matching query does not exist. full traceback with method filter (series = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)) AttributeError: 'QuerySet' object has no attribute this part of views.py generic content on same page like error up, there this is work, i can get and filter by slug, Since these slugs are written in the parameters of the function, and everything works there, although in fact this slug is a string, but here everything works, here is this code! def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None): serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) #print(serie) title = … -
Connecting Two Users together (Django Rest) to 'grant' access to each other's User Model
In my Django Rest API, I have a large user serializer where I pull in all 'attached' models with a depth of 1. I have two users connect to each other like a 'friendship' (They can only have one connection). User A -> sends req to userB (In the Relationships model: user: userA_id, partner: userB_id is created). userB gets a notification on login pertaining to the request. UserB can choose to accept or deny. If they accept: (In the relationships model: user: userB_id, partner: userB_id is created). Then on the client-side, a check is done to see if the fields exist for each other on the relationship model. This isn't ideal, because a client could still always pull down info if they just made their own modified client... On the service side, how is it possible to only see data if the the two users match? (the User serializer has a lot of attached models with a depth of 1 so I can build the client page). Thank you. -
How to add pagination to Django Postman?
I'm using Django-Pagination module. Now I want to add pagination to Inbox. I've read the docs but I could not find any guide on how to do so. Here is my inbox.html {% extends "postman/base_folder.html" %} {% load i18n %} {% load postman_tags %} {% block pm_folder_title %}{% trans "Received Messages" %}{% endblock %} {% block pm_undelete_button %}{% endblock %} {% block pm_recipient_header %}{% endblock %} {% block pm_date %}{% trans "Received" %}{% endblock %} {% block pm_recipient_cell %}{% endblock %} -
binding virtualenv to project using setvirtualenvproject command doesn't work (windows)
I'm trying to bind my virtualenv to django project. So when I type the command workon my_project it should cd to my django project. (my_project) C:\User\User\Desktop\Project> (my_project) C:\User\User\Desktop\Project>setvirtualenvproject 'setvirtualenvproject' is not recognized as an internal or external command, operable program or batch file. Why the command doesn't work? Is there another way of binding virtualenv to my django project? -
How to test email sending after http request in Django
I just read this question. A lot of people suggested using the django.core.mail module for unit testing email sends like so: def test_send(self): mail.send_mail('subject', 'body.', 'from@example.com', ['to@example.com']) assert len(mail.outbox) == 1 But what if your test involves sending an http request with django.test.Client? Then you would not have access to that mail instance from the unit test. In this scenario, how could I test an http endpoint which automatically sends an email? -
override the FilteredSelectMultiple widget to filter on more arguments
I have been trying for days many ways without success. I m trying to filter on more fields a manytomany relationship field I have this form: from django.contrib.admin.widgets import FilteredSelectMultiple class ProjectAdminForm(forms.ModelForm): class Meta: model = Project userprofiles = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.all(), required=False, widget= FilteredSelectMultiple( verbose_name='User Profiles', is_stacked=False ) ) def __init__(self, *args, **kwargs): super(ProjectAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['userprofiles'].initial = \ self.instance.userprofile_set.all() #self.fields['userprofiles'].queryset = \ #UserProfile.objects.filter(principle_investigator=self.instance.principle_investigator) def save(self, commit=True): project = super(ProjectAdminForm, self).save(commit=False) if commit: project.save() if project.pk: project.userprofile_set =\ self.cleaned_data['userprofiles'] self.save_m2m() return project class ProjectAdmin(admin.ModelAdmin): form = ProjectAdminForm ... and my project is : class Project(models.Model): name = models.CharField(max_length=100, unique=True) application_identifier = models.CharField(max_length=100) type = models.IntegerField(choices=ProjectType) account = models.ForeignKey(Account) principle_investigator = models.ForeignKey(User) active = models.BooleanField() class ProjectAdmin(admin.ModelAdmin): form = ProjectAdminForm list_display = ('name', 'application_identifier', 'type', 'account', 'active') search_fields = ('name', 'application_identifier', 'account__name') list_filter = ('type', 'active') admin.site.register(Project, ProjectAdmin) I have tried many things like setting the queryset of userprofiles in the init using the a filter so that in the form, i can set the principle_investigator, the Projects gets filtered in my box, then start adding Projects, then change the principle_investigator again and add other projects an so on but that didnt work (commented below) Any solution please? -
Django add fields to form dynamically based on number of values in model choice field
Objective: From a Django Form, modelchoice field i am making the widget display multiple checkboxes. But for each checkbox I would like to display exactly one textbox and then submit. I need to know if the checkbox is not selected, it's id still and the possible textbox value. How do I acheive this, if it is Ajax. please elaborate. as I am fairly new to django and haven't worked much with ajax. -
Tamporarily saving and sanitizing image objects in Django
I'm creating a Django website where users post details of used items they want to sell/barter. When posting an item, the second-last step is to upload (upto 3) photos of the item on sale. The last step is to provide personal details (name, address, mobile). After this, the ad is finalized and goes into a "pending approval" queue. I don't want to save photos to the DB until an advert is finalized. Hence I'm thinking I'll temporarily save a reference to the UploadedFile object retrieved from the form like so: request.session["photo"] = form.cleaned_data.get('photo',None) So far so good, or is this problematic? Assuming everything is correct so far. Next, once ad is final, I'll save the images to my storage backend and pop photo from the request.session dictionary. But what if the user drops out before finalizing the ad? How would I handle cases where a request.session["photo"] entry was created, but the user never finished the ad? Where are UploadedFile objects saved? Basically, I need an efficient way to process 'orphaned' request.session image entries and related UploadedFile objects. -
jQuery not working after ajax call, even though I'm using the correct on() method
I'm using django-el-pagination, a django package that allows ajax pagination. I'm paginating a queryset of Comment (a list of comments). The queryset is inside comments.html, which is inside comments_base.html, which is inside article.html (the parent view). Here's my views: def article(request, category, id, extra_context=None): name = resolve(request.path).kwargs['category'] instance = get_object_or_404(Post, id=id, entered_category=name) new_comments_list = Comment.objects.filter(destination=id, parent_id=0).order_by('-timestamp') template = 'article.html' page_template = 'comments.html' if request.is_ajax(): template = page_template context = { 'id': id, 'comment_list': new_comments_list, 'page_template': page_template, 'instance': instance, } if extra_context is not None: context.update(extra_context) return render(request, template, context) comments_base.html {% block comments_base %} <div class="commentsContainer"> <div class="endless_page_template"> {% include 'comments.html' %} </div> {% block js %} <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="{% static 'js/el-pagination/js/el-pagination.js' %}"></script> <script> $.endlessPaginate({ }); </script> {% endblock %} </div> {% endblock %} comments.html {% block comments %} {% paginate 10 comment_list %} {% for i in comment_list %} {% if i.parent_comment %} <div class="comment_shell hasParent"> {% else %} <div> {% endif %} <div class='comment_div' data-comment_id="{{ i.id }}"> <div class="left_comment_div"> <div class="username_and_votes"> <h3><a class='username_foreign'>{{ i.user }}</a></h3> {% for j in i.score.all %} <span class="upvotes">{{ j.upvotes }}</span> <span class="downvotes">{{ j.downvotes }}</span> {% endfor %} </div> <br> <p>{{ i.comment_text }}</p> </div> </div> {% include 'comments.html' with comment_list=i.replies.all %} </div> {% … -
Django Socket Error 10053.
I created Django Web Server. It uses a request module. I use polonyex api to fetch the value and print it to my django server. This action is received as it is continuously refreshed for 5 seconds. There is no problem for an hour, but after about an hour, I get a Socket 10053 error. Do I need to increase the refresh time? I would appreciate it if you could tell me why this error occurred. -
React Native + WebRTC: Video Not Working
So some friends and I are trying to build a simple video chat app using https://github.com/oney/react-native-webrtc For some reason though, we cannot get a video-to-video connection from two iphones whatsoever. We established that we can get the two users in the same 'chat' room, but after that no luck. Anyone know the best way to connect two users? (We are using WebRTC with react native above). Here' some code that shows just audio, but not video for the answer: Got message {"candidate": {"candidate": "candidate:2148750707 1 udp 2122260223 192.168.0.131 64147 typ host generation 0 ufrag Db4M network-id 1 network-cost 10", "sdpMid": "audio", "sdpMLineIndex": 0}, "username": "john"} Thanks! -
Docker + Django + MySQL - End of list of non-natively partitioned tables
I am trying to use Docker with Django and MySQL database but unfortunately during docker-compose up at some point it stops on End of list of non-natively partitioned tables When I am using my app without Docker it works. Any suggestions what is wrong? -
Getting values correctly while using Many to Many relation
I have standart User model and Categories model like this; class Categories(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name And here is another class for relation which associates some users with some categories; class Interested(models.Model): user = models.ManyToManyField(User) category = models.ManyToManyField(Categories) For example if I have Users such as Bob, Eric, Oliver, Michael and categories such as Basketball, Football and relations like that Bob -> Basketball,Football Eric-> Basketball Oliver -> Football (michael not interested in anything) I want to get list of who interested in what? How can I handle this? Thank you for your help. -
Where does Django controller logic live?
I'm having trouble working out where to put controller logic in my Django project. I have models for players (think like chess players) who will be rated by ELO scores. After a round, two players have their ELO scores modified and updated. The next matches are chosen based on the players who have so far participated in the least number of contests. class Player(models.Model): tournament_class = models.ForeignKey(Topic, on_delete=models.CASCADE) # each player is part of a single tournament class name = models.CharField(max_length=200) contests = models.IntegerField(default=0) last_contest = models.IntegerField(default=0) # round number of last contest participated in ELO = models.FloatField(default=1000) # current ELO ranking Where would I put control logic like the following functions? def select_candidates() # return candidates who have participated in the least number of contests def update_ELO_scores (winner,loser) # updates ELO scores based on match results From what I have read, I think these functions I want to write should not live in the models, as these functions do not relate to single object instances. They might belong in a custom manager, as they do work on QuerySets, or do they belong in a QuerySet manager or a seperate package (python file)?