Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting model objects information from html page in django
I created a simple login/signup web app in django. I wana get my current user's(the object of my User model that is logged in) informations (the value of attributes of my user model in models.py). but i don't find any way to get my object information. how can i get my current user data from my .html page? thanks -
I am trying to import a models.py method, but get error no module named
I have 2 apps: friends/apps/loginreg/models.py/User friends/apps/friends/views.py I am trying to import the User method into the views.py file. These are my imports: from __future__ import unicode_literals from .models import Friend from loginreg.models import User from django.shortcuts import render, redirect It continues to give error no module named loginreg.models -
Consistent user authorization across url with/without www
I need to clarify a fundamental concept (beginner here). In a Django web app I'm practicing on, I notice that if one logs in via going to example.com, they remain logged out on www.example.com (and can then go on to create a clone account). 1) Why does this happen? 2) What's the standard practice to iron out this issue? I.e., give one consistent experience across www and no-www. In case the answer is as basic as just a redirection, I could use some pointers and an illustrative example there too - I'm using nginx reverse proxy with gunicorn. -
Why do I get AttributeError when trying to open a folder in django cms filer manager?
I have a fresh install of django cms and when I try to create a folder and add images to it using the filer app it just gives me the error: AttributeError at /en/admin/filer/folder/1/list/ 'str' object has no attribute '_meta' it looks like the issue is in filer/admin/folderadmin.py in directory_listing I thought maybe it had something to do with the fact that I was using django-storage to store on s3, but I took that part out so that it just stored the files locally and I am still getting the error. If anyone has any information on how to fix this please let me know. This is happening out of the box with no previous data. -
Which python framework (Flask or Django) is better for creating rest Api of software?
I am developing a api of software. Which framework is better for creating rest API of Software. FLASK or DJANGO? -
Django Retrieve all Certifications based on names of the certificate
I want to retrieve all the Prospects that have all of the certifications For example, if the certifications are A, B & C. Only all prospects that have exactly A, B & C should be returned. If they have more than ABC or less than ABC, they should be ignored. In my model.py class Certification(models.Model): name = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return "%s" % self.name class Prospect(models.Model): certification = models.ManyToManyField(Certification, blank=True, related_name="certification_prospects") How can I write a Django query to retrieve all the prospects that have strictly certification of A, B & C? -
passing data form datatable to modal django
please i want to display data from datatable to modal bootstrap example Name | prenom | id |edit example | test | 2 |button edit button will send data to modal to display for update code button : a class="btn btn-info" role="button" data-toggle="modal" data-form="{% url 'up' id=val.id }" data-target="#myEdit" >Edit</a> Modal Code : <div class="modal fade" id="myEdit" role="dialog"> <div class="modal-dialog"> <form class="well contact-form" method="post" action="{% url 'up'}"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <label for="usr">Name:</label> <input type="text" class="form-control" required="" name="uss" value="{{ instance.name }}" id="uss"> <label for="pwd">Password:</label> <input type="password" class="form-control" required="" value="{{ instance.sname }}" name="pwd" id="pwd" > </div> <div class="modal-footer"> <button type="submit" class="btn btn-default">Valider</button> <button value="" type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </form> </div> </div> views.py def posts_edit(request , id = None): instance = get_object_or_404(namemodel , id=id) context={ 'instance':instance } return redner (request, '/ges/sortie/' , context) i want to display two values Name and prenom in modal the data show it from database . I think the best solution with ajax -
How to use normal user(Models) in machina
I have created model of instructor (for project like cousera and udacity where instructor uploads video for student) with name,uname,email,password,pic for my project and i have done code for session and all that stuff for it.Now i want to add forums in it so, i tried to use django-machina but then i came to know that machina forums can only be used by Superuser or Staff user and i have seperate model for instructor what should i do?(How can i create staff user from that model) Models.py for instructor class instructor(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) uname = models.CharField(max_length=30) email = models.CharField(max_length=100) password = models.CharField(max_length=20) pic = models.FileField() def __str__(self): return self.email -
Django functional testing database results after calling view
I'm writing functional tests for my Django views using django.test.Client to simulate HTTP requests (this is much faster than using LiveServerTestCase + Selenium, and I am only testing my Django views in these tests, not the associated JavaScript code). I have a view that bulk-creates a number of objects all at once and I want to verify that the correct number of objects was, in fact, created. Testing by hand reveals no issues; the objects do get created and the result is correct. However, objects created by a view POSTed to by django.test.Client don't show up in querysets that are created after the view is called, even though they do show up in subsequent calls to entirely different views. How do I get querysets in tests to notice changes in the test db caused by requests issued from django.test.Client? -
Trying to Query on Login and based on email and password return First Name
I a have a SQLite Database with: first_name email password Andrew t@t.com abcde I am using this to check if there is a matching email and password: if User.userManager.filter(email = postData['email'], password = postData['password']): name = User.userManager.filter(email = postData['email'], password = postData['password']) print name.get('first_name') return "success" When I try to print first_name from the query i did above I get error 'too many values to unpack' -
Django - Form FileField error "This field is required"
I want to add Post form into my django project and I've got problem with FileFiled. Here is my code: forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = [ 'author', 'image', 'title', 'body' ] models.py class Post(models.Model): author = models.ForeignKey('auth.User') image = models.FileField(default="", blank=False, null=False) title = models.CharField(max_length=200) body = models.TextField() date = models.DateTimeField(default=timezone.now, null=True) def approved_comments(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title If it helps. I also set enctype="multipart/form-data in <form> Thanks for help. -
django rest framework user prefix in serializers
models.py address_choices = (("home":"Home"),("shop", "Shop")) class Address(models.Model): address_type = models.CharField(max_length=128, choices=address_choices) location = models.CharField(max_length=128) forms.py class AddressForm(forms.ModelForm): class Meta: model = Address views.py home_address = AddressForm(prefix="shop") shop_address = AddressForm(prefix="home") can i use prefix in serializers just like that i used in forms above serializers.py class AddressSerializers(serializers.ModelSerializer): class Meta: model = Address views.py home_serializer = AddressSerializers(prefix="home") shop_serializer = AddressSerializers(prefix="shop") -
Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt'
I don't know what happened but all of the sudden i am getting this error: Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': cannot import name 'flatatt' any ideas? -
Circular Dependency Error in Django
Having an issue when running makemigrations/migrate with my Django project. Getting this error: CircularDependencyError(", ".join("%s.%s" % n for n in cycle)) django.db.migrations.exceptions.CircularDependencyError: accounts.0001_initial, projects.0001_initial I have two apps---one called Accounts and another called Projects for my Accounts app, here is the model: class UserManager(BaseUserManager): def create_user(self, email, username=None, password=None): if not email: raise ValueError("Users must have an email address") if not username: username = email.split('@')[0] user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save() return user def create_superuser(self, email, username, password): user = self.create_user( email, username, password, ) user.is_staff = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True, default='') date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return "@{}".format(self.username) def get_short_name(self): return self.username def get_long_name(self): return "@{} ({})".format(self.username, self.email) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) first_name = models.CharField(max_length=40, default='', blank=True) last_name = models.CharField(max_length=40, default='', blank=True) bio = models.TextField(blank=True, default='') avatar = models.ImageField('Avatar picture', upload_to=avatar_upload_path, null=True, blank=True) skills = models.ManyToManyField(Skill) def __str__(self): return self.user.username @property def get_avatar_url(self): if self.avatar: return '/media/{}'.format(self.avatar) return 'http://www.gravatar.com/avatar/{}?s=128&d=identicon'.format( '94d093eda664addd6e450d7e9881bcad' ) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) and for my Projects app here is … -
Beginner to Intermediate projects in Python
Can anyone add me to their projects so I could gain some much needed Python coding experience? It could be an Open Source Project or even Closed Source projects. It would be nice to have a project where I could actively engage in with people with greater experience who could answer my questions and point me in the right direction. I like challenges so, the more obscure the project for me the better. Cheers. -
NOT NULL constraint failed: news_comment.post_id
I bounced Into this error. My Models.py file is class Post(models.Model): user = models.ForeignKey(User,related_name='posts') created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('news:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta(): ordering = ['-created_at'] class Comment(models.Model): post = models.ForeignKey('news.Post',related_name='comments') aurthor = models.CharField(blank=False, max_length=100) comment = models.TextField(blank=True) created_date = models.DateTimeField(auto_now = True) comment_html = models.TextField(editable = False) def save(self,*args,**kwargs): self.comment_html = misaka.html(self.comment) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('news:single',kwargs={'username':self.user.username,'pk':self.pk}) def __str__(self): return self.comment and My Views.py file is class CommentCreateView(LoginRequiredMixin,generic.CreateView): model = models.Comment fields = ('comment',) login_url = "/users/login" def form_valid(self,form,*args,**kwargs): self.object = form.save(commit = False) self.object.aurthor = self.request.user #self.object.post_id = self.kwargs['pk'] #print(self.request,self.kwargs['pk']) self.object.save() return super().form_valid(form) And The error I get is IntegrityError at /posts/4/comment/ NOT NULL constraint failed: news_comment.post_id Request Method: POST Request URL: http://localhost:8000/posts/4/comment/ Django Version: 1.11.3 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: news_comment.post_id Exception Location: C:\Users\Sahil\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 328 Python Executable: C:\Users\Sahil\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.0 Python Path: ['C:\\Users\\Sahil\\Documents\\GitHub\\news-for-good\\my_app', 'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip', 'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Sahil\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages'] Server time: Tue, 25 Jul 2017 16:21:26 +0000 Can Anyone Please Tell What the error is. If You need rest of the code This My Github Repo Thanks in Advance... Thank You :) -
The included urlconf module does not appear to have any patterns in it
I have this code for my urls.py inside the blog file, which is accessed easily by the urls.py in the mysite folder. from django.conf.urls import url, include from blog import views from django.views.generic import ListView from blog.models import Post urlpatters = [ url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("date"),template_name="blog/base.html")), ] When I try to access the /blog/ file, which should lead to the blog/base.html file, it gives the following error: The included urlconf module 'blog.urls' from '/mysite/blog/urls.py' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Any help would be highly appreciated! -
How should i call class based generic view in function view
i want to call class based index view in function view i render the index template in login function view but when i add a extra context in index template which i do from function views ' it only render's extra context not the one which is already rendered by class based index view. so i thought if i could call class based index view from function so that i add extra context to class based view and render it at the same time. in short word's i want to add extra context from function view and render it. -
Update django template after object creation
I have a model package, and a table in the template that displays all the package instances, I want that table to be updated whenever new package instance is created without refreshing the page, after researches I found that ajax is the solution, also I have have read about django signal post_save, how can I send the post_save signal to ajax in order to update the template ? thank you -
Django template not getting view data
Im trying to make my own app called Services, I have been following the Django tutorial on how to make your own app. I am making this app in Django CMS, I essentially want this app to contain templates that I can then insert into pages of the CMS via the includes tag. I have made my models, views, urls and template. But the template isn't receiving any data from the view. I am able to create new service objects in the backend so I know my model is working how I want and I'm not getting a template error when including it. Here are my models, views, URL file and template. I suspect it is either something to do with how I setup my view or how I'm pulling my view in the URLs file. Currently the only output I get in the template is "No Services Available" which it is set to output when there is no service_list from the view. models.py from django.db import models from djangocms_text_ckeditor.fields import HTMLField import filer.fields.image from django_extensions.db.fields import AutoSlugField from colorfield.fields import ColorField class Service(models.Model): title = models.CharField(max_length=200,default="") slug = AutoSlugField(max_length=50, populate_from='title') color = ColorField(default='#FFFFFF') tab_content = HTMLField(blank=True,help_text='Describe the service you … -
Empty cleaned_data dict when using custom dictionary made of request.POST for Django formset
I get data from POST request. I want to make some changes with this data and then pass it to formset. This is my function: def add_report(request, project): if request.method == 'POST': data = dict(copy.deepcopy(request.POST)) del data['media_url'], data['save_reports'] data['document_type'] = map(lambda x, y: x or y, data['document_type'], data['document_type_other']) data['paid_at'] = zip(data['day'], data['month'], data['date-year']) data['paid_at'] = map(lambda x: get_paid_at_date(x), data['paid_at']) del data['document_type_other'], data['day'], data['month'], data['date-year'] qdict = QueryDict('', mutable=True) qdict.update(data) max_num = len(request.POST['description']) media = request.POST.get('report_file') qdict['form-TOTAL_FORMS'] = max_num qdict['form-INITIAL_FORMS'] = u'0' qdict['form-MAX_NUM_FORMS'] = u'' ReportFormset = formset_factory(form=DocumentCreateForm) formset = ReportFormset(qdict) for form_number, form in enumerate(formset): if form.is_valid(): print ("form.cleaned_data", form.cleaned_data) # After I want to do something with the fields and save the object The form is valid but cleaned_data is an empty dictionary. This is my DocumentCreateForm: class DocumentCreateForm(forms.ModelForm): document_type = forms.ChoiceField(widget=forms.Select(), choices=Document.DOCUMENT_CHOICES) report_file = forms.CharField(required=False, widget=forms.HiddenInput) class Meta: model = Document fields = ('amount', 'paid_at', 'description', 'document_type',) def clean_document_type(self): document_type = self.cleaned_data.get('document_type') if document_type: return document_type raise forms.ValidationError("This field is required", code='required') Do you have any idea what am I doing wrong and how can I fix this? Thanks a lot in advance! P.S. I've found some similar questions but they didn't help. -
http get request from ionic 3 to django
i have i ionic 3 app in my dev environment and i want to get url from my django (both run locally) i get error on my ionic get method: XMLHttpRequest cannot load http://127.0.0.1:8001/api/account/check/123456/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. my provider function in ionic getCodeResult(code:string){ return this.http.get('http://127.0.0.1:8001/api/account/check/'+code+'/') .map(res => res.json()) .map(res => res.results); }; and in page.ts CheckTheInvitationCode( code:string ){ console.log(code); this.CodeProvider.getCodeResult(code).subscribe( myresult =>{ console.log(myresult); }); } my django rest framework run on 8001 port and ionic on 8100 -
Posting data to django rest framework using javascript fetch
I'm trying to post data to my django rest framework using javascript fetch. I've already set up and liked the DRF to my model and got everything set up from the backend. I used the postman app to ensure "get", "post" etc are all working as interned. However, now I'm having problem posting data using javascript to post the data using fetch. I want to add data to my article model which has a "headline", "tag", "content", "background_image" and the user that posted the article. This is how my code looks like data = JSON.stringify({ headline: "Testing", tag: "Testing", background_image: "Testing", content: "Testing", user: 1 }) fetch( "http://127.0.0.1:8000/api/v1/articlesapi/", { method: "post", headers: {"Authorization":"Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e"}, body: data } ).then(function(response) { return response.json(); }).then(function(data) { console.log("Data is ok", data); }).catch(function(ex) { console.log("parsing failed", ex); }) However, I keep getting the error parsing failed TypeError: Failed to fetch. Does anybody know what I'm doing wrong ? -
Django update migrations from sqlalchemy to south
I've a django project which was using alembic and sql alchemy for migrations. I'd upgraded django to 1.9 which has south by default for migrations. Is there any way to switch to south for adding and removing of new fields without creating migrations for tables? I'd tried python manage.py makemigrations but it is creating migrations for tables that already exists. -
how to run manage.py on heroku with cleardb apps
I uploaded django app to heroku and than provision the cleardb add-on using these 3 commands from heroku documantation: heroku addons:create cleardb:ignite heroku config | grep CLEARDB_DATABASE_URL heroku config:set DATABASE_URL='mysql://adffdadf2341:adf4234@us-cdbr-east.cleardb.com/heroku_db?reconnect=true' it seems to be O.K and the app is running (but without database). now I try to run: $ heroku run python manage.py migrate and this is the error I get: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 327, in execute self.check() File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.5/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.5/site-packages/MySQLdb/__init__.py", line 86, in Connect return Connection(*args, **kwargs) …