Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_suit : how to create two-level menu?
Django 2.2, django-suit==0.2.26 This is more django_suit question rather then django. I have a flat menu defined in my settings.py, each item is a link in admin view: SUIT_CONFIG = { 'ADMIN_NAME': 'MyAdminName', 'MENU': ( 'sites', '-', { 'label': 'MenuItem1', 'url': SCRIPT_NAME + '/some_view1', }, { 'label': 'MenuItem2', 'url': SCRIPT_NAME + '/some_view2', }, { 'label': 'MenuItem3', 'url': SCRIPT_NAME + '/some_view3', } } } I would like to make it work as two level menu that opens on mouseover. It can be easily done for the application's models like this: SUIT_CONFIG = { 'ADMIN_NAME': 'MyAdminName', 'MENU': ( 'sites', '-', {'app': 'MyApp', 'label': 'MenuLabelTopLevel', 'models': ('MyModel1', 'MyModel2', 'MyModel3') } } } When I position the mouse over MenuLabelTopLevel, I get a dropdown with 'MyModel1', 'MyModel2', 'MyModel3'. I am looking for the syntax that would allow me to have the same functionality for any arbitrary list of views in my application, something line this: SUIT_CONFIG = { 'ADMIN_NAME': 'MyAdminName', 'MENU': ( 'sites', '-', {'app': 'MyApp', 'label': 'MenuLabelTopLevel', 'link_list': (SCRIPT_NAME + '/some_view1',SCRIPT_NAME + '/some_view2', SCRIPT_NAME + '/some_view3') } } } Does this functionality exist in django_suit? If not, some other package (that allows me to do it in my existing admin menu, not to … -
How to use external database in django?
I am new to django, I have pretty good idea of basics. I am able to build model(Django database) and use it in templates. But now I want to connect external database to the django templates. How do I do that? I referred to the following link - Pulling data to the template from an external database with django But I am still running into errors. My views.py file looks like this : def view(request): conn = sqlite3.connect("data_new.db") try: cur = conn.cursor() cur.execute("delete from data_new where date = ''; ") cur.execute("select * from data_new;") results = cur.fetchall() finally: conn.close() return render("main.html",{"results": results}) Following error is displayed when I run it on server : - TypeError at / join() argument must be str or bytes, not 'dict' -
replace string except inside <a> tags
example i have string i need to replace 'game' word except in <a> tag "<p class='glossary_hover'> cricket is good game <li> hello game </li> <a href='https://game.in'> game of thrones </a> need to replcae game word </p>" result is "<p class='glossary_hover'> cricket is good game2 <li> hello game2 </li> <a href='https://game.in'> game of thrones </a> need to replace game2 word </p>" where i replaced game to game2 word -
How to convert 'CSV messy data' into 'JSON structured data' Using Django DRF
I write a django api without model. I use Serializer. In views this api takes a csv and when i call the get api it gives me a data that i don't want. I want more structured. But i can't figure which function do i need to use to show formatted json. view.py class bonolothaView(views.APIView): def get(self, request): # Load CSV Data data = pd.read_csv("Data/ShapeUpData.csv", index_col=0) # Load Specific Column in Dataframe df = pd.DataFrame(data, columns = [ 'Challan Date' , 'Region', 'Net Sales', 'Qty']) df.columns = df.columns.str.strip().str.replace(' ', '') yourdata= [{"challandate": df["ChallanDate"], "region":df["Region"] , "qty": df["Qty"], "netsales": df["NetSales"]}] print(yourdata) results = bonolothaSerializer(yourdata, many=True).data return Response(results) serializers.py from rest_framework import serializers class bonolothaSerializer(serializers.Serializer): challandate = serializers.CharField() region = serializers.CharField() qty = serializers.CharField() netsales = serializers.CharField() data.csv heading are: Challan Date, Region, Qty, Net Sales when i call the postman it gives me output like that: [ { "Challan Date":"07\/03\/2017", "Region":"Dhaka North", "Qty":1, "Net Sales":7748 }, { "Challan Date":"07\/03\/2017", "Region":"Dhaka North", "Qty":1, "Net Sales":7748 } ] i expect that type of JSON file from my csv. But the actual output is like that [ { "challandate": "Challan Date\n07/03/2017 NaN\n07/03/2017 NaN\n07/04/2017 NaN\n07/04/2017 NaN\n07/05/2017 NaN\n07/05/2017 NaN\n07/06/2017 NaN\n07/06/2017 NaN\n07/06/2017 NaN\n07/06/2017 NaN\nName: ChallanDate, Length: 990, … -
convert a word in editor
In django, I want to create an editor that can modify the word file. If I have a word file on my computer, I would like to upload it to the editor and distribute the contents of the word file to the editor. I'd like to revise the scattered content, but I don't know how. Please give me a sample or information. Reference https://wordtohtml.net/ -
Django told me connection already closed
Hello I am using Django and I am trying to do a request : myobject = Myobject.objects.get(myid=myid)[0] mycolor = myobject.color But Django told me that : psycopg2.InterfaceError: connection already closed I don't understand why I cannot get mycolor... Do you have any ideas to solve this ? Thank you very much. -
Thread-safe monkey patching
In our Django app we have large blocks of code where we want an exception to be raised if the value fetched from the database is None. We could of course write a custom accessor for this behaviour, but in order to keep those blocks of code simple we monkey-patched Model: def raise_error_on_none_model_values(func): @wraps(func) def wrapped(*args, **kwargs): # execute function if already patched already_patched = ( Model.__getattribute__ == _getattribute_raising_if_value_is_none ) if already_patched: return func(*args, **kwargs) # patch Model.__getattribute__ = _getattribute_raising_if_value_is_none # execute function try: return func(**kwargs) finally: del Model.__getattribute__ return wrapped However, we are (of course!) running into issues when threading is being used. I have investigated whether libraries like wrapt or gevent could help, but I'm not sure if they do. Is it possible to do a thread-safe monkey patch? Is there a better way to achieve what we want to do? -
Login \ Registration redirection
I created login\registration form for user. My problem is that when I login I get an error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/profile/ If login is successful it should redirect me to "home.html". If I login I came to an error above and if I hit "Back" button in browser I am redirected on my "Home.html" and I am successfully logged in. My other problem is that when I loggout I am redirected to DJANGO default logout page instead of mine "logged_out.html". Views.py @login_required def home(request): return render(request, 'home.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) Urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^login/$', auth_views.LoginView.as_view(), {'template_name': 'login.html'}, name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), {'next_page': 'login'}, name='logout'), url(r'^signup/$', views.signup, name='signup'), ] login.html {% extends 'base.html' %} {% block content %} <h2>Log in to My Site</h2> {% if form.errors %} <p style="color: red">Your username and password didn't match. Please try again.</p> {% endif %} <form method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> {% for field in form … -
How to remove products from cart in Django?
I am writing code for removing product from cart but i am facing a few problems.First is when i click on remove the product is not deleted from cart and the second is that, in my urls.py, i have added regex on id for removing product from cart.But when i click on remove, the id isn't displayed in the url. Views.py def remove_from_cart(request,id): try: the_id=request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: return HttpResponseRedirect(reverse("cart")) cartitem=CartItem.objects.get(id=id) cartitem.cart=None cartitem.save() return HttpResponseRedirect(reverse("cart")) models.py class CartItem(models.Model): cart=models.ForeignKey('Cart',on_delete=models.SET_NULL,null=True,blank=True) product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True,blank=True) accessory = models.ForeignKey(Accessories,on_delete=models.SET_NULL,null=True,blank=True) quantity=models.IntegerField(default=1) updated = models.DateTimeField(auto_now_add=True,auto_now=False) line_total=models.DecimalField(default=10.99,max_digits=1000,decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) def __unicode__(self): try: return str(self.cart.id) except: return self.product.title urls.py url(r'^cart/(?P<id>\d+)/$', remove_from_cart, name='remove_from_cart'), template.html <td><a href="{% url 'remove_from_cart' item.id %}">Remove</a></td> Please if any one can help it would be really appreciated? Note: I have searched different links on stackoverflow but none helped. -
Nginx Upload Model for Django REST framework
I want to upload large files (1-50GB) to my django server using the nginx upload module. For this I have the model Measurement which contains the filefield data: class Measurement(models.Model): ... data = models.FileField(null=True, upload_to=mediafolder) I can upload the file to my MEDIA=/vol/web/media/ folder and attach it to the filefield data by POST using the viewset action @action(methods=['POST'], detail=True, url_path='upload-data') def upload_data(self, request, pk=None): measurement = self.get_object() serializer = self.get_serializer( measurement, data=request.data ) if serializer.is_valid(): serializer.save() return Response(...) So if I go to the detailed view of the Measurement with #id=1,2,3, respectively, I can upload a file at http://localhost:8000/api/record/measurements/#id/upload-data/ I now want the upload to work with the nginx upload module I got here. After a bunch of 400-errors, I managed to get the "nginx" docker-container running with the django container "app" #/etc/nginx/conf.d/default.conf upstream my-project {server app:8000;} server { listen 80; client_max_body_size 80000M; client_body_buffer_size 80000M; client_body_timeout 120; server_name localhost; location / { proxy_pass http://my-project; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } location /static/ {alias /vol/web/static/;} location /media/ {alias /vol/web/media/;} location /upload-data { upload_pass @test; upload_store /vol/web/media/_upload 1; upload_store_access user:r; upload_set_form_field $upload_field_name.name "$upload_file_name"; upload_set_form_field $upload_field_name.content_type "$upload_content_type"; upload_set_form_field $upload_field_name.path "$upload_tmp_path"; upload_aggregate_form_field "$upload_field_name.md5" "$upload_file_md5"; upload_aggregate_form_field "$upload_field_name.size" "$upload_file_size"; upload_pass_form_field "^submit$|^description$"; upload_cleanup 400 … -
Why can't I add data to models in Django database?
I can't data to any of the schemas on my database. It gives error HTTP 400 when I click on save. Applicable to all schemas and models. Images attached. [Add data window] (https://i.imgur.com/aubPOhi.png) [Error Window] (https://i.imgur.com/RvfqJKp.png) I expect it to add the data to the model but it says that the page isn't working and returns error 400. -
What is def get_queryset, def get_object, def filter_queryset, def get_serializer_class?
I couldn't understand from the django rest documentation, Can anyone explain me what is def get_queryset, def get_object, def filter_queryset, def get_serializer_class? Why we use them? And how we use them? -
How to send mails from email address not from gateway email id because my mail always send from gateway email id in django?
Sending email using from email address not using gateway email id in Django. -
TypeError: issubclass() arg 1 must be a class in Django tests
I am using Django 2.1.5 and pycharm. When running tests from Pycharm I started getting this error: File "/Users/..../lib/python3.6/site-packages/nose/loader.py", line 576, in _makeTest if issubclass(parent, unittest.TestCase): TypeError: issubclass() arg 1 must be a class I'm getting it only when trying to run one test (and not a test class). Also getting it when trying to run it through python manage.py test specific_test I understand the error meaning, but I don't understand why I started getting it suddenly. -
Get ForeignKey object fields in the template files
I have a select list which shows ForeignKey in the template Django. When user select a object in the field related values should appear. For example I have a contact list here and for this I am using generic views class SendContactView(CreateView): model = SendContact template_name = 'contact.html' fields = ['customer'] def get_context_data(self, **kwargs): context = super(SendContactView, self).get_context_data(**kwargs) context['form'].fields['customer'].queryset = Contact.objects.filter(author=self.request.user) return context in the template everything is fine <label class="mt-1">Contact*</label> <select class="browser-default custom-select" ng-value={{ form.customer }} and this shows ForeignKey as customer Contact. The problem is if I select any of them (in the select list customers name is visible only) how can I get their email, phone number and other stuff in the other form field? any help world be appreciated! Thank you! for more information I upload a photo here link here if I select an item name cola in the other field its features will be filled. How can I solve this issue with my project? -
If Else in Djnago Views
I'm making a LMS. Where a user applies for leave and the admin accepts or rejects it. Right now I am stuck in a problem where I want the user to apply for a leave through the Django form by selecting a leave type (casual, sick etc), if the admin accepts it then the default values in the database changes or gets deducted and when the counter reaches 0 an error is generated that you don't have any leaves,contact admin. I'm unable to understand how to make the logic for it. I tried Applying if else statement in the views and even in the models. views.py The function name is Reject as I am trying to make changes to the accept function. def reject_leave(request, id): # reject email # employee_item = Employee.objects.get(id=id) all_item = Leave.objects.get(id=id) all = Employee.objects.get(id=id) context = {'all': all,'all_item': all_item} if leave_type.id is "Annual_leave": Annual_leave - 1 else: subject = "Leave Rejected" # email subject email_from = "settings.EMAIL_HOST_USER" # email from to_email = ['talhamurtaza@clickmail.info'] # email to with open( "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.txt", 'rb') as f: msgbody = f.read() msg = EmailMultiAlternatives( subject=subject, body=msgbody, from_email=email_from, to=to_email) html_template = get_template( "C:/Users/Bitswits 3/Desktop/Intern Work/LMS/LMS/projectfiles/templates/projectfiles/email/reject_email.html").render() msg.attach_alternative(html_template, "text/html") msg.send() return render(request, 'projectfiles/rejectemail.html',context) … -
How to perform more than one operation in django function view
I'm trying to perform 2 operation with in a single function view. But it perform only first operation. Which operation i mentioned first only that operation is executed second operation is not executed. Any other way to solve this problem. def home_view(request): if 'username' in request.session: if 'username' in request.session: username = request.session['username'] business_objs = AddBusiness.objects.all().values() myoffers_objs = Offers.objects.all().values() ads_objs = Ads.objects.all().values() myrating_objs = Rating.objects.all().values() return render(request, 'home/index.html', {'business_objs': business_objs}) elif request.method == 'GET': username = request.session['username'] form = ProfileForm(request.POST) if form.is_valid(): profile_info = Profile.objects.filter(username=username).values() print(profile_info) for i in profile_info: profiledict = i return render(request, 'home/index.html', {'profile_first_name': profiledict['first_name'], 'profile_last_name': profiledict["last_name"], 'profile_phone_number': profiledict['phone_number'], 'profile_email': profiledict['email'], 'profile_address': profiledict['address'], 'profile_image': profiledict['image']}) return redirect('/home/') return redirect('/home/') else: return redirect('/login/') -
Accessing a users google drive
I have a django site that uses Django allauth for users to log in using their google account and grant permission to their google drive. Once logged in, django-allauth saves a token for that user. This part all works correctly. How do I now access the user's google drive (who has granted permission), to list the available files? Presumably using the token that was saved thanks to django-allauth. I have installed the python google api client but am struggling to figure out how to use the user's token to list the content of their google drive. There is an example here which im trying to modify without success for my needs. -
How do I create 2 input fields for age range in Django?
I'm relatively new to Django and Python I would like to be able to implement 2 input fields for a patient's age range in Django. For example i would like to look for a patient within the age range of 10 to 20 and what shows on the page would be ' age range: 10 to 20 ' where '10' and '20' are fields that I can input numbers into. My desired output would be the full data of patients whose age are within that 10 to 20 range that was specified. How do I go about doing this in Django with models.py, views.py and django-filter's filterset? -
Getting a true iterable from taggit in views.py
I'm writing a custom view with taggit - I want to prepopulate an object edit formfield with the tags currently assigned to that object. I'd like the format to be arranged,in,this,kind,of,format. Instead what I'm getting is ['this','format'], and even when using the code below, I'm getting the list format with the single quote marks included # Create an empty string, iterate through tags and add each one joined with ',' tags_on_set = '' for each_tag in set.tags.names(): tags_on_set + ',' + each_tag print(each_tag) print(tags_on_set) # prepopulate field with the results of above: if set.tags: set_edit.fields['tags'].widget.attrs['value'] = tags_on_set The above results in this being printed: ['are', 'new', 'tags', 'the', 'these']. I can delete those values in the formfield, add this: 'here,are,some,new,tags' and I get back the same results, a list string, even though I'm trying to print each tag out individually. Basically, in the code above, 'each_tag' == ['are', 'new', 'tags', 'the', 'these'] Am I implementing incorrectly? **forms.py class SetEdit(forms.ModelForm): class Meta(): model = Set fields = ('title','tags',) widgets = { "title":forms.TextInput(attrs={'class':'borderless textinputclass editable', 'placeholder':''}), "tags":taggit.TagWidget(attrs={'class':'textinputclass editable', 'placeholder':'',}), } labels = { "title":None, "tags":None, } implementation of tag saving on views.py (I tried set.tags.add() and got the same results, only I … -
ImportError: No module named Mail python sendgrid
User.views.py this is the folder of Mail/views.py im having error when i started the local development server <pre> from Mail.views import sendgrid_mail content['url'] = input_values["host"] + "/EmailVerification/" + user.email + '/' + md5_key message = render_to_string('accountverification.html', content) # sendMail.delay("[GavaGives] Account created successfully", message, content['email']) sendgrid_mail('info', user.email, '[GavaGives] Account created successfully', message, 'user_offline_donation') return response("create", "success", []) </pre> Mail.views.py <pre> def sendgrid_mail(from_email, to_email, subject, content, template): sg = sendgrid.SendGridClient(config('SENDGRID_API_KEY')) mail = sendgrid.Mail() mail.add_to(to_email) mail.set_from(mail_from(from_email)) mail.set_subject(subject) mail.set_html(content) mail.add_filter('templates', 'enable', '1') mail.add_filter('templates', 'template_id', get_templates(template)) sg.send(mail) </pre> Settings.py this is the folder of the main project/settings.py im having error when i started the local development server INSTALLED_APPS = [ 'django.contrib.sessions', 'corsheaders', # CORS installation 'django_cron', # celery 'django_crontab', # Cron jobs 'celery', 'djcelery', 'Users', 'Campaign', 'Donor', 'Media', 'Admin', 'Common', 'CommonModules', 'Event', 'Cards', 'Mail' ] <pre> -
django.contrib.message Translation
Need to translate the django contrib messages into diffrent languages. Here is the code i tried: In Views.py from django.utils.translation import gettext as _ messages.success(self.request, _("Sample text")) In template: {% for message in messages %} <div class="alert alert-{{ message.tags }}"> <a class="close" data-dismiss="alert">×</a> {{ message }} </div> {% endfor %} But the text is not getting translated. Is there any particular way to translate this? I am using python3 and django 1.11 -
How convert epoch time integerfield to datetime field in django admin
I use django and for saving time I am using epoch time in an IntegerField so my model is like this: class MyModel(models.Model): start_time = models.IntegerField() and start_time in admin is like this: It's not a problem but it's hard to check and update field for a person so my question is how can I convert this IntegerField to DateTimeField in django admin without changing my model? I know I can represent this field as readonly field and convert epoch time to DateTime but how can i use django admin DateTime picker? -
Create a basic contact form that send a mail
I have a template for a form already designed (using bootstrap-studio). I just need to get the data from it and send it as a mail to my email id. It would also be great if the page could get redirected to a new one after pressing submit. I have already set up the settings.py and am able to send the 'message' part of the form. if request.method == 'POST': message = request.POST['message'] send_mail( 'Contact Form', message, settings.EMAIL_HOST_USER, ['abcd@gmail.com'], fail_silently=False ) return render(request, 'contact.html') What I need is to be able to send an email with 'message', 'name', 'email', included in it. I tried writing message = request.POST['message','name','email'] Didn't get expected results. -
adding bed raw html form to room raw html as a pop up to add a lot of beds
I have a raw html which i get the room details in which i need to add in a button pop up for a raw html form that can show up ○ You should be able to add multiple beds for a Room § Each Bed entity will have following fields: □ Width □ Length □ Quantity □ Mattress Type ® None ® Innerspring ® Pillow top ® Hybrid ® Specialty foam ® Gel ® Memory foam ® Latex ® Matress airbed Matress waterbed with each click on the +add beds it should show up the html form to add in details and then save all this while saving the Room form. didnt find a better way to approach NA it must be a raw html with some js or jquery to pop up a html form on click fill in the details and when clicked on add bed it should open another html form and need to add in details and same must show in edit view too.must be able to remove the beds html form if not needed and in the end must save with the room html form.