Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin suit tabs not showing
I have a point of interest model that is linked to a couple other models by foreign key that I would like to make into tabs in the Django admin by using suit tabs. In my admin class I am creating two admin inline classes and giving them suit tab classes specified in the main admin class they are linked to. However whenever I go to the admin in the browser, all the models are still just stacked on top of each other and not showing as tabs at all. We recently started using the latest version of suit, which is a little different in the way you configure what models will show up and where, but I don't think that has anything to do with the suit tabs, and am at a loss as to why else it wouldn't be working. admin.py from django.contrib import admin from poi.models import PointOfInterest, PointOfInterestTag, PointOfInterestInformation class PointOfInterestInfoInline(admin.TabularInline): model = PointOfInterestInformation suit_classes = 'suit-tab suit-tab-info' readonly_fields = ('create_date', 'modified_date') fieldsets = ( (None, { 'classes': ('full-width',), 'fields': ( 'info_type', 'header_image', 'information', 'phone', 'website', 'file_attachment', 'create_date', 'modified_date') }), ) class PointOfInterestTagsInline(admin.TabularInline): model = PointOfInterestTag suit_classes = 'suit-tab suit-tab-tags' fieldsets = ( (None, { 'classes': … -
Filter a contenttype with list of content object's field
I creating an app where users can post with its related tags: class Tag(models.Model): name = models.CharField(max_length=255, unique=True) class Post(models.Model): user = models.ForeignKey(User) body = models.TextField() tags = models.ManyToManyField(Tag) pub_date = models.DateTimeField(default=timezone.now) activity = GenericRelation(Activity) class Photo(models.Model): user = models.ForeignKey(User) file = models.ImageField() tags = models.ManyToManyField(Tag) pub_date = models.DateTimeField(default=timezone.now) activity = GenericRelation(Activity) class Activity(models.Model): actor = models.ForeignKey(User) verb = models.PositiveIntegerField(choices=VERB_TYPE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') pub_date = models.DateTimeField(default=timezone.now) What I want to do is filter the Activity with the a list of users, and a list of tags of the from list of Post objects. Eg: UserA created a new Post obect with tags(#class, #school) UserB created a new Post object with tags(#professor, #teacher) UserC created a new Post object with tags(#school, #university) UserD created a new Post object with tags(#university, #school) So say I want to filter Activity with user_list=[UserA, UserC] and tag_list = [#class, #teacher] It should return: UserA created a new Post obect with tags(#class, #school) UserC created a new Post object with tags(#school, #university) UserB created a new Post object with tags(#professor, #teacher) To filter the Activity with users, I can query this way: Activity.objects.filter(actor__in=user_list) But, how do I filter … -
Django Rest Framework -A concrete example of when you would use a serializer class vs a model serializer class
I am learning django rest framework, while I understand what a serializer does and when you would use it, I cannot fully seat the need for a serializer and a model serialzer class. Can one of you please give me a concrete real world example use case of both please? -
Django app on production server gives ImportError at / No module named 'app.models'
ImportError at / No module named 'app.models' from app.models import Category, Item, AdvancedInfo, Theme -
How do I send a private message from an user to another?
I'm trying to create private chat application, but to be able to move forward I need to understand how I can send a secure and private message from an user to another. I have no idea how to proceed on doing this I thought creating a model with a receiver and a sender, but I have no idea how I should configure my view so the message from user A goes to user B ? models.py class chat(models.Model): created = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, blank=True, null=True, related_name="sender") receiver = models.ForeignKey(User, blank=True, null=True, related_name="receiver") message = models.TextField(max_length=255) forms.py class chatForm(forms.ModelForm): class Meta: model = chat fields = ('receiver', 'message') views.py def write(request): if request.method == "POST": sender = request.user form = chatForm(request.POST) if form.is_valid(): form.save() else: form = chatForm() template = 'compose.html' context = {'form': form} return render(request, template, context) This is what I wrote till now but I don't get what I should do from there, How can I link the sender and the receiver ? -
How can I check whether an entry that a user inputs has already been entered by him/her in the past 30 days in my django website
I am building a survey website using Django 1.7.7 and Python 3.4.4, where a user enters say his "name" and "id". I have a sql table called "list" that stores all the users names and id's. I would like my Django website to check if when a user enters his/her name and id, if the id already exists in the table for the past 30 days. Basically if the user's id exists in the past 30 days, he/she will not be prompted to take the survey, else they would have to take the survey. I know I have to build a view function that checks this condition but I am unable to figure out what the query/logic should be. Any help on the view function would help me out in my development immensely! Thank you. -
Integrate polymer into mako templates
I'm working on a project which extensively uses django and mako templates and I want to use Polymer framework to change it's UI incrementally (with the help of encapsulation features that shadow dom provides). But I don't know how to use it for example in mako templates. -
Django url warning urls.W002
Sorry in advance if this question look a bit superfluous but is something that is really bothering me. I have a set of API's written in Django defined by the following urls. # urls.py import ... urlpatterns = [ url(r"^api/v1/account", include(profile.urls)) ] and # profile/urls.py import ... urlpatterns = [ url(r"^$", AccountAPI.as_view()), url(r"^/login$", LoginAPI.as_view()), url(r"^/logout$", LogoutAPI.as_view()) ] This configuration should allow only the urls: /api/v1/account /api/v1/account/login /api/v1/account/logout This work for my purpose but I keep having warnings like(I have several API defined with this rule and the warning list is way bigger): ?: (urls.W002) Your URL pattern '^/login$' has a regex beginning with a '/'. Remove this slash as it is unnecessary. ?: (urls.W002) Your URL pattern '^/logout$' has a regex beginning with a '/'. Remove this slash as it is unnecessary. If I remove the slash the server will not validate the urls I defined. For that I have to had a slash to the first level of the urls like: # urls.py import ... urlpatterns = [ url(r"^api/v1/account/", include(profile.urls)) ] And this will make the account call to end with a slash, something I don't want to. I feel that I have defined the urls the most elegant … -
Besides HTML, JQuery, and Javascript what technology does Weebly and Wix use
Besides HTML/HTML5, JQuery, and Javascript what technology does Weebly and Wix use? Does it use Django, Bootstrap to make widgets. -
Using the Django ORM to join on the same table
I am currently switching our server from Java to Python (Django) and am using the ORM to recreate our SQL queries, one of them is proving difficult as I need to join on the same table. Below is the query SELECT U1.suser, COUNT(U1.id) FROM United U1 INNER JOIN United U2 ON U1.sUser = U2.pUser WHERE U2.sUser IN (select sUser from united where pUser = '105660') and U1.pUser = '105660' and U1.sUser IN ('580664','1015396') GROUP BY U1.id, U1.suser This is my model: class United(models.Model): id = models.IntegerField(primary_key=True) puser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, db_column='puser') suser = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, db_column='suser', related_name='secondary_united') date = models.DateTimeField(max_length=34, blank=True, null=True, auto_now_add=True) class Meta: db_table = 'United' unique_together = (('puser', 'suser'),) the query is meant to find the number of mutual connections between myself (the calling user) and all of their friends (the list of ID's) The query works how I want it to using straight SQL (although I cannot get it to work using the .raw() method because of a primary key error but I would like to find a way to do it using the ORM. -
Counting Boolean Values in field of Child Model in Django QuerySet API
I have the following model (below).I would like a query that returns every record of parent Question(models.Model), where ALL the values for the is_relevant field within the child Choice(models.Model) are "True". Having a difficult time creating the QuerySet. Any Assistance would be very helpful. Thanks model.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) is_relevant = models.BooleanField() -
How to make a POST request using DJANGO REST framework with ajax
this is my models class PoliceAssurance(models.Model): Numpolice = models.IntegerField() Raison = models.CharField(max_length=50) Tel = models.IntegerField() Email = models.CharField(max_length=50) and the serializers class PoliceSerializer(serializers.ModelSerializer): class Meta: model = PoliceAssurance fields = ('Numpolice','Raison','Tel','Email'); now i need to post data with an ajax request -
create() takes exactly 1 argument (2 given) error in Django Rest Framework
I am using a custom user model for my API. The following are the codes for my project: models.py class AccountManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Users must have a valid email address.') if not kwargs.get('username'): raise ValueError('Users must have a valid username.') account = self.model( email=self.normalize_email(email), username=kwargs.get('username') ) account.set_password(password) account.save() return account def create_superuser(self, email, password, **kwargs): account = self.create_user(email, password, **kwargs) account.is_staff = True account.is_superuser = True account.save() return account class Account(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40, blank=True) last_name = models.CharField(max_length=40, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __unicode__(self): return self.email def get_full_name(self): return ' '.join([self.first_name, self.last_name]) def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser I am serializing the Account model using a serializer as shown below in serializers.py class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model = Account fields = ( 'id', 'email', 'username', 'created_at', 'updated_at', 'first_name', 'last_name', 'password', 'confirm_password', ) read_only_fields = ('created_at', 'updated_at',) def create(self, validated_data): return Account.objects.create(**validated_data) def update(self, instance, validated_data): instance.username = validated_data.get('username', instance.username) instance.save() password … -
Django - delete multiple models in a record
I'm having a problem I would like to know if you could help me out. I'm having a table where I'm showing three different models and that's working ok. My problem is when I want to delete that record, as you know I have to specify which model I'm picking so I can delete it. I used to do it with three different tables one table for each model, but now as I made one table for the three models I have no clue how to do it. I've been trying different ways but nothing worked. Here's what I got: Views.py def eliminar_activos(request, id): opc = activo_opc.objects.get(id=id) #first model odbc = activo_odbc.objects.get(id=id) #second model eip = activo_eip.objects.get(id=id)# third model delete = chain(opc,odbc ,eip ) delete.delete() messages.success(request, "Success!") return redirect('activo') Urls.py url(r'^eliminar_activos/(?P<id>\d+)/$',views.eliminar_activos, name='eliminar_activos'), Template: <td><a href="{% url 'eliminar_activos' item.id %}"> Eliminar </a> </td> note: only works with first model, not working with the rest. if I try with the other two models I got this error: activo_opc matching query does not exist. Is there a possible way to do it without having three tables? Thanks! -
javascript ajax changes the variable that django sended from views
for strange reasons the value of variable that i am sending from django to html gets change in javascript ajax. i am sending id from veiws.py and then in body i use {{ id }} and it is equal to the value that it was in veiws.py. but when in i use var id = {{ id }}; i get different value, the new value is slightly different than the original value. what am i doing wrong here? in views.py: context = { 'id' : str(id) } return detail_page(request,context) in .html : <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type = "text/javascript" language = "javascript"> var myVar = setInterval(ReLoad , 5000); var id = {{ id }}; function ReLoad() { var url = '/data/' + id; $.get( url, function(data) { var result = JSON.parse(data.replace(/&quot;/g,'"')); console.log( JSON.parse(data.replace(/&quot;/g,'"'))['code'] ); document.getElementById("code").innerHTML = result['code']; }) .fail(function (jqxhr, status, error) { console.log('error', status, error) }); } </script> <head> <body> {{ id }} <div class="w3-container" id="code"></div> </body> -
Create an email in django with an HTML body and includes an attachment
Can I send an html formatted document as the body of an email and include an attachment? send_mail() has an option for html_message but the EmailMessage class does not. My understanding is that to send an attachment, I need to use the EmailMessage class to use the attach_file method. Am I missing something? I thought send_mail() uses the EmailMessage class, so why do these two features seem mutually exclusive? -
Django forms DateTimeInput widget- how to specify max date?
I have a form displayed in my Django project, and one of the form fields is a DateTimeInput widget, defined with: presentation_date = mDateTimeField(required=False, label="Presentation date", widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M')) This widget currently displays all dates between the start of last year to the end of this year (01/01/2016- 31/12/2017). However, at the end of last year this caused some issues, as it meant that users were unable to select dates for the beginning of this year. What I want to do is extend the range of the dates available for selection in the widget by one year (i.e the new range would be 01/01/2016- 31/12/2018). I understand that it is possible to do this using form validation (for example, by writing a view such as clean_presentation_date() and performing the validation inside that view, but this won't solve the issue I'm having- as currently, dates before 01/01/2016 or after 31/12/2017 (displayed in the datetimepicker calendar that's shown when the user selects the field in the form) are 'greyed out' and it is not possible to select them. This is exactly the functionality that I want, but I just want to change the values of the dates on which it is performed, so … -
How to display the graph more than once?
I am getting user input,the user input is saved in the database. From database the values are fetched to display the graph. I am using matplotlib package. Every time the graph is displayed with no problem when the server is run for the first time , but when I try to display the graph again the page keeps on loading forever. Everytime I have to restart the system to stop the page from loading. I tried to solve the problem by adding close(),clf() methods, but the problem persisted. I'm using Python2.7,Django 1.10.4 and mysql **Views.py** def show(request): try: x = [] y = [] con = MySQLdb.connect("localhost", "root", "", "mydb") c = con.cursor() c.execute("select * from dummy") row = c.fetchone() while row != None: x.append(row[0]) y.append(row[1]) row = c.fetchone() plt.plot(x, y) plt.title("THE GRAPH") a = max(y) a1 = min(y) a2 = numpy.mean(y) plt.xlabel("X-AXIS",color='red') plt.ylabel("Y -AXIS",color='red') plt.text(-2,1,"Max Y-Value:"+str(a),verticalalignment="top",horizontalalignment="right") plt.text(-2,2,"Min Y-Value:"+str(a1), verticalalignment="top", horizontalalignment="left") plt.text(-2,3,"Avg Y-Value:"+ str(a2), verticalalignment="top", horizontalalignment="center") plt.show() return render(request,"back.html",{}) -
Use php while running mod_wsgi-express with django
I am currently running a django application on my server and everything is fine with it but when I try to access php files like phpliteadmin.php which is located in /etc/mod_wsgi-express-80/htdocs I can only see the code but the php is not executed. I could find similar questions but nothing really helpful. I just started web developing so I need some help. Some say I should change the <VirtualHost *:80> part but there are multiple of it and my /etc/mod_wsgi-express-80/httpd.conf looks different to theirs, I assume it's because they are not using the "express" version. Thanks for your help! -
502 error django + nginx + gunicorn - connect() recv()
I'v set up Digital Ocean one-click app (django + neins + gunicorn are installed and setup https://www.digitalocean.com/community/tutorials/how-to-use-the-django-one-click-install-image). Default worked for me , but after I tried to apply code changes via service gunicorn restart I received 502 error with the following nginx error log line connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 178.136.215.70, server: _, request: "GET / HTTP/1.1",upstream: "http://unix:/home/django/gunicorn.socket:/".. I have looked thought similar issues and found that often it's caused by mistake in ALLOWED_HOSTS, everything is right there, but I also tried to replace 'ip' or 'www.adress.com' with single '*' and got different error: recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 178.136.215.70, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "192.241.176.184" -
Sending email from EC2 instance using third-party SMTP server taking way too long
I have a django app that sends notification emails. I'm using Bluehost's SMTP server. When in my local machine, using django's dev server, the emails arrive in about 5-10 minutes, which is not optimal but acceptable. However, when on AWS, the emails take hours to arrive. Here's what I'm using: EC2 instance Docker container with Ubuntu, nginx, gunicorn I have a couple of questions: I'm unsure as to where the problem is (EC2, docker container, django, etc), could someone point me in the right direction? I've seen in several places that SES is the way to go. Is this the case? I find it a little restrictive Thanks! -
Django error while running server settings
I'm trying to execute python manage.py runserver But it throws an error saying ImportError: Could not import settings 'survivalguide.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named survivalguide.settings I installed Anaconda with python 2.7 and set up a virtualenv. My manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "survivalguide.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) My current os.path ['', '/Users/KWYI/Documents/Python_Practice/Django_Practice/survivalguide', '/Users/KWYI/anaconda/envs/PyCon/lib/python27.zip', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/plat-darwin', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/plat-mac', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/lib-tk', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/lib-old', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/lib-dynload', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/site-packages', '/Users/KWYI/anaconda/envs/PyCon/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg'] I'm troubleshooting for hours now and still can't figure out what the problem is. I appreciate your help! -
Django site architecture
When you are busy developing an app, it is sometimes easy to get carried away and write many many models, somewhat related. Then, the question is how to layout the website given all the models. Say you have the following models: models: M1, M2, ..., M60 You then come to realize you can divide them into apps: apps: AP1, AP2, ..., AP12 Then, after a while you might realize you have different projects, with different databases, business logic, target audience, etc. (e.g. a site that has lodging, skiing, equipment rental, eCommerce, etc. all under one site) projects: P1, P2, P3 The question is if it is better to have semantically unrelated apps within one project or group related apps under separate projects? Site | P1 - P2 - P3 | ... ---------------- | | | | AP1 AP2 AP3 AP4 | ... --------------------- | | | | | M1 M2 M3 M4 M5 OR: Site | Solo_Project | ---------------- | | | | AP1 AP2 AP3 AP4 | ... --------------------- | | | | | M1 M2 M3 M4 M5 If the former, then how should one have a meta settings.py to specify the ROOT_URLCONF and all other settings that … -
Django filter by number of matches
Say I have model with 10 boolean fields. Input is 10 boolean values. How can I obtain a QuerySet that will retrieve only rows with 6 or more matches? -
django-nvd3 xdata time from model
I'm looking at: demo_linewithfocuschart from https://github.com/areski/django-nvd3/tree/master/demoproject/demoproject the ydata are loaded correctly but I can't get the xdata from the db, this is a working view but xdata aren't real: def demo_linewithfocuschart(request): """ linewithfocuschart page """ nb_element = 10000 start_time = int(time.mktime(History.objects.first().date_ref.timetuple())*1000) xdata = range(nb_element) xdata = map(lambda x: start_time + x * 1000, xdata) ydata=map(str,History.objects.values_list('Z01', flat=True)) tooltip_date = "%d %b %Y %H:%M:%S %p" extra_serie = {"tooltip": {"y_start": "Temperatura di: ", "y_end": ' C'}, "date_format": tooltip_date} chartdata = { 'x': xdata, 'name1': 'Z01', 'y1': ydata, 'extra1': extra_serie, } charttype = "lineWithFocusChart" chartcontainer = 'linewithfocuschart_container' # container name data = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, 'extra': { 'x_is_date': True, 'x_axis_format': '%d %b %Y %H', 'tag_script_js': True, 'jquery_on_ready': True, } } return render_to_response('linewithfocuschart.html', data) How can I get the xdata from the model? Like: xdata=History.objects.value_list('date_ref').timetuple() this is my model: class History(models.Model): id = models.AutoField(primary_key=True) date_ref = models.DateTimeField(db_column='DATA_RIF', verbose_name='Data di Riferimento', auto_now_add=True) Z01 = models.DecimalField(max_digits=6,decimal_places=2,default=Decimal('0.00'))