Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to build an android app with django backend?
I need to build android app with django backend, I am using rest-framework for getting json data. I have wrote views and models,app is working fine in browser. For Example my home view: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer urls.py: router = routers.DefaultRouter() router.register(r'api/users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Result page: My issue is when I hit the url in android app, I am getting connection timeout and some times I receive the request but android app doesn't receive the response. app continuously loading then getting connection timed out error. Is there any setting is needed in django backend code. Please let me know the solution or directions how to do this? Thanks in advance. -
mezzanine cms crashed after added user profile model
I am learning mezzanine. I just followed the quick start steps set up Mezzanine 4.4.2 project myproject and changed the local_settings to use postgresql database. Everything ran very well until I tried to set up a user profile. I created an app called myapp and I followed this link to setup models and settings: [http://mezzanine.jupo.org/docs/user-accounts.html#profiles] # In myapp/models.py from django.db import models class MyProfile(models.Model): user = models.OneToOneField("auth.User") date_of_birth = models.DateField() bio = models.TextField() # In settings.py INSTALLED_APPS = ( "myapp", "mezzanine.accounts", # Many more ) ACCOUNTS_PROFILE_MODEL = "myapp.MyProfile" after this was done I then ran manage.py makemigrations manage.py migrate. After these 2 steps, I then ran manage.py runserver. Yes, the bio and date of birth fields are available in the signup and update profile forms. However, when I used admin to add new user, I got: InterfaceError at /admin/auth/user/add/ connection already closed Request Method: POST Request URL: 127.0.0.1:8000/admin/auth/user/add/ Django Version: 1.10.2 Exception Type: InterfaceError Exception Value: connection already closed Exception Location: /home/nighthawk/.virtualenvs/mez/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py in create_cursor, line 211 Python Executable: /home/nighthawk/.virtualenvs/mez/bin/python Python Version: 2.7.12 Python Path: ['/home/nighthawk/www/testproject', '/home/nighthawk/.virtualenvs/mez/lib/python2.7', '/home/nighthawk/.virtualenvs/mez/lib/python2.7/plat-i386-linux-gnu', '/home/nighthawk/.virtualenvs/mez/lib/python2.7/lib-tk', '/home/nighthawk/.virtualenvs/mez/lib/python2.7/lib-old', '/home/nighthawk/.virtualenvs/mez/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-i386-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/nighthawk/.virtualenvs/mez/local/lib/python2.7/site-packages', '/home/nighthawk/.virtualenvs/mez/lib/python2.7/site-packages'] The database was actually not closed. I created another project and if I didn't add … -
Using celery beat as a scheduler for irregular intervals?
I have a single django application that allows the user to create multiple distinct blogs. Each blog needs to collect model data (e.g. number of visits, clicks, etc.) hourly/daily/weekly etc. and the interval at which data is collected may be different between blogs. Additionally, at some point in time, the users may want to change the frequency of data collection e.g. from weekly to daily on the user interface. Looking into Periodic Tasks from the official documentation, it appears that I would have to 'hardcode' the interval values into the settings file and I can only specify the interval once e.g. from celery.schedules import crontab CELERYBEAT_SCHEDULE = { # Executes every Monday morning at 7:30 A.M 'add-every-monday-morning': { 'task': 'tasks.add', 'schedule': crontab(hour=7, minute=30, day_of_week=1), 'args': (16, 16), }, } How do I go about this or is it even possible for celery to schedule multiple tasks of the same kind at different intervals AND change the values through the user interface (via AJAX)? -
Tag detail page with Django-taggit
Im trying to create pages for tags on my django blog. I already have a simple index page which displays a list of all used tags, now I want to have individual pages for each tag and on that page I will display all posts marked with that tag. The url structure for these tag detail pages will be like this localhost/tag/my-tag-here I already have django-taggit installed and added some tags and I have them displaying fine on post detail pages and the tag index page mentioned above but Im getting a 404 when I try to visit each tag detail page such as /tag/test. These are my files and the full error message below. views.py def tag_detail(request, tag): tag = get_object_or_404(Tag, tag=tag.name) return render(request, 'blog/tags_detail.html', {'tag': tag}) urls.py (app) urlpatterns = [ url(r'^$', views.blog_index, name='blog_index'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.blog_post_detail, name='blog_post_detail'), url(r'^contact/$', views.contact_form, name='contact_form'), url(r'^thanks/$', views.thanks_view, name='thanks_view' ), url(r'^about/$', views.about, name='about'), url(r'^upload/$', views.upload_image, name='upload_image'), url(r'^tag/(?P<tag>[-/w]+)/$', views.tag_detail, name='tag_detail'), url(r'^tags/$', views.tags_index, name='tags_index') ] and this is the full error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/tag/test is the problem here in my view or the url structure? For the view I'm not 100% sure if thats the correct way … -
Django Postgresql ArrayField CharField to store tuples
I'm using Django (1.9.7) ArrayField with models.CharField as the base field to store a list of tuples. Each tuple has a string and integer such as ("hello", 5). I thought that by using CharField as the base field I could append values like ("hello", 5), which would be stored as string and then retrieved as "("hello", 5)", which I could then convert back to tuples using eval(). However, sometimes my_tuple_field[i] returns a string "("hello", 5)" and sometimes a tuple ("hello", 5). What could be happening? -
Cannot have any URLs with slugs. NoReverseMatch
I'm a begginer grasping at straws with difficulty dealing with the django slug url system and these NoReverseMatch errors that make no sense to me even after reading the docs. I have a django project. In one of the views, I pass a list of geoJSON features into a template, and show them on a map. I want to have each feature act as a clickable 'link' to a view that will show stuff about it. The following is part of the template that has those features that I want to click on: //part of the template: <script type="text/javascript"> ... function onEachFeature(feature, layer) { layer.on('click', function (e) { window.location.href = "{% url 'polls:areadetail' feature.properties.myslug%}"; }); } (I have confirmed that feature.properties.myslug does in fact contain the slug I want). The url pattern I want to go to: urlpatterns = [... url(r'^areadetail/(?P<areaslug>[-\w]+)/$', views.AreaDetail, name='areadetail'),] And the view it relates to: def AreaDetail(request, areaslug): area = get_object_or_404(Area, nameslug=areaslug) return render(request, 'polls/areadetail.html', {'area':area}) The issue I get is, by doing what I show and placing that url reference inside that template I show above, that I want to be able click on, that template won't even work at all, giving me a 'Error … -
Force page refresh
I have a simple class based view that extends Django's (1.10) generic UpdateView. On the GET, the view presents a pre-populated form from the linked model. On the POST, the view updates the db record and then redirects the user to the list page that shows all the database records in a table. I am using the success_url property to do the redirect. However, when the redirect finishes and the list page is displayed, the changes I made during the update are not reflected. When I look in the database, the changes are there. The redirect must be pulling from a previous cache or something but how do I prevent this from happening? I am using Django 1.10; Ubuntu OS; Chrome Browser; supplied wsgi dev django webserver. class UpdateBrandAmbassador(UpdateView): model = BrandAmbassador form_class = BrandAmbassadorForm template_name = 'core/base_form.html' title = "Update Brand Ambassador" success_url = "/brand_ambassadors" -
Create a django superuser and serve static files in a Docker container
So I am dockerizing a django app and I cannot figure out how to create a superuser and get the static files going. I am using supervisor to start uwsgi + nginx(so far nginx not running perfectly).As I am using an image for MySql, I am running everything using docker-compose. My Dockerfile looks like this: FROM ubuntu:16.04 MAINTAINER Dockerfiles RUN apt-get update && apt-get install -y libldap2-dev libsasl2-dev libssl-dev RUN apt-get update && apt-get install -y \ libmysqlclient-dev \ nginx \ python-dev \ python-mysqldb \ python-setuptools \ supervisor \ vim \ python-pip \ && rm -rf /var/lib/apt/lists/* RUN pip install uwsgi RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/default RUN ln -s /home/docker/code/nginx-app.conf /etc/nginx/sites-enabled/ RUN ln -s /home/docker/code/supervisor-app.conf /etc/supervisor/conf.d/ COPY app/requirements.txt /home/docker/code/app/ RUN pip install -r /home/docker/code/app/requirements.txt COPY . /home/docker/code/ WORKDIR /home/docker/code CMD ["supervisord", "-n"] Should I create a .sh file and add command = sh file.sh to my supervisor? Or is there a better way to create a superuser for a django app in a docker container and also get the static files going? -
Django SMS Polling
I'm trying to build a Django App into an existing website that uses SMS messages for polling (kind of like what American Idol did, like "Send '1' to to vote for '1'"). Are there any existing packages or services that are easily integrated into Django for this? It would be preferable for this to be free or low cost, as its for a charity! Thanks! -
Django + Celery: 'str' object has no attribute 'publish_task'
I'm using Celery to send emails asynchronously with Django. When I'm trying to use a task, I get an error stating 'str' object has no attribute 'publish_task'. From the logs, it seems like the error lies in Celery's code, but my code could also be the source. Here are my logs: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/reminder/ Django Version: 1.8.5 Python Version: 3.4.3 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'bootstrap3_datetime', 'haystack', 'registration', 'tinymce', 'djcelery', 'djcelery_email', 'RemindApp', 'home', 'BookRoom', 'GameDev') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.locale.LocaleMiddleware') Traceback: File "C:\Users\Tony\Desktop_Files\Envs\ReminderVenv\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tony\Desktop_Files\Envs\ReminderVenv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "C:\Users\Tony\Desktop_Files\Programming\Django\Reminder\RemindApp\views.py" in index 49. request.user.email) File "C:\Users\Tony\Desktop_Files\Envs\ReminderVenv\lib\site-packages\celery\app\task.py" in apply_async 565. **dict(self._get_exec_options(), **options) File "C:\Users\Tony\Desktop_Files\Envs\ReminderVenv\lib\site-packages\celery\app\base.py" in send_task 350. task_id = P.publish_task( Exception Type: AttributeError at /reminder/ Exception Value: 'str' object has no attribute 'publish_task' In addition, here is my task: @celery.task def Mailer_Send(reminder, reminder_title, user, email): mail = Mailer() mail.send_messages( subject = "Time's up! {} is due".format(reminder_title), template = 'reminder/email.html', context = {'user': user, 'post': reminder}, to_emails = [email] ) logger.info('Sending email for reminder: {}'.format(reminder_title)) And here is where I'm trying to use the task: … -
Django content types how does it works?
I have these relations: class Article(models.Model): title = models.CharField(max_length=60) body = models.TextField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) pub_date = models.DateField() comments_count = models.IntegerField(default=0) objects = PublishedManager() comments = GenericRelation(Comment) class Entry(models.Model): title = models.CharField(max_length=60) body = models.TextField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) pub_date = models.DateTimeField() comments_count = models.IntegerField() objects = PublishedManager() comments = GenericRelation('Comment') class Comment(models.Model): body = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Adding comments to article/entry works fine ex: position = Article.objects.get(pk=pk) new_comment = Comment(content_object=position, body=form.cleaned_data['body']) new_comment.save() I can see them in database but I want to list them in template in details of specific article/entry. I tried many solutions that I have found in internet but I get everytime the same error Unable to get repr for <class 'django.db.models.query.QuerySet'> What is wrong with my generic relationship? How can I list all comments related to specific article/entry? -
Django query taking hours, only 1.5M records
There are about 1.5 million rows in Product, and about 1.1 million rows in RetailerProduct with retailer_id=2 (2.9 million in total in RetailerProduct) Models: class Product(models.Model): ... upc = models.CharField(max_length=96, unique=True) ... class RetailerProduct(models.Model): ... product = models.ForeignKey('project.Product', related_name='retailer_offerings', on_delete=models.CASCADE, null=True) ... class Meta: unique_together = (("retailer", "retailer_product_id", "retailer_sku"),) Query: Product.objects.exclude(retailer_offerings__retailer_id=1).values_list('upc', flat=True) Generated SQL: SELECT "project_product"."upc" FROM "project_product" WHERE NOT ("project_product"."id" IN (SELECT U1."product_id" AS Col1 FROM "project_retailerproduct" U1 WHERE (U1."retailer_id" = 1 AND U1."product_id" IS NOT NULL))) Running that query takes hours. An EXPLAIN in the psql shell renders: QUERY PLAN --------------------------------------------------------------------------------------------------- Seq Scan on project_product (cost=0.00..287784596160.17 rows=725892 width=13) Filter: (NOT (SubPlan 1)) SubPlan 1 -> Materialize (cost=0.00..393961.19 rows=998211 width=4) -> Seq Scan on project_retailerproduct u1 (cost=0.00..385070.14 rows=998211 width=4) Filter: ((product_id IS NOT NULL) AND (retailer_id = 1)) (6 rows) I wanted to post the EXPLAIN ANALYZE but it's still running. Why is the cost so high for Seq Scan on project_product? Any optimization suggestions? -
Handling big queries with many relationships in django
So if I have a parent like this: class Comic(models.Model): authors = models.ManyToManyField(Author) artists = models.ManyToManyField(Artist) genres = models.ManyToManyField(Genre) name = models.CharField(max_length=255, default="") image = models.ImageField(upload_to=upload_comic_cover) Then a many to one relationship with the parent and child: class ComicChapter(models.Model): comic= models.ForeignKey('Comic', on_delete=models.CASCADE) name = models.CharField(max_length=255, default="", null=True, blank=True) chapter_number = models.IntegerField(default=0) Then a many to many relationship with author, artists, and genres. They all look alike, just have different names. class Genre(models.Model): name = models.CharField(max_length=255, default="") summary = models.TextField(max_length=1000, default="") date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) How would I go about making a search of 100 comics that contains all the genres, artists, authors and also the last chapter into something easily manageable like a nested dictionary. My idea is to do something like this: query = Comic.objects.order_by('name')[:100] comic_dict = {} for chapter in query: comic_dict[chapter.name] = {} comic_dict[chapter.name]['image'] = chapter.image comic_dict[chapter.name]['authors'] = list(Author.objects.filter(chapter=chapter.id).values_list('name', flat=True)) comic_dict[chapter.name]['artists'] = list(Artist.objects.filter(chapter=chapter.id).values_list('name', flat=True)) comic_dict[chapter.name]['genres'] = list(Genre.objects.filter(chapter=chapter.id).values_list('name', flat=True)) comic_dict[chapter.name]['last_chapter'] = ComicChapter.objects.values_list( 'name', 'chapter_number', ).filter(chapter=chapter.id).order_by('chapter_number').last() But that obviously makes over 400 queries instead of just a few. How can I change this up so I can get something similar, a nested dictionary containing all the relationships properly. Is it hard to avoid many queries when using … -
How to stack changes made to a page based on user clicks?
Here's a simplified example of my problem: I have a django app. I have a model called 'my_model' with a CharField called my_char_field. I have a template called detail.html that details an instance of 'my_model' and also has two buttons (forms), 'Button_X' and 'Button_Y'. Let's say the instance we're dealing with has a my_char_field = 'Happy days.' When Button_X is clicked, my_char_field is doubled, i.e. it turns into 'Happy daysHappy days'. When Button_Y is clicked, my_char_field is lowercased, i.e. it turns into 'happy days'. The problem is that these two actions don't stack. e.g. If a user clicks Button_X and then Button_Y, I want my_char_field to be 'happy dayshappy days'. How can I manage this? I could compute both Button_X and Button_Y actions upon submission of either, but I want to avoid doing this, because in reality, these are quite heavy computations. e.g. I'd rather not have to have a user click Button_X double my_char_field, and then upon clicking Button_Y, have to both double my_char_field (again) and lowercase my_char_field. -
django querset filter foriegnkey select first record
I have a History model like below class History(models.Model): class Meta: app_label = 'subscription' ordering = ['-start_datetime'] subscription = models.ForeignKey(Subscription, related_name='history') FREE = 'free' Premium = 'premium' SUBSCRIPTION_TYPE_CHOICES = ((FREE, 'Free'), (Premium, 'Premium'),) name = models.CharField(max_length=32, choices=SUBSCRIPTION_TYPE_CHOICES, default=FREE) start_datetime = models.DateTimeField(db_index=True) end_datetime = models.DateTimeField(db_index=True, blank=True, null=True) cancelled_datetime = models.DateTimeField(blank=True, null=True) Now i have a queryset filtering like below users = get_user_model().objects.all() queryset = users.exclude(subscription__history__end_datetime__lt=timezone.now()) The issue is that in the exclude above it is checking end_datetime for all the rows for a particular history object. But i only want to compare it with first row of history object. Below is how a particular history object looks like. So i want to write a queryset filter which can compare first rows end_datetime only. -
Django - Query object by last element added to ManyToMany field
I have something like this: class Car(models.Model): model = models.CharField(max_length=200) brand = models.CharField(max_length=100) status = models.ManyToMany(Status) class Status(models.Model): name = models.CharField(max_length=40) date = models.DateTimeField('Status creation date') How can I query all the cars where their last status (most recent) is REPAIRED for instance? Is this achievable in just one query? -
Is there any application or method to manage correctly responses and exceptions of emails in Django?
Sending emails is quite easy, but how to correctly handle all exceptions and feedback in Django? Once I made my own solution, but the process is quite complicated, so I'm wondering if there is a better solution. Sending of emails is easy. I send emails via postfix (SMTP connection with Django). Receiving exceptions is a complicated process. I also receive bounces and responses via postfix, that forwards them to Django (via HTTP). This is how the responses should be handled correctly in normal web application: Hard bounces - save bounce message in DB, and never send email again Soft bounces - save bounce message in DB, and don't send email if soft bounce repeats after few days (eg 4 days) Spam reports - never send emails again Unsubscription link on bottom of the email - this one is obvious List-Unsubscribe - it's a link in header of the email, it should unsubscribe all email except system emails (for example, password reminder) User manual response - most of them are irrelevant (eg "out of office"), but if a user writes in reply a request to unsubscribe him, I want to unsubscribe him. It's kind of manual work for a moderator to … -
How to go to a different page from current in Django template
urlpatterns = [ url(r'^$', predict_views.index, name = 'HomePage'), url(r'^admin/', admin.site.urls), url(r'^Update_db/$', predict_views.Update_db, name = 'Update_db'), url(r'^compare/(?P<phone1_id>[0-9]+)/(?P<phone2_id>[0-9]+)/$',predict_views.Compare, name = 'Compare'), url(r'^predict/(?P<phone_id>[0-9]+)/$',predict_views.Predict, name = 'Predict'), ] these are my url patterns in djano. I want to go to compare directly from predict which is not possible for me currently because : when I go to predict the url is 127.0.0.1:8000/predict/1 now when i go to compare from predict the url becomes 127.0.0.1:8000/predict/1/compare/1/2 which is not the expected url .. my url should be 127.0.0.1:8000/compare/1/2 I have seen django docs there are some redirect methods but I do not understand them. Any help is appreciated. -
Internal Server Error using uwsgi and django
So am I trying to build a Docker container for a django app but I got stuck at an error. Before adding nginx I wanted to see if uwsgi is working fine and it is not... When I run the container everything goes well, I get no error messages, however, when I check Kitematic (I am using docker on windows) under Web Preview I get Internal Server Error. My Dockerfile looks as follow: FROM ubuntu:16.04 MAINTAINER Dockerfiles RUN apt-get update && apt-get install -y libldap2-dev libsasl2-dev libssl-dev RUN apt-get update && apt-get install -y \ libmysqlclient-dev \ nginx \ python-dev \ python-mysqldb \ python-setuptools \ supervisor \ vim \ python-pip \ && rm -rf /var/lib/apt/lists/* RUN pip install uwsgi RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/default RUN ln -s /home/docker/code/nginx-app.conf /etc/nginx/sites-enabled/ RUN ln -s /home/docker/code/supervisor-app.conf /etc/supervisor/conf.d/ COPY app/requirements.txt /home/docker/code/app/ RUN pip install -r /home/docker/code/app/requirements.txt # add (the rest of) our code COPY . /home/docker/code/ WORKDIR /home/docker/code/app CMD ["supervisord", "-n"] and my supervisor-app.conf looks like this: [program:app-uwsgi] command = /usr/local/bin/uwsgi --http :8000 --module mysite.wsgi Last but not least my wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() I think it is also worth mentioning the … -
Python edit form data prior to django validation
I'm fairly new to python and have been searching for awhile to find how I can edit form data BEFORE all the standard python form/field validators do their magic. I have a model form with an IntegerField which I'd like to remove the "$" and commas from (using some sort of custom validation), then let the normal to_python() validate() etc do their thing. My code is below - any help would be much appreciated! forms.py class BuyerSettingsForm(forms.ModelForm): total_offer_limit = forms.IntegerField(required=False, max_value=10000000, min_value=0) def __init__(self, request, *args, **kwargs): super(BuyerSettingsForm, self).__init__(*args, **kwargs) class Meta: model = Buyer fields = ['total_offer_limit'] def save(self, commit=True): profile = super(BuyerSettingsForm, self).save(commit=commit) profile.total_offer_limit = self.cleaned_data['total_offer_limit'] profile.save() return profile views.py class SettingsPreferences(LoginRequiredMixin, BuyerAccessRequiredMixin, BuyerAdminAccessRequiredMixin, UpdateView): template_name = 'invoicely/buyer/settings/buyer_settings.html' form_class = BuyerSettingsForm success_url = reverse_lazy('settings_preferences') def get_object(self, *args, **kwargs): return self.request.user.profile.buyer def get_initial(self): ctx = super(SettingsPreferences, self).get_initial() ctx.update({ 'total_offer_limit': self.object.total_offer_limit, }) return ctx def get_form_kwargs(self): kwargs = super(SettingsPreferences, self).get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): self.object = form.save() messages.add_message(self.request, messages.SUCCESS, "Settings successfully updated") return super(SettingsPreferences, self).form_valid(form) -
Pagination in Wagtail
I'm fairly new to Wagtail, and I am in the process of creating a site that will have a Resources (blog) section and I'm not sure how to implement pagination so that there are only 5 posts on each page and the user has to click a number (1, 2, 3, etc.) to go to the next page to see the next 5 posts. I have this in my template for the pagination section of the resource/blog index page: <ul class="pagination"> <li><a href="#"><i class="fa fa-angle-left"></i></a></li> <li class="active"><a href="#">1</a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#"><i class="fa fa-angle-right"></i></a></li> </ul> What code do I need to incorporate to make this functional? Thanks in advance. -
Configure a django test with no migrations in pyCharm
I am new to both django and pycharm! I can run the tests in my code on terminal using: python manage.py test Repo/tests/testUnit1.py --failfast -n and it works! Recently, I tried to use pycharm (professional) to run and debug the tests. The problem is that when I specify the option --nomigrations it gives the following error: Usage: /Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py test [options] [path.to.modulename|path.to.modulename.TestCase|path.to.modulename.TestCase.test_method]... Discover and run tests in the specified modules or the current directory. /Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py: error: no such option: --nomigrations I found similar question here but it suggests the same thing that I have already tried. Does this happen because the test unit and the code that I want to test are not in the same folder? How can I run a test in pycharm without migrations? -
How to convert django models schema to json?
This is an example models. class UserModel(db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.String(255), unique=True) name = db.Column(db.String(255)) This is a Json example which I want get. { "user": { "id":{ "type": "Integer", "primary_key": True, "null": True, "default value": "", "foreign key": ""}, "user_id":{ "type": "Integer", "primary_key": True, "null": True, "default value": "", "foreign key": ""}, "name":{ "type": "Integer", "primary_key": True, "null": True, "default value": "", "foreign key": ""}, } } I want translate django model scheme to json, not django models object or queryset. Wait your response online. -
how to change the value of a global varible in the child classe of python?
I have a problem in declaring variable in the child class. I have simplified the case because the code is too long and have many dependencies. So here is the case : I have 2 classes A and B : class A (): global_var=0 def some_function(self): return self.global_var+2 class B(A): def method_that_returns_global_var(self): #do some operations on global_var global_var=(.....some logic....) return global_var How to declare the global_var in the child class B so that it executes the function of the parent class some_function with the value of global_var of child class B -
Reverse for 'results' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['polls/(?P<Album_id>[0-9]+)/results/$']
im trying to create an URL's for albums but getting frustrated so im getting this error(im new to programming) Reverse for 'results' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['polls/(?P<Album_id>[0-9]+)/results/$'] on this line <h1><a href="{% url 'polls:results' Album.id %}">{{ album.AlbumTitle }}</a></h1> heres the view.py file from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from django.http import Http404 from django.template import loader from django.shortcuts import get_object_or_404, render from .models import Artist def index(request): latest_Artist_list = Artist.objects.order_by('id')[:5] context = {'latest_Artist_list': latest_Artist_list,} return render(request, 'polls/index.html', context) def detail(request, Artist_id): global Artist artist = get_object_or_404(Artist, pk=Artist_id) #kazkodel mazoji return render(request, 'polls/detail.html', {'Artist': artist}) #kazkodel mazoji def results(request, Album_id): #global Album album = get_object_or_404(Album, pk=Album_id) return render(request, 'polls/results.html', {'Album': album}) heres the url.py file from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<Artist_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<Album_id>[0-9]+)/results/$', views.results, name='results'), ]