Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify url path generated by serializers.HyperlinkedIdentityField
Is there an easy way to modify the hyperlink generated by serializers.HyperlinkedIdentityField? Specifically, I want to append /download to the url path. > class AbcSerializer(serializers.HyperlinkedModelSerializer): > url = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail") > url_download = serializers.HyperlinkedIdentityField(view_name="api:v1:abc-detail") #append /download to this url > > class Meta: > model = abc > fields = ('url', 'url_download') -
Creating a base response for API calls
I want to create an API by using django-rest-framework. So far I've managed to setup one endpoint of API and managed to fetch all items. A basic response (without the BaseResponse class described later) would look like this: [ { "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83", "created_at": "2018-03-12T19:25:07.073620Z", "updated_at": "2018-03-12T19:25:37.904350Z", "deleted_at": null, "random_name": "random name" } ] The result I would like to achieve would be something like this: [ "success": true "message": "Some exception message", "data" :{ "uuid": "1db6a08d-ec63-4beb-8b41-9b042c53ab83", "created_at": "2018-03-12T19:25:07.073620Z", "updated_at": "2018-03-12T19:25:37.904350Z", "deleted_at": null, "random_name": "random name" } ] I managed to achieve this by creating a BaseReponse class and in view I simply return BaseResponse.to_dict() (a method that I have created inside of class). class BaseResponse(object): data = None success = False message = None def __init__(self, data, exception): self.data = data self.message = str(exception) if exception is not None else None self.success = exception is None def to_dict(self): return { 'success': self.success, 'message': self.message, 'data': self.data, } View: class RandomModelList(APIView): def get(self, request, format=None): exception = None models = None try: models = RandomModel.objects.all() except Exception as e: exception = e serializer = RandomModelSerializer(models, many=True) base_response = BaseResponse(data=serializer.data, exception=exception) return Response(base_response.to_dict()) I want to mention that with the current code … -
Django SECRET_KEY called in os.environ but isn't an environment variable
I've been asked to look at a Django project where the developer has disappeared. I cannot work out how they've set the SECRET_KEY. In settings.py we have SECRET_KEY = os.environ['SECRET_KEY'] It is running on a Ubuntu 14.04.05 server. I understand the code above to mean the SECRET_KEY has been set as an environment setting so in terminal I type printenv to see the environment settings and SECRET_KEY isn't there. How might it be being set? -
server couldn't stop sending emails after cron job and django q were started
I am coming here in real desparation. I am receiving 100+ emails from my test server. We have a feature that will notify members somethings once in a week. It is a django app and we are using django_q with reddis. To start, I decided to send hardcoded emails from a sample function. Set up scheduled tasks for django_q in admin area Started qcluster with python manage.py (probably made a mistake as it was started with a cron job that meets the time of schedules above) Now i do get the emails as intended and it started at the scheduled time. But now, I cant stop it. Deleted the schedule; deleted the cron job; stopped reddis (which is the worker for qcluster of django_q) and finally, the function that contains hardcoded emails. I have restarted server itself but still I am getting emails. My fear is it might behave the same with the real application. I am in ubuntu, running ngix, djang_q 0.8 and django 1.11 -
Django REST Framework : ListCreateAPI and RetrieveUpdateDelete Api for complex foreign key relationships
Apologies if this seems trivial but i want to know what is the most Django way to do this. Below are the models, views and serializers listed for reference. There are 3 models. I am just showing the relevant fields for each, though they have multiple fields. Now, one blog can have multiple authors contribute to it. Similarly one author or contributor can contribute to multiple blogs. class Blog(models.Model): title = models.CharField(max_length="120") ... class Author(models.Model): title = models.CharField(max_length="120") ... class BlogAuthor(models.Model): blog = models.ForeignKey('Blog') author = models.ForeignKey('Author') creator = models.ForeignKey('auth.User') # Should the above relations be a Foreign Key or ManyToMany Field I am using DRF 3.0 to create the below APIs: GET /blogs/1/author : to get a list of authors for the blog identified by id 1 POST /blogs/1/author: create which authors are related to the blog 1 GET /blogs/1/author/1: show details of the author 1 in context of the blog 1; for ex, author 1 may have contributed 300 words to blog 1 so this would return that along with some other details, say name of the author, picture of the author etc DELETE /blogs/1/author/1 : deletes the relation between blog 1 and author 1, thought both entities … -
How to install downloaded django project in virtualenv
I am trying to follow the instructions from this Django/Ajax tutorial: https://realpython.com/blog/python/django-and-ajax-form-submissions/. They say: Download the compressed pre-ajax Django Project from the repo https://github.com/realpython/django-form-fun/tree/master/part1 Activate a virtualenv Install the requirements Sync the database Fire up the server Here is what I am doing: Create new virtualenv using virtualenv -p /usr/bin/python3 ajaxenv inside home/ajaxtutorial/ folder Download the repo and unpack its django-form-fun/part1/pre-ajax/talk_project/ folder in the home/ajaxtutorial folder. Put the requirements.txt provided with the downloaded repo in ajaxenv/bin Run pip install -r requirements.txt inside ajaxenv. At this point I can see that Django gets installed, but I don't think anything else does. At this point the tutorial says to "sync the database". The only way I know how to do this is to use python manage.py migrate, but this throws an error. I guess this method requires starting the project or an app first, which is not a case here, since both the app and the project are downloaded, not created by me. I don't know how to proceed from here. python manage.py migrate throws the following error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/bart/ajaxtutorial/ajaxenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/home/bart/ajaxtutorial/ajaxenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 392, in … -
Matplotlib not working with Python 2.7 and Django on OSX
I am trying to use matplotlib and mpld3 to produce some html plots on my Django report app. Basically I have a controller for the plot that is the following: from django.shortcuts import render import mpld3 from matplotlib.pyplot import figure, title, bar def cpfLogin(request): mpl_figure = figure(1) xvalues = (1,2,3,4,5) yvalues = (1,2,3,4,5) width = 0.5 # the width of the bars title(u'Custom Bar Chart') bar(xvalues, yvalues, width) fig_html = mpld3.fig_to_html(mpl_figure) context = { 'figure': fig_html, } return render(request, 'reports/CPFReport.html', context) The code for reports/CPFReport.html is: {% load i18n %} {% block extrahead %} <style type="text/css"> .chart_title { font-weight: bold; font-size: 14px; } </style> {% endblock %} {% block content %} <div id="content-main"> <div class="chart_title"> {% trans "Custom Bar Chart" %} </div> {{ figure|safe }} </div> {% endblock %} The code is executed right and the plot is displayed correctly but after a couple of seconds the app terminates with the following error: Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1561.20.106/AppKit.subproj/NSView.m, line 14480. I found out that if I comment all the code this exception is thrown when any of the matplotlib libraries are called. Does anyone has a workaround or solution for this problem? -
How to test form submission of image in django
I have a file django view that takes a form request with an image as the submitted content and then returns an httpresponse of the image to be displayed back in the template. I'm new to testing in django and I'm trying to essentially assert that the file that was originally uploaded in the form request is the same one that is being returned back to the user. Here is the code in the view that handles the http request and returns the response: form = PhotoUploaderForm(request.POST or None, request.FILES or None) if request.method == "POST": print request.POST if form.is_valid(): print request instance = form.save(commit=False) instance.save() instance = PhotoUploader.objects.get(id=instance.id) image_full_path = instance.image.path image_data = open(image_full_path, "rb").read() return HttpResponse(image_data, content_type="image/png") I'm following the guide in the django docs for simulating a client request but I'm not clear on how to match up the submitted request with the http response. For the test, I have the code to make the request right now (where I have a test image stored in the static_cdn): with open('../../static_cdn/Keep-Calm-and-Carry-On.jpg', "rb") as fp: form_request = c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp}) form_request = form.save(commit=False) form_request.save() instance = PhotoUploader.objects.get(id=form_request.id) image_full_path = instance.image.path image_data = open(image_full_path, "rb").read() #assert HttpResponse = … -
Django filter from another model
In models.py I have following models: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') town = models.CharField(max_length=100) project = models.ManyToManyField(Project) def __str__(self): return str('Advanced user informations') class News(models.Model): title = models.CharField(max_length=255, blank=False) content = HTMLField() author = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) In my views.py I have: def news(request): news_list = News.objects.all().order_by('-id') paginator = Paginator(news_list, 5) page = request.GET.get('page') news = paginator.get_page(page) return render(request, 'news.html', {'news': news}) Now I want to achieve that a User can only see news for a project he participates. Something like: News.objects.filter(News with a project that the User is linked to) But I am not sure what could be a valid way to solve this. Maybe someone has a tip? -
how to check if a model is in a models foriegn key set? Django, django rest framework
I have a room model which has a many to one relation with a venue. A venue can have many rooms. I am trying to set up my http methods in my rest framework so that way when I add permissions things work well. So if say someone wants to delete a room from a venue, I must make sure that 1 that person has permissions to that venue 2 that room is attached to that venue I would like to get a venue model then get the venue models room_set and check the room_set to see if a room exists with the room primarykey of the model I wish to delete. What I have so far: class GetEditDeleteVenueRoom(APIView): def get(self, request, *args, **kwargs): pass def post(self, request, *args, **kwargs): print('wait its over here') def delete(self, request, *args, **kwargs): venuepk = kwargs.get('venuepk', None) venue = get_object_or_404(Venue, pk=venuepk) venuerooms = venue.room_set print(venuerooms) return Response({}) my hope is I could just interate venue rooms and check each object in venue rooms but I have a strong feeling its not going to work because venuerooms is not python objects? Perhaps it is. I will be updating this question after I do the for … -
Django Authentication Using 3rd Party App
So I'm writing a third-party application in C# to communicate with my Django application. A user registers on the Django application and saves their credentials to a PostGresQL database. I'm encrypting the password with their BCrypt plugin, so the password is stored in the database like so: bcrypt_sha256$$2b$12$R8G3wRDSMV1albrI6.7PT.sv4Po3A1XerBZmP/20hpvdGKRBwi7vi In my C# application, I attempt to login with the following code: NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; Password=PASSWORD;Database=DATABASE_NAME;"); conn.Open(); string query = "SELECT password, setup_stage FROM main_user WHERE email = '" + txtUsername.Text + "'"; NpgsqlCommand cmd = new NpgsqlCommand(query, conn); NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { string[] pass_params = ds.Tables[0].Rows[0]["password"].ToString().Split(new char[] { '$' }, 2); string myHash = BCrypt.Net.BCrypt.HashPassword(txtPassword.Text, pass_params[1]); if (myHash.Equals(pass_params[1])) { int stage = Convert.ToInt32(ds.Tables[0].Rows[0]["setup_stage"]); if (stage == -1) { Setup setup = new Setup(); setup.setStage(stage); setup.Show(); } else { MainForm main = new MainForm(); main.Show(); } this.Close(); }else { lblError.Text = "No username/password match for the credentials entered."; lblError.Visible = true; } }else { lblError.Text = "No username/password match for the credentials entered."; lblError.Visible = true; } My problem is that when myHash is created, is is not creating an equivalent hash. I've passed the correct password, … -
Which payment gateways can be integrated with django? Does Django support any of the existing payment gateways?
I want to build a django website and want to integrate a payment gateway that supports Bangladeshi payment methods. Is it possible? -
Django sum for each distinct value in another field
Say you have a model for order line items: class OrderLine(models.Model): product = models.ForeignKey(Product) quantity = models.DecimalField() unit = models.ForeignKey(Unit) Is it possible to summarize each product's total quantity for each distinct unit in one object? If not, how would you go about displaying it on one line? I've tried this which seems to be sort of on the right track but at the expense of losing the foreign key relationship. lines = lines.values_list('product', 'order_um').distinct().annotate(sum=Sum('order_qty')).order_by('product', 'order_um') -
Django Can't find my template
I've found many questions like this but no one have solved this mine. When I visit the url http://localhost:8000/catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ that is handled by this urls.py path: path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), than my view in the end returns this: I have a view that returns this: return render(request,'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) But I get the template error: TemplateDoesNotExist at /catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ catalog/book_renew_librarian.html Request Method: GET Request URL: http://localhost:8000/catalog/book/88a26558-d636-44c8-8831-242d98fa6d80/renew/ Django Version: 2.0.3 Exception Type: TemplateDoesNotExist Exception Value: catalog/book_renew_librarian.html Exception Location: C:\Users\Araujo\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: C:\Users\Araujo\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.4 Python Path: ['C:\\Users\\Araujo\\Desktop\\first_django\\locallibrary', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Araujo\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Wed, 14 Mar 2018 19:19:10 +0000 But I have the template in the \catalog\templates\book_renew_librarian.html How to solve it? -
Django Formset: saving only the first form of formset
SubTaskFormSet are my SubTasks Forms that i'm having troubles to save properly. In html template i'm dynamically adding/removing inputs thats correspond to elements of my formset, the problem is: only the first form from de formset is being saved. This is how its being created the formset(extra=1 displays 1 input when page loads). SubTaskFormSet = inlineformset_factory(Task, SubTask, form=SubTaskCreateForm, extra=1) This is how im passing the formset to context dict in "get_context_data" method from TemplateView context['form_sub_tasks'] = SubTaskFormSet(self.request.POST or None) Saving a task form and forms of the formset: if all((task.is_valid(), sub_tasks.is_valid())): task.user = self.request.user task = task.save() sub_tasks.instance = task sub_tasks.save() I noticed that when the value of this field changes, the equivalent number of forms from formset is successfully saved in database. <input name="sub_tasks-TOTAL_FORMS" value="1" id="id_sub_tasks-TOTAL_FORMS" type="hidden"> So my question is: how can i change this TOTAL_FORMS input to be possible save more than one form from formset? Of course it could be done via javascript or manually but i'm searching for a better way to accomplish it. -
Django get value in a single currency based on exchange rate
I have a model which has amounts donated in different currencies. Schema: class Donation(BaseSiteModel): """Donation to Fundraising Project""" donor = models.ForeignKey(UserProfile, related_name='donations', on_delete=models.PROTECT) amount = models.DecimalField(max_digits=12, decimal_places=2, default=0) currency = models.SmallIntegerField(choices=CURRENCIES, default=C_USD) Also, I have a table that contains exchange rates. class CurrencyExchangeRate(models.Model): from_currency = models.SmallIntegerField(choices=CURRENCIES) to_currency = models.SmallIntegerField(choices=CURRENCIES) rate = models.DecimalField(decimal_places=3, max_digits=10) Now, in order to get the sum of donations by a donor based on currency, the query will be Donation.objects.filter(donor=donor).values('currency').annotate(total_amount=Sum('amount')) The output should be something like [{'currency': 1, 'total_amount': Decimal('4.50')}, {'currency': 2, 'total_amount': Decimal('10001.00')}] Here I want the amount to be converted in a single currency (suppose USD) and should be sum of USD amount + non USD amount(multiplied by exchange rate) Is there any way to achieve this in a single query? -
Django template tag a model object.
I'm trying to return a different value for my model object rather than the information stored in the field. I'm running this in my html file. I've passed a query of 'localcampaigns' to my html file. In my HTML file I have: {% for campaign in localcampaigns %} <a href="/campaigns/{{campaign.id}}/">{{campaign.title}}</a> {{campaign.time}} {{campaign.event_date}} {{campaign.project_focus}} {% endfor %} So specifically, say I run this and for the {{campaign.project_focus}} I receive the database object of 'community001' - I want to take this and return something different than this 'community001' like "Community Project" I've tried to do this by: {% if '{{campaign.project_focus}}' == 'community001' %} Community Project {% endif %} But I'm unsuccessful. whenever I run != in the template tag, I get the response. So I know that the two don't match. How do I make the two match? Thanks. -
Django get resized image from model
I want to have method that will give me resized image, if i call this method on object, how can i do this with Pillow? my model: class Item(models.Model): title = models.CharField(max_length=255, null=True) img = models.ImageField() def __str__(self): return self.owner.first_name def get_image(self): image = Image.open(self.img) resized_image = image.resize((128, 128)) return resized_image This one always gives me something like that <PIL.Image.Image image mode=RGB size=128x128 at 0x7F001CF92D30> -
Accessing all children of abstract base class in django?
I am still researching whether to use abstract base classes or proxy models for my control panel application. I'm looking at the abstract base classes right now. Assume that I have a few models like this: class App(models.Model): name = CharField(max_length=100) class Meta: abstract = True class CMSMonitorApp(App): alerts = PositiveIntegerField() class PasswordResetApp(App): login = CharField(max_length=100) token = CharField(max_length=100) On the main page of the control panel, I want to display all of the available applications for my users. An easy way to do this would be to get everything that inherits the App abstract class. How can I all of the classes that inherit an abstract base class? -
How can I connect to a Samba 4 server from a Django application installed on IIS 7 using LDAPS?
I have a very specific problem. I had to install a Django application in Windows Server 2008 with IIS 7. For authentication I used the django-auth-ldap package and connected to the Samba 4 server via LDAP without difficulty. The problem begins when the LDAPS connection is tried because I do not know how to configure the application to recognize the security certificate in Windows. In Debian I know the procedure, I need to configure settings.py for this purpose. Thanks for the help. -
Adding a trailing slash to a Django root URL
I am serving through Apache and wsgi a Django Project. The server url is http://example.com and the alias for the project is myProject I'm trying to add automatically a trailing slash to the root url, therefore: http://example.com/myProject should become http://example.com/myProject/ In the Apache settings, I have the project alias: WSGIScriptAlias /myProject /path/to/wsgi.py In the myProject's main urls.py file for Django, I have these entries: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('externalModule.urls')), # I need to add the urls of an external module at this point. ] But doing in this way, if I request http://example.com/myProject the trailing slash is not added and it causes errors later on, during the site usage, due to some relative links. Intrestingly, if I change urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'foo/', include('externalModule.urls')), ] It works: http://example.com/myProject/foo becomes http://example.com/myProject/foo/. How can I get the same behavior at the root level? -
what is best choice to create charts in django? [on hold]
I am still confused what is best chart framework for Django. i am already tried google charts,fusion charts,etc... -
Django's adding parentheses itself to the model name in the admin panel
I don't know why this is happening to my website.. As my perspective, I'm doing all these things right. But there should be something which hid from my eyes. Here is a screenshot of the current result: And here is my models.py and admin.py files. models.py: from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.dispatch import receiver from . import managers class Profile(models.Model): # Relations user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='profile', verbose_name=_('user'), on_delete=models.CASCADE ) # Attributes - Mandatory interaction = models.PositiveIntegerField( default=0, verbose_name=_('interaction') ) # Custom Properties @property def username(self): return self.user.username # Methods # Meta and String class Meta: verbose_name = _("Profile"), verbose_name_plural = _("Profiles"), ordering = ('user',) def __str__(self): return self.user.username @receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) def create_profile_for_new_user(sender, **kwargs): if kwargs['created']: profile = Profile(user=kwargs['instance']) profile.save() admin.py: from django.contrib import admin from . import models @admin.register(models.Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['username', 'interaction'] -
Django relations between Models
What I currently have in my models is this: class Project(models.Model): project_name = models.CharField(max_length=255, unique=True, blank=False) def __str__(self): return str(self.project_name) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(choices=ROLE_CHOICES, max_length=255, default='Agent') Now my question is: Users should be able to have multiple Projects - so I obviously can't use a OneToOne-Field in the Profile-Model. Later I want to use it for example to just show a user news which are only related to the projects he participates in. What would be the best strategy to make this possible? Any input is highly appreciated. -
Installed Django and virtualenvwrapper-win. "mkvirtualenv myproject" command giving "DNS server not authoritative for the zone" error.
I am running Windows 7 with Python 3.6 and no other versions. I installed Django through pip successfully. Yet when I try to make new virtual project, I get "DNS not authoritativer error". I am logged in and running cmd prompt as Admin. What could be the issue here?