Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template extending in Javascript
I want to use template extending in Vanilla Js apps , so that I can create an app shell and then extend the contents, just like the one we do in Python Django, please suggest any frameworks/library in Js to do basic routing and template extending to keep the project organised. -
Subdomain dynamics for blog at nginx and django
I've written a blog service by django Which users can create for the blog itself Now the url is as follows. http://example.com/USER I want to use the subdomain. As follows http://USER.example.com Show your blog. Without redirecting to the primary url But I do not know how to do nginx. thanks -
how to routing auto in django with as few code as possible
l am a novice with django. l use PHP with CI. In CI, it can route automatically. and l don't need to set too much thing In tutorial, it created a view.py and defined a function hello, then defined a rule in urls.py like url(r'^$', view.hello), is there any other way can auto route url like following set a rule like url(r'^hello/(*)$', view.*) then define function in view.py def hello1(request): ... def hello2(request): ... then access url 127.0.0.1:8080/hello/hello1 127.0.0.1:8080/hello/hello2 -
Call ViewSet method from another view
I have a mobile app with a Django REST framework API and I have a lot of ModelViewSet that I call to retrieve data. I have performance issue because I need to call a lot of routes after the user login, and I would like to keep the REST logic but also returns after the login all the viewsets content in the login response (keeping their filters). Is it possible to call a ModelViewset list() from another view (viewset or APIView)? The only answer I found on SO was to do something like this class ContentGenerator(APIView): def get(self, request, format=None): data = MyModelViewSet.as_view({'get': 'list'})(request) return Response({'data': data}) But it is not supported Exception Value: The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request` Is there another solution? -
Django efficiently streaming site (like YouTube )
I just want to make audio/video streaming site how can I transfer the data packet effectively as like YouTube or audiofarm -
django site in urls at in path is error not found and NoReverseMatch at /blog/posts/
i have a django site i have a eerorr in my site please help me see you please : i have in urls in blog django site a path : is it warring ? what? please answer me! erro is : Reverse for 'detail' with arguments -
Get absolute or relative url of wagtail page
I have to following code snippet which should return a correct url (relative or absolute) class LinkFields(models.Model): link_external = models.URLField("External link", blank=True) link_page = models.ForeignKey('wagtailcore.Page', null=True, blank=True, related_name='+') link_document = models.ForeignKey('wagtaildocs.Document', null=True, blank=True, related_name='+' ) @property def url(self): if self.link_page: return self.link_page.url elif self.link_document: return self.link_document.url else: return self.link_external panels = [ FieldPanel('link_external'), PageChooserPanel('link_page'), DocumentChooserPanel('link_document'), ] class Meta: abstract = True So if I use the ".url" property for a "wagtailcore.Page" a get an absolute url starting with "http" instead of "https". What is the correct wagtail way to return a correct relative url or correct absolute url (leading with https in my case) within my "view/model"? Thank you -
django; How to create view (function) without template
Is it possible to create function without template? Like I'm trying to create delete function and what I want to do is to delete something immediately after clicking the delete button and then redirect to other page. I want to place a delete button on the page users can edit their post. html is like this <button type="submit" class="btn btn-outline-secondary">Save Changes</button> </form> and I want to place delete button next to this button. def edit_entry(request, entry_id): '''Edit a post.''' entry = Entry.objects.get(id=entry_id) if request.method != 'POST': form = EditEntryForm(instance=entry) else: form = EditEntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse_lazy('main:index')) return render(request, 'main/edit_entry.html', {'entry': entry, 'form': form}) def delete_entry(request, entry_id): '''Delete post''' #I don't wanna create template for this function. pass Anyone who can give me tips? -
no such column: Schedule_footballscore.match_played
class FootballScore(models.Model): team = models.ForeignKey(Team, related_name='teams_football', on_delete=models.CASCADE) match_played = models.IntegerField(default='0') lose = models.IntegerField(default='0') win = models.IntegerField(default='0') Initially i have team and win field only, Now i am adding new fields match_played and lose . When i am doing python manage.py makemigrations , no change is displayed, i even tried python manage.py makemigrations (my_app_name) . i also tried all the previous answers of Stackoverflow related to this topic. migrations.CreateModel( name='FootballScore', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('match_played', models.IntegerField(default='0')), ('lose', models.IntegerField(default='0')), ('win', models.IntegerField(default='0')), ], ), I have seen this migration type of thing in one of the folder, is this the migrated list, because here all my fields are mentioned? Any help will be appreciated! Thanks. -
Create Offline Refund in Woocommerce
I want to create a refund in woocommerce for an order without using the payment gateway. For that I need to set the property, api_refund whose default value is True to False. How can I send the parameter without changing the url to post to the API? -
object created even if field was required
#models.py class Mymodel(models.Model): name = models.CharField(max_length=100,null=False,blank=False) email = models.EmailField(max_length=100,null=False,blank=False) password = models.CharField(max_length=120,null=False,blank=False) email_notification = models.BooleanField() #views.py obj=MyModel.objects.create(name="ok",password="dsfdsfdsfdsfsfds",email_notification=1) even if email was required field,then also object was created when I see in the admin panel.What can be the issue,Why object got created,even if email field was mandatory? Also if I go in admin panel and open that object and click save then it raises that email is required -
Python timezone delta gives different dates when subtracted from date and datetime
I wrote a python function that gives me datetime or date in the past, with reference to current date. def get_past_date(no_of_days, date_only=False): """Returns timezone aware Datetime object in past based on no_of_days provided""" if date_only: return timezone.datetime.today().date() - timezone.timedelta(no_of_days) past = timezone.datetime.today() - timezone.timedelta(no_of_days) return timezone.make_aware(past, timezone=pytz.timezone(settings.TIME_ZONE)) The problem is: timezone.datetime.today().date() - timezone.timedelta(no_of_days) and timezone.datetime.today() - timezone.timedelta(no_of_days) return different date for same input (no_of_days) timezone.datetime.today() returns a date that is 1 day earlier than timezone.datetime.today().date() timezone.datetime.today() - timezone.timedelta(6 * 365 / 12) = datetime.datetime(2018, 1, 1, 21, 12, 43, 741750) timezone.datetime.today().date() - timezone.timedelta(6 * 365 / 12) = datetime.date(2018, 1, 2) Am I missing something here? -
How to get index in case of nested for-loops in django template?
In my django template code, I've written code for table in nested for loops. By using with statement, I want to put serial number. But it is not working. Have a look at my code in html file: <tbody> {% for a_testcases in testcases %} {% for a_test in a_testcases %} {% with x=forloop.parentcounter.counter %} <tr> <td id="sno_{{a_test.id}}">{{ forloop.counter|add:x }}</td> <td id="name_{{a_test.id}}">{{ a_test.name }}</td> <td id="cputime_{{a_test.id}}">{{ a_test.safe_exec.cpu_time }}</td> <td id="clocktime_{{a_test.id}}">{{ a_test.safe_exec.clock_time }}</td> <td id="memorylimit_{{a_test.id}}">{{ a_test.safe_exec.memory }}</td> <td id="stacksize_{{a_test.id}}">{{ a_test.safe_exec.stack_size }}</td> <td id="child_{{a_test.id}}">{{ a_test.safe_exec.child_processes }}</td> <td id="openfiles_{{a_test.id}}">{{ a_test.safe_exec.open_files }}</td> <td id="maxfilesize_{{a_test.id}}">{{ a_test.safe_exec.file_size }}</td> </tr> {% endwith %} {% endfor %} {% endfor %} </body> It is showing nothing in place of serial number.How to fix it? -
Django website with sqlite db deployment on heroku
I have been reading at many places that Heroku doesn't support sqlite database. Is there no option to use sqlite? Is there any kind of wrapper or plug-in to be used with sqlite so that it can be deployed in Heroku? Can anyone share resources or guides to do the same end to end? -
Can't seek video in localhost - Python Django
I have an issue about Video in Django. I hope your guys help me to fix it. Video larger than 10MB, have URL: http://localhost:8000/media/users/2/videos/58.mp4 This video cannot be loaded and seeked normally. It load partially and I can't even seek it. Please see this error in video: https://www.youtube.com/watch?v=6RoVLUL__JQ What is this problem? Is this an issue coming by Server? -
AttributeError: 'tuple' object has no attribute (SQLite)
AIM Once the User enters search_text in the HashtagSearch FormView, the function get_tweets() will get from Twitter the locations associated with that hashtag. Then, use get_or_create to save the search_text in the Hashtag db. Then, go through the txt file line by line and, assuming the regex requirements have been satisfied, add the line as a locations associated with the search_text in the db. As a summary of the workflow: A User enters search_text in the HashtagSearch FormView, A function is run within HashtagSearch FormView that searches Twitter for tweets using the search_text as a hashtag ('the applicable tweets'), Searches 'the applicable tweets' for whether the tweeter has a location saved on their profile. If so, save that location to a txt file, Performs regex on the txt file to filter out 'non-genuine' locations, Saves the locations to the locations object associated with the search_text in the Hashtag model. Render results.html with the location object associated with the search_text in the Hashtag model. ERROR Request Method: POST Django Version: 2.0 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'locations' Exception Location: /mnt/project/mapping_twitter/views.py in get_tweets, line 87 Python Executable: /mnt/data/.python-3.6/bin/python Python Version: 3.6.5 Python Path: ['/mnt/project', '/mnt/data/.python-3.6/lib/python36.zip', '/mnt/data/.python-3.6/lib/python3.6', '/mnt/data/.python-3.6/lib/python3.6/lib-dynload', … -
Can't output data in page
i have 2 tables in DB wallet(id,name) and balance(id,wallet_id) i need table consisting of 2 cells (post,date) where will all wallets in first cell and them balance in second {% for wallets1 in wallets %} <tr> {% for balance1 in balance %} {% if balance1.wallet_id == wallets1.id %} <td> {{ balance1.balance }}</td> {% endif %} {% endfor %} {% endfor %} if we have balance of coin we print balance if balance1.wallet_id need print "0" The difficulty next. If i do that {% for wallets1 in wallets %} <tr> {% for balance1 in balance %} {% if balance1.wallet_id == wallets1.id %} <td> {{ balance1.balance }}</td> {% else %} <td> 0</td> {% endif %} {% endfor %} {% endfor %} zero will be printed many times -
Listing form items (radio buttons)
I've set up a form that is basically a listing of addresses as radio buttons. This form allows the user to select the address, which they previously entered, to use as the ailling address. Within the template, rather than outputting the form like this: <form method="POST" action=''> {% csrf_token %} {{ form }} </form> I'd like to output the form like this so that I can capture the id of the address and allow the user to click a link that will allow them to edit the address instance (the following outlines what I want to do, but the code won't work): {% for form in forms %} {{ form.address }}<a href="{% url 'address_edit' id=form.id %}">Edit</a> {% endfor %} I'm not sure if this will help, but here is my model and form. Forms.py class AddressForm(forms.Form): billing_address = forms.ModelChoiceField( queryset=UserAddress.objects.all(), widget = forms.RadioSelect, empty_label = None, ) Models.py class UserAddress(models.Model): user = models.ForeignKey(UserCheckout, on_delete=models.CASCADE) address1 = models.CharField(max_length=120) city = models.CharField(max_length=120) state = models.CharField(max_length=120, choices=STATE_CHOICES, null=True, blank=True) country = models.CharField(max_length=120, choices=COUNTRY_CHOICES, null=True, blank=True) zipcode = models.CharField(max_length=120) If needed, I can provide the view, but I'm not sure that that will help at this point. Thanks a ton! -
TypeError: Required argument 'year' (pos 1) not found in django
I added a new field to my already existing model and when I run python manage.py makemigrations and I got the following 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now() I accidentally run >>timezone.date() Then when I run python manage.py migrate I get the following error TypeError: Required argument 'year' (pos 1) not found My following is my showmigrations [X] 0001_initial [X] 0002_auto_20180307_1222 [X] 0003_auto_20180308_1608 [X] 0004_auto_20180421_0937 [ ] 0005_auto_20180702_1917 [ ] 0006_auto_20180702_1949 [ ] 0007_auto_20180702_2000 How can I solve this problem. -
Postgres EXPLAIN ANALYZE cost estimate row count massively higher than actual row count. No Vacuuming?
I have a Postgres 9.4.18 database running on Heroku in a Django project. I had noticed that queries were becoming increasingly slow so I ran an "EXPLAIN ANALYZE" on one query and noticed that for one node the row estimate was massively higher than the actual row count: -> Seq Scan on listings_listing u1 (cost=0.00..1536692.01 rows=5030003 width=8) (actual time=0.811..11263.410 rows=173537 loops=1) I then ran "VACUUM FULL ANALYZE" on the table and then reran the "EXPLAIN ANALYZE" on the query and got: -> Seq Scan on listings_listing u1 (cost=0.00..23554.61 rows=173537 width=8) (actual time=0.001..33.884 rows=173537 loops=1) The execution time is now 100x faster. So the two questions are: A) shouldn't auto vacuuming be preventing this? (how do I check if that is enabled?) B) how did it get this way assuming the vacuuming isn't being performed? -
Localhost with Django Rest from MySQL and HTML based webclient not working as expected
I am having problem with my little project I am working on and come to you with for hope to get some assistance. Firstly I will ask a simple question which might be origin of my problem - but incase it is not I will provide my code from REST settings and webclient side. So this is expected to be long post. I am able to use my webclient from local machine, where localhost 127.0.0.1:8000 is running, and everything is working like a charm. Webclient is run from the browser from my schools public_html system. How this is set up, I am not 100% sure, but basically we can set up webpage run from school system using the folder and access the pages from web. I got index.html and stuff like JS, Tabulator extension, Jquery, Ajax etc etc running from scripts or locally installed and included in tags. I can use GET/PUT/DELETE etc commands as I have set them up - so everything works when I am working on local machine through webclient. Question is: Am I supposed to be able to connect the REST from non-local machine when localhost 127.0.0.1:8000 is running and up on the localmachine where webclient … -
Template does not exsit error happens
I am making Django app.Django version is 1.8 . I wrote in views.py dir_path = "../static/template/" if not os.path.exists(dir_path): os.makedirs(dir_path) html_path = dir_path + "test.html" if os.path.exists(html_path): template = loader.get_template(html_path) return HttpResponse(template.render(request)) When I run it,Template does not exsit error happens.But file is existed in the directory, so I really cannot understand why this error happens.Is relative path not good?How should I fix this? -
ReactJS (create-react-app) and Django backend - best way to handle auth?
What's the best method to handle auth with reactjs and a django backend? Any libraries? -
index for ArrayField in postgresql(django)
I'm using postgresql in Django and also I have an ArrayField in one of my models like follows : words = ArrayField( models.CharField(max_length=255, blank=True), null=True, blank=True ) In my code I have queries on this field only for null values. It means I have only following queries on this field : Entity.objects.filter(words__isnull=True).all() Entity.objects.filter(words__isnull=False).all() Unfortunately table of Entity is large and this query takes long hours to answer. What is best index for this field based on my queries? -
cookiecutter error in django
I installed a cookie cutter using pip. Then I ran this $ cookiecutter https://github.com/pydanny/cookiecutter-django But this hasn't been working. This is the traceback: Traceback (most recent call last): File "/home/choco/.local/bin/cookiecutter", line 7, in from cookiecutter.main import main ModuleNotFoundError: No module named 'cookiecutter'