Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
uWSGI command not found
Background: I am in the process of deploying a Django site and from my understanding and research, I needed to get a web server, a WSGI protocol interface to actually run said python code and 'communicate' with it, and lastly a reverse proxy server to tie the two together and pass HTTP requests through the pipeline to Django. (By virtue of my install method, mod_wsgi is not an option thanks to EasyApache4 and cPanel so I cannot use the mod_wsgi sockets method) My problem: I have organized an apache 2 hosting server and managed to install mod_proxy and mod_proxy_uWSGI using the EasyApache4 auto installer. From what I understand, now I need to set up the proxy system to relay HTTP requests through mod_proxy_uWSGI which doubles up and also runs my Django site, however, I cannot access or configure mod_proxy_uWSGI. When I try using the following style command (sorry, I don't want my server URLs floating around the internet): uwsgi --http :8000 --wsgi-file test.py I get an error message: bash: uwsgi: command not found Am I missing something? -
Django CBV : get() and get_context_data()
I would like to get some indicators about get() and get_context_data() classes because I get an issue and I'm trying to understand why. I have a Django DetailView which let to display some statistics with multiple querysets. In the same class, I have a query string which shows the result from a get queryset. My code looks like this : class StatsView(DetailView): """ Create statistics pageview """ template_name = 'app/stats.html' def get(self, request): return render(request, self.template_name, context) def set_if_not_none(self, mapping, key, value): if value is not None: if len(value) != 0: mapping[key] = value def get_context_data(self, **kwargs): return context_data Like this, get_context_data() function doesn't work, but when I set get() in comment, it works fine. I think there is a small misunderstanding from myself. Maybe I don't use the good django generic display view or maybe it's not possible to use get() and get_context_data() together in the same class ? Thank you I read the Django documentation but I would like to get explanations from you -
How to handle meta_url in Django-CMS , its not a configurable parameter in Django CMS portal
As meta-url is not configurable, the new pages that are duplicating the existing pages are holding the same meta_url of the parent page. How to make meta_url a configurable parameter in djangoCMS ? Is there any work around to handle meta_url ? -
Django & ChartJS: creating dynamic links on pie chart
I am working on a Django template which consists of a doughnut pie chart with ChartJS. My template code with chartjs script is as below: {% block content %} <div class="py-3"> <div class="chartjs-size-monitor" style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; overflow: hidden; pointer-events: none; visibility: hidden; z-index: -1;"> <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div> </div> <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;"> <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div> </div> </div> <!-- Pie Chart Container --> <canvas id="myChart" class="js-chartjs-pie chartjs-render-monitor" width="830" height="414" style="display: block; height: 207px; width: 415px;"></canvas> </div> {% endblock %} {% block scripts %} <script type="text/javascript"> var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: [{% for investment in investments %}"{{ investment.name }}",{% endfor %}], datasets: [ { label: "Share", backgroundColor: ["#44a3e9", "#fa6586","#fccc5f"], data: [{% for investment in investments %}"{{ investment.principle }}",{% endfor %}] } ] } }); </script> {% endblock %} The blocks of the pie chart must be clickable and whenever someone clicks on any block of the chart it sends him to the associated page using a link (e.g www.exampl.com/project/34). But I am confused how to put dynamic IDs on the pie chart and generate links. Any kind of help is highly appreciable. Thanks. -
Why am I getting a null constraint error?
Im Trying to add comments to Facts(posts). When I try to submit a comment I get the following error? Im using postgres FYI IntegrityError at /fc/2/comment/ null value in column "comment_id" violates not-null constraint DETAIL: Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null). Exception Value: null value in column "comment_id" violates not-null constraint DETAIL: Failing row contains (8, It has plugins too, 2018-10-03 07:41:25.249524+00, 1, null). Model: class Fact(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) comment = models.ForeignKey('fc.Fact', on_delete=models.CASCADE, related_name='comments') text = models.TextField() created_date = models.DateTimeField(default=timezone.now) View: def add_comment_to_post(request,pk): fc = get_object_or_404(Fact, pk=pk) if request.method =="POST": form =CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.fc = fc comment.save() return redirect('fc_detail',pk=fc.pk) else: form =CommentForm() return render(request,'add_comment_to_post.html',{'form':form}) Form view: {% extends 'base.html' %} {% block content %} <h1>Check this fact</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} Form: class FcForm(forms.ModelForm): class Meta: model = Fact fields = ('title', 'text',) class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) … -
Django pagination with angular-datatables
My stack 1. Django 1.10 2. AngularJS v1.6.1 3. Restangular v1.6.1 4. angular-datatables 0.6 5. DataTables 1.10.16 What I am trying to do is, I am pulling data using restangular, storing it into a variable and iterating over it in angular template. I have also applied datatables='ng' to table in template and that is paginating data coming from api. The problem is it is paginating only first chunk(50) of data coming. I want to understand what property to set for angular-datatables so that it can generate pages for rest of the data, that will come from API? I tried following code, but this is not hitting the API only. $scope.dtOptions = DTOptionsBuilder.fromFnPromise(function(){ $scope.realestates = Restangular.one('realestates').getList().$object; return $scope.realestates; }) -
Django generate post data with QueryDict
I have a case where I need post data like this: {'data': ['content[]=8&content[]=7&content[]=6']} I want to write a test where I need the data in this format. Is this a special format that I can generate with a function or do I need to write this manually? This is the important part of the function I want to test: data = QueryDict(request.POST['data']) list_ = data.getlist('content[]') -
Django unit test wait for database
I have a Django command that runs a loop until the database becomes available: import time from django.db import connections from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): """Django command to pause execution until database is available""" def handle(self, *args, **options): """Handle the command""" self.stdout.write('Waiting for database...') db_conn = None while not db_conn: try: db_conn = connections['default'] except OperationalError: self.stdout.write('Database unavailable, waiting 1 second...') time.sleep(0.1) self.stdout.write(self.style.SUCCESS('Database available!')) I want to create unit tests for this code. I've managed to test the database being available from the start like follows: def test_wait_for_db_ready(self): """Test waiting for db when db is available""" with patch('django.db.utils.ConnectionHandler.__getitem__') as gi: gi.return_value = True call_command('wait_for_db') self.assertTrue(True) Is there a way to test that the command waits for the DB to be available before returning? So far I've tried the following, however it doesn't work as attempt is not accessible outside of getitem. def test_wait_for_db(self): """Test waiting for db""" attempt = 0 def getitem(alias): if attempt < 5: attempt += 1 raise OperationalError() else: return True with patch('django.db.utils.ConnectionHandler.__getitem__') as gi: gi.side_effect = getitem call_command('wait_for_db') self.assertGreaterEqual(attempt, 5) -
What are the minimum options required to safely allow M2M field empty in DRF serializer Fields?
There are four options: required, allow_empty, allow_null and allow_blank in DRF serializer fields. To allow empty M2M field, is it safe to have just allow_empty as True or do other options need to be coordinated as well? Also, what is required for vice-versa? -
Totaling inside a cart model the subtotal of each TabularInline entry in Django Admin
Not sure if this is possible, but in Django Admin, I'd like to total up each of the inline model class entries I have in a separate, but related (through foreignkey) cart model. Is there a way to do this and save under my cart model class' total_price attribute or somehow use a filter or form widget to add all the subtotals together for the same purpose? Thanks in advance for any help! So far in my admin.py I have a TabularInline admin class that returns the subtotal for each entry by multiplying its quantity by its respective price. Then my CartAdmin class displays that inline relationship inside the cart model detail view. admin.py class EntryInline(admin.TabularInline): model = Entry extra = 0 readonly_fields = ['subtotal'] exclude = ['price'] def subtotal(self, obj): return "$" + str(obj.quantity * obj.inventory.price) class CartAdmin(admin.ModelAdmin): inlines = [EntryInline] fieldsets = ( (None, { 'fields':('user', 'total_price') }), ) models.py class Inventory(models.Model): quantity = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) class Cart(models.Model): user = models.OneToOneField(User) total_price = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) class Entry(models.Model): cart = models.ForeignKey(Cart, related_name="entries") inventory = models.ForeignKey(Inventory, related_name="entries") quantity = models.PositiveSmallIntegerField(default=1) price = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True) PS - Underneath is a screenshot of what I'd … -
Django auto assign value to foreign key when a form is submitted?
I want to render the name of the company into the database automatically whenever user submits the create form... This is my model: class company(models.Model): User = models.ForeignKey(User,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True) Name = models.CharField(max_length=50,blank=False) class group1(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) group_Name = models.CharField(max_length=32) Company = models.ForeignKey(company,on_delete=models.CASCADE,null=True,blank=True,related_name='Company_group') This is what I was trying to do in my views.py: class group1CreateView(LoginRequiredMixin,CreateView): form_class = group1Form template_name = "accounting_double_entry/group1_form.html" def form_valid(self, form): form.instance.User = self.request.user form.instance.Company = company return super(group1CreateView, self).form_valid(form) But got this error: ValueError: Cannot assign "<class 'company.models.company'>": "group1.Company" must be a "company" instance. It worked for the User but is not working for the Company.. Can anyone tell me what I am doing wrong in this??? Thank you... -
"Fatal Python error: initsite: "and "AssertionError: SRE module mismatch"
I am trying to install pip and pillow for Django to web-development. I am using python 3.7. But it gives this error, even though I have fixed the path for pip in my "system variables" but the same problem. C:\Users\Sumon>pip Fatal Python error: initsite: Failed to import the site module Traceback (most recent call last): enter image description here -
How to add user to a group in admin
Since the default django admin group form does not have field for selecting users in a group. I Wrote down some codes which i got online to add the selected users field.Everything is working just fine. Until i tried saving the group form i created, I get this error 'Group' object has no attribute 'user_set' class GroupAdminForm(forms.ModelForm): class Meta: model=group exclude=[] users=forms.ModelMultipleChoiceField(queryset=User,objects.all(),widget=FilteredSelectMultiple('users',False),required=False) def __int__(self,*args,**kwargs): super(GroupAdminForm,self).__int__(*args,**kwargs) if self.instance.pk: self.fields['users'].initial=self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self,*args,*kwargs): instance= super(GroupAdminForm,self).save() self.save_m2m() return instance I am getting this error 'Group' object has no attribute 'user_set' . I donot know on how to go about resolving this problem . Please help . I am navies in django. Help Hlep please -
Django foreign key constraint with Model that lives in different database
I'm trying to use the oauth2_provider library which provides a model for AccessToken, which foreign keys into a User model. My User model will actually live in a different database from the OAuth2 token models. I can use a router to direct which DB to use for a particular model, but am I correct in concluding that Django would not support a foreign key to a model in a different DB? If I still wanted to extend from the AbstractAccessToken with my User in a different DB, is there any way that Django allows me to populate the user_id foreign key column at all? Or would I simply need to leave it null and define and have my custom AccessToken class define its own unconstrained external_user_id column? -
ValueError at /Add invalid literal for int() with base 10: 'O'
This many to many field "location" saves into the database but the webpage returns this error. "ValueError at /Add invalid literal for int() with base 10: 'O'" models.py INSIDEOUTSIDE = ( ('In','Inside'), ('Out', 'Outside'), ) class location1(models.Model): locate = models.CharField(max_length=3, choices=INSIDEOUTSIDE) def __str__(self): return self.locate class Reservation(models.Model): name = models.CharField(max_length=22) psize = models.IntegerField('Party Size') Date = models.DateField() Time = models.Tienter code heremeField() location = models.ManyToManyField(location1, choices= INSIDEOUTSIDE) forms.py class ReservationsForm(forms.ModelForm): class Meta: model = Reservation fields = ('name', 'psize', 'Date', 'Time', 'location') widgets = {'Date': SelectDateWidget(), } views.py def add(request): form = ReservationsForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect('Add') else: form = ReservationsForm() return render(request,'app/Add.html',{'form': form}) Thanks! -
django rest framework serializers giving "serializers.Language.None"
Here is my serializers.py class GetCompanySerializer(serializers.ModelSerializer): language = serializers.CharField() class Meta: model = Company fields = ('company_name','started_from','country','email','website','ip','active','language') here is my views.py class CompanyView(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'GET': serializer_class = GetCompanySerializer return serializer_class Here is my models.py class Company(models.Model): company_id = models.BigAutoField(primary_key=True) company_name = models.CharField(max_length=255) started_from = models.DateTimeField(auto_now=True) country = models.CharField(max_length=255) email = models.EmailField(max_length=254) website = models.URLField() ip = models.GenericIPAddressField(default=get_ip(),null=True,blank=True) active = models.BooleanField(default=True) def __str__(self): return self.company_name class Language(models.Model): language_id = models.BigAutoField(primary_key=True) language_name = models.CharField(max_length=255) language_logo = models.FileField() created_on = models.DateTimeField(auto_now=True) latest_build_on = models.DateTimeField(auto_now_add=True) latest_version = models.DecimalField(max_digits=5, decimal_places=2) company = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='language') def __str__(self): return self.language_name giving api: [ { "company_name": "Guido van dom rossum", "started_from": "2018-10-03T04:58:54.889132Z", "country": "Netherland", "email": "help@python.com", "website": "https://python.org", "ip": "127.0.0.1", "active": true, "language": "serializers.Language.None" } ] it should give the language name for language field bit it is giving "serializers.Language.None" instead. please have a look into this.. -
Rest-Framework return 404 Not Found by nginx
I have being trying to resolve this issue but it seems as a beginner I am not able to. I have created a project following the tutorial on Django-Rest-Framework and it works perfectly when i run Djnago server. However when I wanted to deploy it using uwsgi and nginx, following many tutorials nginx would display Admin Page but it returns 404 Not Found when i try to access Rest-Framework. Here is my uwsgi.ini # _uwsgi.ini file [uwsgi] locates chdir = /Users/userName/Desktop/Project/API/Project/ module = project.wsgi # the virtualenv (full path) home = /Users/userName/Desktop/Project/venv master = true env DJANGO_SETTINGS_MODULE=Project.settings # maximum number of worker processes processes = 10 # the socket (use the full path to be safe) socket = /tmp/project.sock # ... with appropriate permissions - may be needed chmod-socket = 664 # clear environment on exit vacuum = true # create a pidfile pidfile = /tmp/project.pid # background the process & log daemonize = uwsgi.log And this is my nginx. # the upstream component nginx needs to connect to upstream mysite { # server 127.0.0.1:8001; server unix:///tmp/project.sock; # for a file socket, more effective } # configuration of the server server { # the port your site will be served … -
Selecting children from a parent row with a very specific ruleset
I have a parent model that has more than 30,000 records which have at least 3-4 children each. I want to be able to display the children on a table with a very specific ruleset. from django.db import models from django.utils.translation import ugettext_lazy as _ class Parent(models.Model): name = models.CharField(_("Name"), max_length=128) class Child(models.Model): parent = models.ForeignKey(Parent) state = models.CharField( _("State"), choices=( ('A', "Apple"), ('B', "Ball"), ('C', "Cat"), ('D', "Dog"), ) ) Using the two models above, I have filtered out all Child objects who's state is "A" or "B". The part of the requirements that I find hard to meet is, I might have a some Bs inbetween the As and Cs, for example, arranged in a row: [R] [R] [R] Apple Cat Cat If they're without B-states inbetween, I want to retrieve the As and Cs but I have a special case where I want to retrieve the Latest B before the next C instead of the A or B themselves. [R] [R] [R] [R] Apple Ball Cat Ball Ball Cat Ball Cat In summary: I want to always select the latest B before the next C, if there are Bs after the As or Cs or the end … -
Can i compare DateTimeFields whit the tag "if"?
I have this issue and i can't see why it isn't working I have this model class Tweet(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) content = models.TextField(validators=[validate_content]) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.pk) And i have this "for" where i call the objects of the model ... {% for t in object_list %} <tr> <td>{{ t.user }}</td> <td>{{ t.content }}</td> {% if t.updated == t.timestamp %} <td>Created: {{ t.updated| timesince }} </td> {% else %} <td>Updated: {{ t.updated| timesince }} </td> {% endif %} ... So, basically, what i want is to show the first message if the fields have the same content, wich should be true if the object has just been created, but it shows the second message. I have already checked in the admin panel the content of the fields and its the same in both, so i dont know what could be -
Django query for transactions only where there are multiple transactions for company on the same date
I have a model that consists of company name and transaction date columns. How do I construct a Django query that retrieves only those transactions for which there are multiple transactions for that company on the same date? It should exclude any transactions if there is only one transaction for that company on that date. Heres what my data model looks like: class Sales(models.Model); name = models.CharField(max_length=50, null=True, blank=True) transactionDate = models.CharField(max_length=50, null=True, blank=True) -
Image in static couldnt be found without using CSS under Django frame
I want to input an image in the .html so I put image in the static files and I dont want to apply CSS. But it says cant find that pic I wanna use. In the .html file I wrote like this So anybody can tell me what to do or anything I should change in other files like settings.py ? enter image description here My files context is what image shows -
how can I deactivate a form button field for file upload when a selection is made in drop down menu filed without using JQuery and AJAX
I have implemented a crispy form and crispy form helper to render a form. The form contains a drop down selection menu and a file submission button. However I want to deactivate the file submission button when the selection "File not required" is made in the drop down menu. However I want all this to be done before the form submission button is pressed (i.e. before invoking POST method). I'm trying to avoid any Jquery and AJAX implementations. Is there any Django way of doing this using Django Forms, views or Django Crispy Forms. Crispy forms has HTML object for its layout class. Is there any way of doing above mentioned in using HTML objects or any other objects of layout class. Below is the chunk of Django Form that is rendered in its respective template. self.fields[field_name] = forms.ChoiceField(choices=choices, label='') file_name = str(customer_Id) self.fields[file_name] = forms.FileField(label=_("Attach PDF"), required=True) self.helper.layout.append(Layout( HTML('<tr><td>{}</td><td>{}</td><td>'.format(customerId, name)), field_name, HTML('</td><td>'), file_name, HTML('</td></tr>'), )) self.helper.layout.append(Layout(HTML('</tbody></table>'))) -
sqlite3.OperationalError: near "........": syntax error
windows 7 python 2.7 Django 1.11 I have used Django to develop a website. In the backend I have the sqlite database which have 2 tables. One table accepts the form user submitted, and the other is for comparison. Once a form A is submitted by the user, it will be save under table catalog_fw, and the catalog_fw.ODM and catalog_fw.project_name will be compared with the ones in the table catalog_fw_instance. If one line have the exact same content for catalog_fw.ODM and catalog_fw.project, catalog_fw_instance.level will be combined with A to pass to the an .exe to generate a txtx file. However, error occurs in this line: c.execute("catalog_fw_instance.level,...... ` when I run this python file: sqlite3.OperationalError: near "catalog_fw_instance": syntax error The code to get sqlite data, compare and pass to the .exe is here: def when_call_exe(): with sqlite3.connect('db.sqlite') as con: c = con.cursor() c.execute("catalog_fw_instance.level, SELECT catalog_fw.ODM_name, catalog_fw.project_name, catalog_fw.UAP, catalog_fw.NAP, catalog_fw.LAP, catalog_fw.num_address FROM catalog_fw INNER JOIN catalog_fw_instance ON catalog_fw.ODM_name=catalog_fw_instance.ODM_name AND catalog_fw.project_name=catalog_fw_instance.project_name") print(c.fetchone()) parameter = c.fetchone() #pass to exe args = ['.//exe//TestSecureAutoV1.exe', parameter[0], parameter[1]+parameter[2], parameter[3], parameter[4], parameter[5], parameter[6]] output = my_check_output(args) if 'SUCCESS' in output: filename = output[28:-1] else: filename = output[8:-1] downloadlink = os.path.join('/exe', '%s' % filename) #save link to sqlite db c.execute('''UPDATE … -
Django - How to add a value to each tuple in values_list
I have a values_list: mylist = Region.objects.values_list('region_id','region').order_by('region') for x in mylist: print(x) returns (2, 'Africa') (9, 'Antarctic') (3, 'Asia Temperate') ... I would like to add a third element to each tuple to get (2, 'Africa','x') (9, 'Antarctic','y') (3, 'Asia Temperate',x') I have tried: for a in mylist: if some condition: a + ('x',) else: a + ('y',) but it doesn't work. -
How to properly import and configure .csv table in sqlite3
I'm extremely new to django and wanted to figure out how to properly import .csv files into tables in sqlite3 and configure my 'home' section to obtain information from that specific table. Here's what I've done so far.. I've imported a .csv file into a tabled called "csv_master_data", and I want to configure my "home" directory to be able to retrieve data from that particular table Next after watching some tutorials I didn't completely understand how to setup models.py in order to communicate with that table, so far it seems like people are showing how to create a brand new section in the database, and I want to be able to retrieve the information from the db, again sorry for the newbie question, I'm completely new to databases and django as a whole. If you notice in my models.py, is this how it would be done? please disregard the class Schools(models.Model) and I know the names for the rows are incorrect, I just want to know if I rename them using the names within the rows of my csv_master_data would they properly communicate, and how I would be able to migrate them properly to understand that, I want to obtain …