Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assertion error: False is not true
This is my code in testcases by this I am getting False is not true. self.assertTrue(file_equals_filefield( ("rule_regex/test_data/blank_test_na1.csv"), job.processed_file)) -
Cannot assign "42": "Event.user_id" must be a "User" instance
I have checked all the solutions related to my question but no one worked, i have an event table in which i am assigning the id of user. Event Model is class Event(models.Model): user_id=models.ForeignKey(User, on_delete=models.CASCADE) event_auth_id=models.CharField(null=True, max_length=225) event_title=models.CharField(max_length=225) ticket_title=models.CharField(max_length=225) category=models.CharField(max_length=50) event_summary=models.TextField() event_information=models.TextField() restriction=models.CharField(max_length=50, default='No Restriction') artist_image=models.CharField(null=True, max_length=50) event_poster=models.CharField(null=True, max_length=50) notification_email=models.CharField(null=True, max_length=50) notification_frequency=models.CharField(null=True, max_length=15) name_on_ticket=models.CharField(max_length=225) event_tnc=models.TextField() current_step=models.IntegerField(null=True) event_status=models.BooleanField(default=True) created=models.DateTimeField(auto_now=True) modified=models.DateTimeField(auto_now_add=True) I am assigning the logged in user id from view def create_new_event(request, steps): if request.method == 'POST': if(steps=="step_1"): stepFirstForm = CreateEventStepFirstForm(request.POST) if stepFirstForm.is_valid(): eventStepFirst = Event( user_id = request.user.id, event_auth_id = uuid4(), event_title = request.POST['event_title'], ticket_title = request.POST['ticket_title'], category = request.POST['categories'], event_summary = request.POST['event_summary'], event_information = request.POST['event_information'], restriction = request.POST['restrictions'], notification_email = request.POST['notification_email'], notification_frequency = request.POST['email_frequency'] ) But its giving me error Cannot assign "42": "Event.user_id" must be a "User" instance. -
Django writes to DB before each GET http request.
I am using django via scalearc for the database, ScaleArc establishes connection to respective database depending on read/write Query. When I do GET call django is sending following query to database due to that its always connecting to Write database. SET NAMES utf8 set autocommit=0 set autocommit=1 SET SQL_AUTO_IS_NULL = 0 How do I avoid these calls in Django? -
Django API query optimization
I have a Django application wherein I need to do a POST operation on an API. As the time taken for POST operation is high, I was reading this nice material to gain more insight into the situation. I have a question here. I am using select_related and prefetch_related in my code to reduce the number of database trips, but I see that the queries get more and more complex with things like JOIN etc. So, I wanted to know the following: Which is better with respect to time?? A very complex SQL query for a single database trip or 2 simple SQL queries for 2 database trips. -
Django where in queryset with comma separated slug in url
I have a Post Model models.py class Category(models.Model): title = models.CharField(max_length=100,null=True,blank=False) slug = models.SlugField(max_length=150,null=True,blank=False) class Post(models.Model): title = models.CharField(max_length=256,null=True,blank=False) categories = models.ManyToManyField(Category) So in view I need to query all the posts with specific category for example This is the url http://example.com/?category=slug1,slug2 views.py class PostList(TemplateView): ... def get(self,request,*args,**kwargs): categories = request.GET.get('category') post_list = Post.objects().filter(categories__in=categories) ... The above view throws error as invalid literal for int() with base 10: ',' because of passing comma separated strings, but how can I achieve this? -
Django display a photo from a model
I've tried several of methods on how to retrieve an image from a model with no luck, this is where I'm at so far. I'd like to have the image show and when the user clicks on it it opens a modal showing a projects detail. models.py class Project(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) client = models.CharField(max_length=200) date = models.DateField(timezone.now()) service = models.CharField(max_length=200) info = models.TextField() photo = models.ImageField(upload_to='ports/static/img/', default='ports/static/img/port_photo.png', height_field='photo_height', width_field='photo_width',) photo_height = models.PositiveIntegerField(blank=True, default=900) photo_width = models.PositiveIntegerField(blank=True, default=650) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) index.html <section id="portfolio"> {% for project in projects %} <div class="row"> <div class="col-lg-12 text-center"> <h2>Portfolio</h2> <hr class="star-primary"> </div> </div> <div class="row"> <div class="col-sm-4 portfolio-item"> <a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"> <div class="caption"> <div class="caption-content"> <i class="fa fa-search-plus fa-3x"></i> </div> </div> <img src="{{ projects.photo.url }}" class="img-responsive" alt=""> </a> </div> </div> </div> {% endfor %} </section> views.py from django.shortcuts import render from .forms import ContactForm from django.utils import timezone from .models import Project # Create your views here. def index(request): form_class = ContactForm projects = Project.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'ports/index.html', {'form': form_class, 'projects': projects}) -
How to use Many2many field in analytic view odoo
I want to tag_ids field in statistical view. I am using this type of query SELECT min(pol.id) AS id, po.date_order::date AS date, pol.product_id AS product_id, pp.product_tmpl_id AS product_tmpl_id, po.company_id AS company_id, pt.product_brand_id AS product_brand_id, pt.categ_id AS categ_id, array_agg(p_tag.name) AS tag_id, 'Point of Sale' AS origin, sum(pol.qty) AS qty FROM pos_order_line pol LEFT JOIN pos_order po ON po.id = pol.order_id LEFT JOIN product_product pp ON pp.id = pol.product_id LEFT JOIN product_template pt ON pt.id = pp.product_tmpl_id LEFT JOIN product_product_tag_rel pp_rel ON pp_rel.product_id=pp.product_tmpl_id LEFT JOIN product_tag p_tag ON p_tag.id=pp_rel.tag_id LEFT JOIN product_brand pb ON pb.id=pt.product_brand_id WHERE po.state IN ('paid', 'done', 'invoiced') GROUP BY po.date_order, pol.product_id, pp.product_tmpl_id, po.company_id,pt.product_brand_id,pt.categ_id Here I don't know how can i pass tag_id value to many2many field and set its filter? this query giving me result as i want, Buti Don't know how to display it on statistical view (analytic view) Someone please tell me about it, I'll be very thankful -
I was doing my first django project,but it said no module named 'polls'
i followed the django official document,and i am doing the poll app. [enter image description here][1] [1]: https://i.stack.imgur.com/6yUit.png this is my project directory [enter image description here][1] [1]: https://i.stack.imgur.com/SmtVs.png and this is url.py in the mysite package ,but it says No module named 'polls' when i run it,how can i solve it? whis is my first time to use it and my english is really poor. Thank you in advance! my python is 3.6,my django is 1.10.2, -
How to convert nested OrderedDict to Object
I have dictionary like this data = OrderedDict([('name', 'NewIsland'), ('Residents', [OrderedDict([('name', 'paul'), ('age', '23')])])]) and I want to convert it to class object. Here are my django models. class Country(models.Model): name = models.CharField(max_length=20) class Residents(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() country = models.ForeignKey('Country', related_name='residents') When I code like this result = Country(**data) I got exception 'residents' is an invalid keyword argument for this function How can I convert it to class object that I can access residents with result.residents[idx]? -
Django REST API custom methods for generic views
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework. We are creating new user. My view method is following: class NewUser(generics.CreateAPIView): model = User permission_classes = [permissions.AllowAny] serializer_class = NewUserSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) token, created = Token.objects.get_or_create(user=serializer.instance) return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers) When someone wants to create new user via POST request if user name has't been taken yet, then API return 201 status code and token in JSON, if user name already taken it returns 400 status and error message in JSON. MY colleague request me to change status message to 200 when he tries to create username with name that already exist. He says that he can't consume the ERROR response. His code looks like: $http.post(url,{ username:$scope.tel, password:$scope.passwd }).success(function(data){ alert(data); $ionicLoading.hide(); console.log(data); }) Question: 1) Should I tweak my API to send 200 status instead of more logical 400 for 'user already register' error? I tried to change my code, But i couldn't find the method to override in CreateAPIView/ModelSerializer of DRF. I ended up rewriting my view class to method: … -
Create a separate app to combine the models from multiple apps?
I have multiple apps in my project which contain models which are related to each other. For example: I have a crawler app which contains text which is crawled. (app 1) I have an images app which contains images which have been uploaded. (app 2) I have a color palettes app which generates color palettes based on images. (app 3) The problem is all of the data is related. For example, the crawled text (app 1) has a 1-to-1 relationship with an uploaded image (app 2), and a color palette (app 3) also has a 1-to-1 relationship with an uploaded image (app 2). So right now my data is scattered across models in multiple apps. Therefore I am thinking of creating a new app called "Data" whose job is just to contain the models from app 1, app 2 and app 3. Is this considered a bad practice or does it make sense in my situation? Thank you. -
In Django, how to click button to call a view and then reload page
In Django, how to click button on page without passing any value to view.py and then reloading current page? I have a button in the HTML: <button type="button" class="btn btn-primary" id="refresh">refresh page</button> I want to call a view in view.py, in which new HTML will be returned: @csrf_exempt def topology_show_refresh(request): '''topology refresh''' plan = {...} ... return render(request, 'topology_show.html', {'plan': plan}) The plan dictionary will be used in the new page. In my way, I use ajax to jump to this view, but I have no idea how to handle the return. $(function(){ $("#refresh").click(function(event){ url = 'refresh/'; $.post(url, {}, function(ret){ //do something window.location.reload(); //how to handle the return page from view.py }); }); }); -
Django Rest Framework - Return no values if filter is not selected
I have a fairly simple view where, if no filters are selected, I want the api call to return nothing. Currently the base api url returns everything and the filters successfully limit the return which is half way to what I want. so this would return values: http://localhost:8000/api/v1/widgets/?name=abc&list=def this would return no results: http://localhost:8000/api/v1/widgets/ Here is my current view: class WidgetViewSet(EncryptedLookupGenericViewSet, viewsets.ModelViewSet, ): queryset = Widget.objects.all() serializer_class = WidgetSerializer permission_classes=[IsAuthenticated, ] lookup_field = 'id' filter_class = WidgetFilter def get_queryset(self): return super(WidgetViewSet, self).get_queryset().filter(list__owner=self.request.user) -
Error when creating superuser in Django
I'm very new to Python and even newer to Django. I'm using Visual Studio and trying to create a new Django Web Project and receiving the error below: Executing manage.py createsuperuser Traceback (most recent call last): File "c:\users\gweathersby\documents\Python Experiments\SRC Project Mngr\manage.py", line 17, in execute_from_command_line(sys.argv) File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\site-packages\django\core\management__init__.py", line 316, in execute settings.INSTALLED_APPS File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\site-packages\django\conf__init__.py", line 53, in getattr self._setup(name) File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\site-packages\django\conf__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\site-packages\django\conf__init__.py", line 97, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\gweathersby\AppData\Local\Continuum\Anaconda2\lib\importlib__init__.py", line 37, in import_module import(name) ImportError: No module named SRC Project Mngr.settings The Python REPL process has exited I've done some searching online and have seen that other folks have had this issue, but to be honest, none of the solutions make sense to me because I'm so new. Could someone advise with simple steps as to how to remedy? -
What to import in querying with dates() in Django?
Entry.objects.dates('pub_date', 'month') I would like to test the code above from the documentation Documentation, but I can't figure/find out what to import. I can query using filters but this returns a name 'dates' is not defined. I imported from django.utils import dates but it returns TypeError: 'module' object is not callable. Thank you -
features.py Cause ERROR "check_array ValueError: Found array with 0 sample(s)"
I need to setup retrieval-2016-deepvision. I have successfully run the following: - database (oxford) - database (paris) - data/models/fetch_models.sh - read_data.py But when I run features.py I have the following error: Traceback (most recent call last): File "features.py", line 119, in <module> learn_transform(params,feats) File "features.py", line 23, in learn_transform feats = normalize(feats) File "/usr/lib/python2.7/dist-packages/sklearn/preprocessing/data.py", line 1280, in normalize estimator='the normalize function', dtype=FLOAT_DTYPES) File "/usr/lib/python2.7/dist-packages/sklearn/utils/validation.py", line 407, in check_array context)) ValueError: Found array with 0 sample(s) (shape=(0, 512)) while a minimum of 1 is required by the normalize function. -
Django general and app templates
I want to customize my Django project, I will have a dashboard app and a home site app (you can enter from this home site to the dashboard with a URL). I want to save a template for the HTML and css so both apps can use them. I followed this tutorial on django official site, but I think I missed a setup because. This is the error: Not Found: /dashboard/css/style.css. At this point, my django project is structured this way, I think that I will add another app (module) to serve the home page: mysite/ manage.py mysite/ __init__.py settings.py urls.py wsgi.py dashboard/ __init__.py admin.py migrations/ __init__.py 0001_initial.py models.py static/ templates/ polls/ index.html tests.py urls.py views.py templates/ css/ style.css -
process to load database in django project
what is the correct process to move a django cms_project to the server? I create the database from my project like this ./manage.py dumpdata > resource/ddbb/20160817_db.json I save inside the project in resource file I move the entire project to the server and after that I execute that command python manage.py loaddata resource/ddbb/20160817_db.json But I obtain this error File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib/python2.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named djangocms_admin_style any idea how to solvent? Thanks in advances -
Filter django admin according to polymorphic
Trying to get django-polymorphic to work in the admin. I have a number of ChildModels inheriting from BaseModel, but clicking on any of them in the Django admin all lead to a listing of all BaseModel objects, which is useless to me. I've tried both redefining the queryset and including the list_filter as the documentation (outdated, I've learned) suggests, but neither seems to have any effect. class BaseModelChildAdmin(PolymorphicChildModelAdmin): base_model = BaseModel show_in_index = False form = BaseModelForm class ChildModelAdmin(BaseModelChildAdmin): exclude = ('asset_url', 'asset_file') base_model = ChildModel show_in_index = True def queryset(self, request): qs = ChildModel.objects.all() return qs class BaseModelAdmin(PolymorphicParentModelAdmin): base_model = BaseModel child_models = [(ChildModel, ChildModelAdmin)] list_filter = (PolymorphicChildModelFilter,) -
How to set up a new database in Postgresql
I'm attempting to work out how to set up PostgreSQL for my django project and am struggling with using the shell to create the database (on windows). In lots of tutorials I've seen the commands to input but they don't seem to work with what the shell I have accepts. When I load the shell it gives me: Server [localhost]: Then whatever I input it follows with, Database [postgres]: Port [5432]: Username [postgres]: Password for user postgres: Then exits. It seems as if it is trying to connect to a database but I can't work out how to create a new one that I will be able to connect my django app to. Any advice on how I'm using PostgreSQL wrong and what to do to solve this would be much appreciated. Thanks! -
Redis telling me "Failed opening .rdb for saving: Permission denied"
I'm running Redis server 2.8.17 on a Debian server 8.5. I'm using Redis as a session store for a Django 1.8.4 application. I haven't changed the software configuration on my server for a couple of months and everything was working just fine until a week ago when Django began raising the following error: MISCONF Redis is configured to save RDB snapshots but is currently not able to persist to disk. Commands that may modify the data set are disabled. Please check Redis logs for details... I checked the redis log and saw this happening about once a second: 1 changes in 900 seconds. Saving... Background saving started by pid 22213 Failed opening .rdb for saving: Permission denied Background saving error I've read these two SO questions 1, 2 but they haven't helped me find the problem. ps shows that user "redis" is running the server: redis 26769 ... /usr/bin/redis-server *.6379 I checked my config file for the redis file name and path: grep ^dir /etc/redis/redis.conf => dir /var/lib/redisredis/redis.conf grep ^dbfilename /etc => dbfilename dump.rdb The permissons on /var/lib/redis are 755 and it's owned by redis:redis. The permissons on /var/lib/redis/dump.rdb are 644 and it's owned by redis:redis too. I also ran … -
How to add custom search_field Django admin
I want to create a new search field box with my on filters, and add to the django admin: admin.py from django.contrib import admin from .models import Aluno, Data from .relatorio import salvarRelatorio class AdminAluno(admin.ModelAdmin): list_editable = ['is_active',] list_display = ['first_name', 'matricula', 'is_active','cpf', 'cargo', 'date_joined','image_tag'] ##mostra esses campos search_fields = ['first_name', 'matricula'] ## campos q pesquise exclude = ['password'] class AdminData(admin.ModelAdmin): list_display = ['aluno__first_name','data_entrada', 'hora_entrada', 'hora_saida', 'descricao'] ##mostra esses campos search_fields = ['aluno__first_name', 'matricula', 'data_entrada'] ## campos q pesquise actions = [salvarRelatorio] admin.site.register(Aluno, AdminAluno) admin.site.register(Data, AdminData) I want to create a extra search field to filter with data_entrada__gte and data_entrada__lte. -
graphene django relay: Relay transform error
Being very new to GraphQL, I have a graphene django implementation of a server with two models, following rather closely the graphene docs' example. In graphiql, I can do this, and get a result back. Following another relay tutorial, I'm intending to render the result of this query on screen. My attempt looks like this: class Note extends Component { render() { return( <div> {this.props.store.title} </div> ) } } Note = Relay.createContainer(Note, { fragments: { store: () => Relay.QL` fragment on Query { note(id: "Tm90ZU5vZGU6MQ==") { id title } } ` } }); class NoteRoute extends Relay.Route { static routeName = 'NoteRoute'; static queries = { store: Component => { return Relay.QL` query { ${Component.getFragment('store')} } `}, }; } My browser's console shows the following error: Uncaught Error: Relay transform error ``There are 0 fields supplied to the query named `Index`, but queries must have exactly one field.`` in file `/Users/.../src/index.js`. Try updating your GraphQL schema if an argument/field/type was recently added. I've been trying to figure it out on my own with limited success. Can someone point me in the right direction? -
Fake Django migration (in the migration itself)
I have a coworker who did some magic while changing a managed manytomany field to one using a custom model. This is great! Unfortunately, when running ./manage.py makemigrations we now get a migration autogenerated that we don't want. The migrations without this autogenerated one work well and it seems that the migration script is confused. Since this code is already deployed on production and on many environments, I want to generate the migration, mark it as fake permanently and then nobody will ever run that migration (but the makemigration script will be happy). Is there any way to do this or am I stuck running ./manage.py migrate <migration> --fake on all the environments (and all new ones) I am using Django 1.10 on Python 3.5 with MySQL 5.6. -
Make non-published "petitions" inaccessible by url
I have a petition model with a BooleanField called "published" and by default it is set to false. class Petition(models.Model): # Added on creation target = models.CharField(max_length=50, null=True) title = models.CharField(max_length=300) body = models.TextField() goal = models.IntegerField() # Added after form creation letter = models.TextField(null=True) published = models.BooleanField(default=False) featured_image = models.CharField(max_length=250, null=True) end_date = models.DateTimeField(null=True) # Not User Submitted is_victory = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.title def get_absolute_url(self): return reverse("petitions:detail", kwargs={"id": self.id}) On the petition index page I know I can filter by only published petitions and non-published petitions will not show. But right now non-published petitions are still accessible if you entered the url path in manually. How can I get it to show a "petition doesn't exist" message for petitions that have not been published.