Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Form object has no attribute 'user' despite passing user as kwarg?
I'm getting this error when I instantiate the TransactionForm in my view. The traceback is below. I would expect this to work because I'm passing "user" as a keyword argument when I call the Form instance, so I'm not sure what the problem is here? File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\py\portfolio-project\myportfolio\views.py" in add_transaction 122. form = TransactionForm(user = request.user) File "C:\py\portfolio-project\myportfolio\forms.py" in __init__ 36. qs_coin = Coin.objects.get(user = self.user) Exception Type: AttributeError at /myportfolio/add_transaction/ Exception Value: 'TransactionForm' object has no attribute 'user' Views.py def add_transaction(request): print(request.method) print("test1") if request.method == "GET": if request.is_ajax(): print("ajax test") data = { 'test': "test1" } form = TransactionForm(request.GET, user = request.user, coin_price = GetCoin(str(coin.coin)).price) return JsonResponse(data) form = TransactionForm(user = request.user) if request.method == "POST": print("test2") form = TransactionForm(request.POST, user = request.user) if form.is_valid(): print("test3") obj = form.save(commit = False) obj.user = request.user obj.save() return HttpResponseRedirect('/myportfolio/') else: print(form.errors) return render(request, 'myportfolio/add_transaction.html', {'form': form}) Forms.py class TransactionForm(forms.ModelForm): CHOICES = ((1, 'Buy'), (2, 'Sell'),) coin = forms.ModelChoiceField(queryset = Coin.objects.all()) buysell = forms.ChoiceField(choices = CHOICES) field_order = ['buysell', 'coin', 'amount', 'trade_price'] … -
Mix Django website and rest
I start a new website made with Django : just some forms. But, I need to add, also, some REST api urls (secure). How can I do that ? (TastPie ?, I read it's a bad idea). DRF it's a full rest api, not web... it's seems. Thanks for help Fabrice -
How can do a query in order if the input word contains a word in the database?
I know that I can use __contains to look in the database for a word that contains the String I put in the query word=ModelTester.objects.filter(word__icontains='neuro') print word neurology and in my database, I have neurology, for that reason I get neurology, but I want to do the contrary. What I mean is that I have neuro in my database, and in my query I put neurology and I get neuro, Is there a way to do that word=ModelTester.objects.filter(word='neurology') print word neuro -
Django ManyToMany Field Querying
For days now i have been looking for the simplest way to go about solving this problem . So i have models ,user , Company Model , And product Model as bellow . model .py class Company(models.Model): name=models.CharField(models.Model) user=models.ForeignKey(user,unique=True,null=True,related_name="user") follow=models.ManyToMany(user,related_name="follow",null=True) class Product(models.Model): name=models.Charfield(models.Model) company=models.ForeignKey(Company,related_name="Product",null=True) In my view def Display(request): #get all products products=Product.objects.all() #get all company objects companies=Company.objects.all() So the idea is users can follow companies and companies can post products . Assuming userA is following companyA(usA has been added to ManyToManyField in Company), When companyA post a product, the product is displayed in usA timeline. I have done research and i even came across an app called django activity streaming . It was complicated for me to integrate in to my project . Since i am just looking for something simple .I am reading django contenttype which tracks all models, but yet i have no idea how to implement it to solve my problem . Please if you have an idea on how i can solve this problem using django query set or any suggestion . I will gladly appreciate . -
Error with asynchronous request in DRF
I need to fulfill a request to two services. The code looks like this: async def post1(data): response = await aiohttp.request('post', 'http://', json=data) json_response = await response.json() response.close() return json_response async def get2(): response = await aiohttp.request('get', 'http://') json_response = await response.json() response.close() return json_response async def asynchronous(parameters): task1 = post1(parameters['data']) task2 = get2() result_list = [] for body in await asyncio.gather(task1, task2): result_list.append(body) return result_list If I run the code locally, it's OK. The code looks like this: if __name__ == "__main__": ioloop = asyncio.get_event_loop() parameters = {'data': data} result = ioloop.run_until_complete(asynchronous(parameters)) ioloop.close() print(result) I get the right result. But if I try to execute code from the DRF method, an error occurs: TypeError: object _SessionRequestContextManager can't be used in 'await' expression example code that I run: class MyViewSet(GenericAPIView): ..... def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) ...... ioloop = asyncio.get_event_loop() result = ioloop.run_until_complete(asynchronous(serializer.data)) ioloop.close() ...... return Response(serializer.data, status=status.HTTP_201_CREATED) Please, tell me what the problem may be? -
Django - Redirect to another domain from View
I'm trying to redirect from mydomain.com to google.com. There are a couple of answers on stackoverflow that asume the following is working: return HttpResponseRedirect('google.com') or return redirect('google.com') But it doesn't it. This just redirects the page to itself and appends the google.com part so it comes out like this: www.mydomain.com/google.com What throws a 404 of course.. My view now looks like the following: class MyView(TemplateView): def get(self, request, *args, **kwargs): return HttpResponseRedirect('google.com') Can anyone give me insights in what I'm doing wrong? -
Django: editing multiple existing model-entries based on a foreign key filter
Am trying some things based on the initial setup of Myfirstapp tutorial. https://docs.djangoproject.com/en/2.0/intro/tutorial01/ I've tried many different methods from other answers, but am getting errors or blank pages. So will ask a clean question. I have the follow models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text And the following urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('<int:pk>/editchoices/', views.ChoiceEditView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] I want to create a page (form, view and template page) that gives me all choice_texts of choices related to a question (based on the pk in the url) in order to edit the multiple choice_texts (and save) and possible add 1 or 2 choices. I've tried a lot of code examples for modelformset, etc. but cannot get them to work. I already have LoginRequiredMixin and @login_required working in other views to limit this functionality to only registered users (once I get it to work), but don't want to use the admin part. Working with Django version 2.0.4 -
How import the same lib to every app view in Django?
In every view in Django 1.11 I import the same lib. How can I declare it in one place to use everywhere? For example, for logging import coloredlogs, logging logger = logging.getLogger(__name__) coloredlogs.install(level='DEBUG', logger=logger) def index(request): logger.error('test') return -
Django test stuck on permissions
So, I noticed that my tests were not running and seem stuck so I ran them locally with --verbosity 3 optional argument. The log seems stuck after my last application permission creation. Running post-migrate handlers for application vehicles ... Adding permission 'Permission object (78)' System check identified no issues (0 silenced). The last part seems rather confusing - I am not calling django.setup() or run server anywhere in the code. Relevant pieces of info. I use a proxy model in authentication.models and I updated the settings accordingly. AUTH_USER_MODEL = 'authentication.User' and I have two strings for heroku db_from_env=dj_database_url.config(conn_max_age=500) and DATABASES['default'].update(db_from_env) This is only unorthodox settings. Where would I be able to locate how this issue happens and how to tackle? -
django-allauth social account error on live server
I have a django application that used django-allauth for authentication. the problem I am facing now is I used google as my social login option but when ever I am in development mode , everything works fine as specified in the docs but when I go live I get error when the continue with google button is clicked. The error I got is [xxxxxx]ERROR (EXTERNAL IP): Internal Server Error I am lost at this point because I do not receive any error while in development mode. I assume this is an error associated from the ALLOWED_HOST but I can not figure it out. Thanks in advance -
Push rejected by Heroku for the static file collection reason
When I'm trying to deploy a Django app to Heroku, encounter the identical problem as python - Collectstatic error while deploying Django app to Heroku - Stack Overflow it starts to build, download and installs everything, but that's what I get when it comes to collecting static files: $ git push heroku master Counting objects: 5375, done. Total 5375 (delta 1092), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: ... remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to fierce-cove-94300. remote: To https://git.heroku.com/fierce-cove-94300.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/fierce-cove-94300.git' I tried all its answers, but not helps. Additional I tried Django and Static Assets | Heroku Dev Center to configure … -
Force django querystring in url
Say you have a url like this: /cats/?filter=kittens Is it possible to build a django url pattern that forces the use of the querystring? Currently I have: url(r'^/cats/$', views.CatsListView.as_view(), name='cats') Now I want to add the querystring and get a different view, something like this: url(r'^/cats/?filter=(?P<filter>.+?)$', views.CatsFilteredListView.as_view(), name='cats-filtered') Is it possible to do something like this and still keep the querystring in the GET parameter of the request? Remember that this is just a testcase, I, and you should too, know that filtering like probably this isn't the way to go.. -
Represent model graphically
Java environments like BuleJ (https://www.bluej.org/) allow to visually see your objects and their properties and actions available on them: Let's say I have a model Student in my application: class Student(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) address = models.CharField(max_length=50, blank=True, null = True, ) Is there a way to represent objects of this model in such a graphical way? To see its attributes and methods, perhaps invoke them and so on? Can we do it in Django/DRF? To me it seems like a view on this object that all stakeholders can understand. -
ValueError: invalid literal for int() with base 10: 'rakash@tech.com'
This is the line in which i am getting error: User.objects.filter(id__in=Setupuser.share_KB_with.through.objects. values_list("user_id").filter(setupuser_id=Setupuser.objects. values_list("email_id",flat=True).filter(email_id="rakash@tech.com") [0])) There are two tables "User" and "Setupuser".I want to retrieve some objects from User by applying filters on setupuser. How can i resolve error -
Custom query for Django Rest Framework
The basic DRF setup for my little Podcast Backend is working quite well: router.register(r'episodes', views.EpisodeViewSet) urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/', include(router.urls)), ] in urls.py and class EpisodeSerializer(serializers.ModelSerializer): # show = ShowSerializer() class Meta: model = Episode depth = 1 class EpisodeDetailSerializer(serializers.ModelSerializer): chapters = ChapterMarkSerializer(source='chaptermark_set', many=True) media = MediaClipSerializer(source='mediaclip_set', many=True) show = ShowSerializer() class Meta: model = Episode depth = 1 in serializers.py as well as class EpisodeViewSet(viewsets.ModelViewSet): queryset = Episode.objects.all().order_by('-published_at') def get_serializer_class(self): if self.action == 'retrieve': return EpisodeDetailSerializer return EpisodeSerializer work well for creating a full episode list (I chopped down the classes a bit, they do additionally contain some field filters but this is not related) and also for a hyperlinked Detail view for each episode. Additionally to that I need the possibility to query episodes by other fields. Especially a "number" field and the "show_id" I can't seem to get behind how this is done in DRF. I already tried adding def get_queryset() to the EpisodeDetailSerializer Class but that didn't work. So what I'm looking for is to process something like /api/episodes/?show_id=2&number=24 to deliver episode details instead of the default /api/episodes/123 any help is appreciated. -
Django: Unable to connect to Microsoft SQL Server
I am unable to connect to the MS SQL server using Django (Version- 1.11.3) Here is the error, I seem to be getting: django.db.utils.OperationalError: ('08001', u'[08001] [unixODBC][FreeTDS][SQL Server]Unable to connect to data source (0) (SQLDriverConnect)') This is the odbcinst.ini file: [FreeTDS] Description=TDS driver (Sybase/MS SQL) Driver=/usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup=/usr/lib/x86_64-linux-gnu/odbc/libtdsS.so CPTimeout= CPReuse= UsageCount=2 This is the django settings.py snippet: DATABASES = { 'mssql': { 'ENGINE':'sql_server.pyodbc', 'NAME': '<NAME>', 'USER': '<USER>', 'PASSWORD':'<password>', 'HOST':'<host-id>', 'OPTIONS': { 'driver':'FreeTDS' } } } -
Django REST how to set throttle period to allow one request in 10 minutes?
Documentation says that period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day'). I am curious have can I set period to something like 1/10min? -
python.exe - The FastCGI process exited unexpectedly w/ Django 2.1, IIS 7.5, Python 3.6.5
I know there are some similar questions/articles/discussions/threads out there about this, but I've read them all, and I've seemed to miss the mark still. So, please, bear with me. I'm trying to get a Django 2.1 project with Python 3.6.5 and wfastcgi 3.0.0 hosted on a server running IIS 7.5. My error is displayed when I attempt to go to my page in internet explorer: HTTP Error 500.0 - Internal Server Error C:/path/to/python.exe - The FastCGI process exited unexpectedly Module FastCgiModule Notification ExecuteRequestHandler Error Code 0x000000ff Some articles/threads mention only Python 3.4 being compatible with wfastcgi.py, but those are older articles (1-2 years old) and I can't imagine that years later this would still be an issue. I would really prefer to solve this while keeping my version of Python current. What I've done: Successfully ran and accessed the page from the python.exe manage.py runserver 8080 command wfastcgi-enable has been executed successfully Created a Module Mapping under Handler Mappings with * for the path, FastCgiModule as the Module, and the Executable string is: C:\path\to\python.exe|C:\path\to\wfastcgi.py Verified that FastCgiModule is appearing under Modules Updated settings.py: ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'actual.server.address.net'] Fixes I've tried Changing my site's Identity under Application Pools from ApplicationPoolIdentity … -
pytest-django could not find a Django project
Trying to configure pytest with django, the project already has a lot of test not written with pytest (written with unittest) but I am trying to get them run with pytest so I can write pytest tests and get it work with old tests. I know pytest-django checks for the manage.py file in the root dir of a django project but this project the manage.py file is not in the root dir so I guess that's why the error below is thrown when I run pytest however running pytest and supplying a particular file works. How do I specify where manage.py is? As I can't find this in the documentation pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up. -
Quick and dirty way to access files external to Django?
I'm working on a demo for a program that creates some files on its own directory. This demo will be shown to someone physically far, via VPN, so I made a simple django project just to receive an input, call some scripts and display the output - the generated file. However, I don't have permission to open the file to display it since it's on a directory outside of the django project (the result is a permission denied error). I'm aware it's not good practice or even safe for a web server to have access to files outside of its directories, but since this will run in a closed environment for a short amount of time only, is there a workaround? -
Django: generate python code from command line
Is here a way to write a Django command to generate code automatically? In my case: every time I create a new model I must create the following stuff too: Create Administration classes in admin.py Create service functions related to this model. Create a factory using FactoryBoy. Create test classes. It would be nice if there was a command that generates this stuff automatically. Not everything, of course, but just the basic, the definition. Is there something like this today in Django? Or is there a way I can write Django commands to generate code? -
Insert an HTML form with javascript
I have a problem with my program. When I click on my button I want to make my form appear. But here is the error I get when I click on my button: "SyntaxError: unterminated string literal". Can you help me please ? Here is my code Js: $(document).ready(function(){ $('#modifier').click(function(){ $('#modification').append('{{form}}'); $('#test').show() }); }); The '{{form}}' is django which is the equivalent of: '<tr><th><label for="id_commentaire">Commentaire:</label></th><td><textarea name="commentaire" required maxlength="200" rows="10" cols="40" id="id_commentaire"> </textarea></td></tr>' I do not understand where this error comes from. Thank you in advance. Yours sincerely, -
Django form not being rendered with custom validator errors
How do you get a form to render with error messages from a custom validator? def today_or_future(date): if date < dt.date.today(): raise forms.ValidationError('Date cannot be in the past.') return date class DateForm(forms.Form): date = forms.DateField(required=True, validators=[today_or_future]) class MyView(UpdateView): def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['form'] = self.form_class(self.request.POST or None, instance=self.object) return context def form_valid(self, form): context = self.get_context_data() form = context['form'] if form.is_valid(): order = form.save() return redirect(self.get_success_url()) return render(self.request, self.template_name, context) Rendered in the template using {{ form }}, on submit with a past date the page reloads but there are no field error messages included. -
Postgresql database not updating after migration Django 2.0
I am working on a Django REST API backend using Postgresql and Psycopg2, but the database does not update its tables when I run python3 manage.py migrate. I tried to remove past migration files because of an int() argument problem and it was solved after the deletion but now the database does not update at all even though I have successfully made migrations and migrated without any errors. I tried to change the database to a new one, when done so: I get this error after running migrate: django.db.utils.IntegrityError: null value in column "name" violates not-null constraint DETAIL: Failing row contains (11, null, sessions, session). -
How to filter data and pages for Users logged?
my problem is. I have a application with systems login. But I want that User1 just see data added by User1, and User2 see data added by User2. That view, in a generic.ListView I got filter in my views using: def get_queryset(self): return Tarefa.objects.filter(user=self.request.user) But if I logged by User1 and access a URL with some information by User2, I can see that information, like generic.DetailView, UpdateView, and DeleteView. I need to know how User1 does not see this information from User2, and on the contrary. Thanks.