Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Give Class Variables, values from POST methods without using functions?
remember that I don't want to use functions, I Know I can use def post(self, request) but I I can't use them because then my variables would be initialized inside a class function and I don't want that I need something like this: class Test(request): a=request.POST['key'] I'd really appreciate it if you'd choose to help me figure this out -
Django, Postgresql Aggregate By Month Function is Also Using Year
I have a database table that contains "tickets" over a 2 year period. Each ticket has a work date. I want a count of the total number of tickets in each month by year (e.g Jan 2018 being different from Jan 2019). As I was cobbling together the query, I stumbled on something that worked, but I do not know why. Or if the query makes sense. Here it is: qs = Ticket.filter(work_date__range=[datetime.date(2018, 1, 1), datetime.date.today()]).\ annotate(year=ExtractYear('work_date'), month=ExtractMonth('work_date')).\ values('year','month').\ annotate(count=Count('month')).order_by('year', 'month') Giving this output: {'count': 13816, 'year': 2018, 'month': 1}, {'count': 12778, 'year': 2018, 'month': 2}, {'count': 13960, 'year': 2018, 'month': 3}, {'count': 14128, 'year': 2018, 'month': 4}, {'count': 15277, 'year': 2018, 'month': 5}, {'count': 15689, 'year': 2018, 'month': 6}, {'count': 14905, 'year': 2018, 'month': 7}, {'count': 16025, 'year': 2018, 'month': 8}, {'count': 14044, 'year': 2018, 'month': 9}, {'count': 16332, 'year': 2018, 'month': 10}, {'count': 15397, 'year': 2018, 'month': 11}, {'count': 14348, 'year': 2018, 'month': 12}, {'count': 17166, 'year': 2019, 'month': 1}, {'count': 15504, 'year': 2019, 'month': 2}, {'count': 16311, 'year': 2019, 'month': 3}, {'count': 14910, 'year': 2019, 'month': 4}, {'count': 440, 'year': 2019, 'month': 5} My expectation is that since the aggregating function is only counting by 'month' that, … -
Changing default Django date format from YYYY-MM-DD to DD-MM-YYYY
I'm struggling to correctly set my date format in my local Django app. Everything saves into the database as yyyy-mm-dd and I've been on this site all night and none of the examples work and I'm out of ideas I've tried setting default DATE_INPUT_FORMATS in settings.py and various date parameters in my form.py i.e date = forms.DateField(input_formats=['%d-%m-%Y']) , and date = forms.DateField( widget=forms.DateInput(format='%m/%d/%Y'), input_formats=('%d/%m/%Y', ) ) my date value in my model is date = models.DateField() My form data is class MacroForm(forms.ModelForm): date = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y')), input_formats=('%d/%m/%Y',)) class Meta: model = Macro fields = ('country', 'date', 'value','comment') my settings.py has the following LANGUAGE_CODE = 'eng' TIME_ZONE = 'GMT' USE_I18N = False USE_L10N = True USE_TZ = False DATE_INPUT_FORMATS = [ ("%d/%m/%Y"), ] Unfortunately everything I try is going in the database as yyyy-mm-dd. I'd really appreciate it if someone could give me a pointer to what I'm doing wrong. I would have liked to set it somehow in the model but I don't think that's possible. Thanks in advance. -
FileNotFoundError for the media folder after deploying Django app on Apache
I have a Django app that I just added to the already deployed Django web on Apache. Because it is ran by Apache, path of the media folder seems to be different. My app lets the user upload an excel file which then changes numbers and save as csv file. (only showed relevant folders/code snippets) Current directory converts\ _init_.py apps.py forms.py models.py converter.py urls.py views.py main\ settings.py urls.py wsgi.py meida\ excels\ example.xlsx csvs\ example.csv static\ manage.py settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' main\urls.py urlpatterns = [ path('', RedirectView.as_view(url='/converts/')), path('converts/', include('converts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The part that causes the problem is the following in converts/converter.py: def convertExcel(name): path = 'media/excels/' key = path + name wb = load_workbook(key) Originally in development, a function in view calls convertExcel(example.xlsx) and the workbook, via media/excels/example.xlsx, finds the correct file to work with the loaded workbook. But in production server, it gives FileNotFoundError: [Errno 2] No such file or directory: 'media/excels/example.xlsx' My Question is: Do I have to back track from where apache2.conf is to find the path? Or is there a way to set path to my django project so i can just set path in my convertExcel() … -
How can I compare request.path and user.username in a template?
I have tried with {% if request.path == "/{{user.username}}" %} You are in Contact</p> {% else %} nono But It doesn't work -
How to set choices of field dynamically from foreign key related models field?
I have models as Offer , Wood , SliceTec and JointTec. And Wood related with SliceTec and JointTec by M2M field. At Django admin I can select multiple options for SliceTec and JointTec when adding new Wood record. No problem. When it comes to Offer I need to show options from selected Wood records woodSlice data and also woodJoint data. For ex; SliceTec data: Slicet A, Slicet B, Slicet C JointTec data: Jointt A, Jointt B, Jointt C Wood data: Wood A , (Slicet A, Slicet C), (Jointt B, Jointt C) At Offer I need to show Slicet A and Slicet B options when Wood A selected. class Offer(models.Model): name = models.CharField(max_length=200, verbose_name='Adınız Soyadınız') phone = models.BigIntegerField(verbose_name='Telefon Numaranız') email = models.EmailField(verbose_name='E-mail Adresiniz') date = models.DateTimeField(verbose_name='Teklif Tarihi') frontWood = models.ForeignKey('Wood', on_delete=models.PROTECT) frontSlice = models.CharField(max_length=200) frontJoint = models.CharField(max_length=200) frontSupport = models.ForeignKey('Support', on_delete=models.PROTECT) frontThick = models.CharField(max_length=200) frontDimen = models.CharField(max_length=200) frontFlow = models.ForeignKey('Flow', on_delete=models.PROTECT) frontGlue = models.ForeignKey('Glue', on_delete=models.PROTECT) class Meta: verbose_name = 'Teklif Talebi' verbose_name_plural = 'Teklif Talepleri' def __str__(self): return self.name class Wood(models.Model): woodName = models.CharField(max_length=200, verbose_name='Ahşap Adı') woodCode = models.CharField(max_length=50, verbose_name='Stok Kodu', blank=True, null=True) woodSlice = models.ManyToManyField('SliceTec', verbose_name='Uygun Kesim Teknikleri') woodJoint = models.ManyToManyField('JointTec', verbose_name='Uygun Ekleme Teknikleri') woodImage = models.ImageField(verbose_name='Görsel', blank=True, null=True) woodPrice … -
Many to many relation django in post to signs to post
So I want to make a sign-ups model for my app. This model needs to have 2 fields, a post field and a users field. Both fields are a many 2 many relation with the User model and Post model. But I don't know how to achieve that. Here is what I have: this is the models.py class Post(models.Model): title = CharField(max_length=250) ... def __str__(self): return self.title class SignUpPost(models.Model): post = models.OneToOneField(Post,on_delete=models.CASCADE,primary_key=True,) users = models.ManyToManyField(User) so many users can be signed up in a post. I have no idea how to do the forms.py and the views.py to store the data. I want to have in the post detail view a "sign up" button, and when clicked, fill the sign up form with the data of the post and user that clicked the button. And so, the database will have in the post field the post_id and in the users field the users_id of every user that signed up to the post. thanks in advance -
How to install pillow in docker.?
I'm trying to install Pillow in Docker but I get this error "An error occurred while installing pillow==6.0.0" Anyone who has a clue on how to install Pillow in Docker even in if it is installing through Dockerfile? -
How can i set unique mail registration in my Django project?
I was testing my registration view and i noticed that if i try to register using an alreaxy existing Username, i'll get an error; if i try to register using an already existing email, the app will let me do so. Obviously, i don't want someone to register multiple accounts with the same email on my site. I'm fairly new to Django, and since i noticed that the form checked if an username already exists, i thought it would do the same with the email field. I don't really know how to go from that, should i work on my view or on the form? And how can i make it loop through my DB and find if an e-mail had already been registered? I thought email = form.cleaned_data.get('email') would do the trick, but it didn't. Any help is appreciated. Here is my view: def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context={"form":form}) And here is the … -
How do I write a Django query that joins two tables without a common column and uses a formula to calculate time?
I'm using Django and Python 3.7. I want to write a Django query that returns instances of my Article model but I want to write the query where two tables are joined in which there isn't a common key between them. The PostGres query would look like ... select a.* FROM myproj_statbyhour h, myproj_article a WHERE h.hour_of_day = extract(hour from a.created_on + 1000 * interval '1 second') and h.total_score < 1000; The models in question look like class Article(models.Model): objects = ArticleManager() title = models.TextField(default='', null=False) ... created_on = models.DateTimeField(db_index=True, default=datetime.now) class StatByHour(models.Model): total_score = models.DecimalField(default=0, max_digits=12, decimal_places=2, null=False) ... hour_of_day = IntegerField( null=False, validators=[ MaxValueValidator(23), MinValueValidator(0) ] ) I have no idea how to do this, especially how to write the "h.hour_of_day = extract(hour from a.created_on + 1000 * interval '1 second')" part. -
Addition of data to the form in the view, displayed in the template
It transmits data from one view to another. For example forwarding=123 now I want forwarding to be displayed in my html template as in the example below. How do I pass the 'forwarding' parameter to my get on the next view, so that it is visible in the template and that I can edit it later in the template.? My next view def search(request, forwarding): product_list = Product.objects.all().order_by('created') product_filter = ProductFilter(request.GET, queryset=product_list) #How can i add here forwarding context = {'product_filter': product_filter,} return render(request, 'search.html', context) Any help will be appreciated. -
'NoneType' object has no attribute 'DoesNotExist'
I would appreciate some help in receiving data from a database by viewing it in another page as you click onto the search button. The problem I am receiving is an AttributeError. after clicking into that button I have tried to look at similar issues. Views.py def act_results(request): ''' display the acts suitable for a particular user ''' template = loader.get_template('polls/act_results.html') try: Act = request.GET.get('Act') data = Act.objects.get(act__name=Act) return HttpResponse(template.render({'Act':Act},request)) except Act.DoesNotExist: return HttpResponse(template.render({'error_msg':'Act does not exist for this Festival'})) Acts.csv "Kendrick Lamar","Main Stage","20:00:00","21:00:00","2019-06-08" "Dua Lipa","Bacardi Stage","20:00:00","21:00:00","2019-06-07" "Prodigy","Big Tent","20:00:00","21:00:00","2019-06-09" act_results.html <table style="width:100%"> <tr> <th>Acts available</th> </tr> <tr> <td>Act : {{ Acts }}</td> </tr> </table> {% endif %} I expect to receive all the information about that act in the html page. As of now I am receiving an error. -
TypeError at /search/ search() missing 1 required positional argument: 'request'
I'm trying to add search filters for my django-taggit tags in my Django project but I keep getting a TypeError. How can I fix it? I'm using Django-Haystack and Elasticsearch for the search functionalities, and this time I'm trying to add the filter with haystack Facets. Here's the full output: Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 123, in get return self.form_valid(form) File "C:\Users\loicq\desktop\coding\uvergo_search\venv\lib\site-packages\haystack\generic_views.py", line 76, in form_valid self.queryset = form.search() TypeError: search() missing 1 required positional argument: 'request' [02/May/2019 15:29:31] "GET /search/?q=las+vegas&Ptags=Solo HTTP/1.1" 500 82872 My models looks like this: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title This is my custom forms.py file: from haystack.forms import FacetedSearchForm from … -
Different crontab for each objects of single Django model using Celery
I am able to create the celery_beat_schedule and it works. YAY! But I was wondering if there any way to create the cronjob for different objects of same Django model. Settings.py CELERY_BEAT_SCHEDULE = { 'ok': { 'task' : 'bill.tasks.ok', 'schedule' : crontab(minute=27, hour=0), # 'args' : (*args) } } bill/tasks.py from celery import task @task def ok(): bills = Bill.objects.all() for bill in bills: perform_something(bill) I wanted to change the crontab time for each object. How can I do it? Assuming I have an hour and minute value in model object Thanks for your time :) -
Images are broken after uploading them on 'detail_page'
After uploading picture to my webpage (local), it adds picture to database, it adds picture to my media dir, BUT on the webpage it appears broken. settings.py MEDIA_URL = '/uploaded/' MEDIA_ROOT = os.path.join(BASE_DIR, '../media_root') views.py class MovieImageUpload(LoginRequiredMixin, CreateView): form_class = MovieImageForm def get_initial(self): initial = super().get_initial() initial['user'] = self.request.user.id initial['movie'] = self.kwargs['movie_id'] return initial def render_to_response(self, context, **response_kwargs): movie_id = self.kwargs['movie_id'] movie_detail_url = reverse( 'core:MovieDetail', kwargs={'pk': movie_id}) return redirect( to=movie_detail_url) def get_success_url(self): movie_id = self.kwargs['movie_id'] movie_detail_url = reverse( 'core:MovieDetail', kwargs={'pk': movie_id}) return movie_detail_url class MovieDetail(DetailView): queryset = Movie.objects.all_with_related_persons_and_score() def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['image_form'] = self.movie_image_form() if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote( movie=self.object, user=self.request.user ) if vote.id: vote_form_url = reverse( 'core:UpdateVote', kwargs={ 'movie_id': vote.movie.id, 'pk': vote.id}) else: vote_form_url = ( reverse( 'core:CreateVote', kwargs={ 'movie_id': self.object.id} ) ) vote_form = VoteForm( instance=vote) ctx['vote_form'] = vote_form ctx['vote_form_url'] = \ vote_form_url return ctx def movie_image_form(self): if self.request.user.is_authenticated: return MovieImageForm() return None models.py def movie_directory_path_with_uuid( instance, filename): return '{}/{}.{}'.format( instance.movie_id, uuid4(), filename.split('.')[-1] ) class MovieImage(models.Model): image = models.ImageField( upload_to=movie_directory_path_with_uuid) uploaded = models.DateTimeField( auto_now_add=True) movie = models.ForeignKey( 'Movie', on_delete=models.CASCADE) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) forms.py class MovieImageForm(forms.ModelForm): movie = forms.ModelChoiceField( widget=forms.HiddenInput, queryset=Movie.objects.all(), disabled=True ) user = forms.ModelChoiceField( widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True, ) class Meta: model = … -
Check if status is Paid and display content accordingly
I would like to know who i can check if a post item has been paid or not and display the content accordingly for the fields content and content_preview. models.py class Post_Sell_Once(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=40) content_preview = models.TextField(verbose_name="Post Content Preview", max_length=500) content = EncryptedTextField(verbose_name="Post Content", max_length=10000) ... POST_PAYMENT_STATUS = ( (0, 'unpaid'), (1, 'paid') ) class Post_Paid_Sell_Multiple(models.Model): paying_user = models.ForeignKey(User, on_delete=models.CASCADE) post_sell_multiple = models.ForeignKey(Post_Sell_Multiple, on_delete=models.CASCADE) STATUS = models.IntegerField(choices=POST_PAYMENT_STATUS, default=0) paid_date = models.DateField(auto_now_add=True) def publish(self): self.paid_date = timezone.now() self.save() class Meta: ordering = ['-paid_date'] views.py def post_sell_multiple_detail(request, pk): post = get_object_or_404(Post_Sell_Multiple, pk=pk) list_comments = Post_Sell_Multiple_Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk') paginator = Paginator(list_comments, 10) page = request.GET.get('commentpage') comments = paginator.get_page(page) return render(request, 'app/Post_Sell_Multiple/post_sell_multiple_detail.html', {'post': post, 'comments': comments}) But if i manually set a post to paid nothing changes at my template and i was not yet able to find the issue template.html <div> {% if post. == 'paid' %} <<<<<< <p>{{ post.content|safe|linebreaksbr }}</p> {% else %} <p>{{ post.content_preview|safe|linebreaksbr }}</p> {% endif %} <div class="clearfix"></div> </div> i guess my problem is that i dont know how to call the status at the if statment on my template. thankful for any hint -
trouble with my nested for loops achieve results similar to a sumif
I'm trying to cycle through 2 lists using for loops to calculate the sum for each unique reference. I suppose I'm looking for a pythonic sumif! # list of data ("user_ID", "contract_Number", "weight", "type") list1 = [ ('1','261','6.2','Input'), ('1','262','7.2','Input'), ('1','263','5.2','Input'), ('1','264','8.2','Input'), ('1','261','3.2','Input'), ('1','262','2.2','Input'), ('1','262','7.2','Input'), ('1','263','4.2','Input'), ('1','264','6.2','Input'), ('1','265','6.2','Input'), ('1','261','9.2','Input'), ('1','261','10.2','Input') ] contract_list = [] # create a list of contract numbers for data_row in list1: if data_row[0] == "1" and data_row[3] == "Input": contract_list.append(data_row[1]) #remove duplication - left with a list of unique contract numbers contract_list = list(dict.fromkeys(contract_list)) print(contract_list) # I'm trying this...[28.6, 16.6, 9.4, 14.4, 6.2] tally_list = [] tally = 0 for c in contract_list: for l in list1: if data_row[0] == '1' and data_row[1] == contract_list[0]: tally = tally + float(data_row[2]) tally_list.append(tally) print(tally_list) I'm expecting... ['261', '262', '263', '264', '265'] [28.6, 16.6, 9.4, 14.4, 6.2] I'm getting... ['261', '262', '263', '264', '265'] [122.40000000000002, 244.7999999999999, 367.19999999999976, 489.5999999999996, 612.0] -
How to add multiple hosts to django database?
The connection URL to my MySQL server is like so jdbc:mysql://server1:3306,server2:3306,server3:3306/mydb After I parse and extract the hosts and ports, how can I pass it in Django DATABASES section below? DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'mydb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'server1', 'PORT': '3306' } } -
how to check image is already save in directory
I'm creating a project on mobile's comparison website in Django. I'm using beautifulSoup4 for scraping the mobile's details. I rendering the scraped data in the Browser as a JSON without storing the data in the database but downloading the image of the mobile. when a user searches for a phone, it's run the code and grab the data and save the phone's image in the directory. the problem is that when another user searches for the same phone, program scraped the data and download the image but image filename is already in the directory. An Error occurs: filename is already in the directory my Point is - Is there any way to check the image filename is already in the directory or not -
Using Django With fast-cgi
Im using nginx and uwsgi to serve a django application on ubuntu server . My Problem is , when there'is no requests to webserver Nginx will be put to sleep ! And whenever a new request comes it will take some time to OS fire it up . I tried to change the nginx configuration several times, But Non of them works . Recently i heard about fast-cgi which can solve this problem. Please explain what exactly is a fast-cgi ? And is it good to serve Django Application with fast-cgi ? is it better than default nginx proxy webserver ? Thanks -
Can't install any pip package within my docker environment, since it won't be recognized
I am running a Cookiecutter django project in a docker environment and I would like to add new packages via pip. Specifically I want to add: djangorestframework-jwt When I do: docker-compose -f local.yml run --rm django pip install it seems like it would be perfectly working because I get: Successfully installed PyJWT-1.7.1 djangorestframework-jwt-1.11.0 Now the problem is that it doesn't install it. It doesn't appear when I run pip freeze, and also not in pip list Then I tried to put it into my requirements.txt file and run it with: docker-compose -f local.yml run --rm django pip install -r requirements/base.txt Same result. It says that it is successfully installed but it is not. I thought it might be a problem with my django version and the package, but the same happens when I try to update my pip. It says it updated, but when I run pip install -upgrade pip I get again: You should consider upgrading via the 'pip install --upgrade pip' command. I'm running out of options. My requirements: -r ./base.txt Werkzeug==0.14.1 # https://github.com/pallets/werkzeug ipdb==0.11 # https://github.com/gotcha/ipdb Sphinx==1.7.5 # https://github.com/sphinx-doc/sphinx psycopg2==2.7.4 --no-binary psycopg2 # https://github.com/psycopg/psycopg2 # Testing # ------------------------------------------------------------------------------ pytest==3.6.3 # https://github.com/pytest-dev/pytest pytest-sugar==0.9.1 # https://github.com/Frozenball/pytest-sugar # Code quality … -
How do we pass values - from a list in views.py - to html
I read all the applicable django documentation (tag templates, classes, for loop, how to receive the values from list, dict etc.) and set-up a small project to learn more about Django, and python. My problem is clear as crystal: why is the function defined in views.py not passing the argument to the .html file (while receiving zero errors) Goal: Fill my html template with image-blocks for each value in list[], or dict{'x':x}. The dictionairy is made out of 3 dictionairies: Dict { 1 { X: '1', '2', '3' }, 2 { X: '1', '2', '3' }, 3 { X: '1', '2', '3' }, } all Dict.keys contain urls as strings '/folder/folder/image.png' which will be used in the src='' tag in the html). Based on what i've read the code for my loop in .html would be (i.e. for a list): {% for value in list %} <div id ="Menu-Item"> <div id ="Menu-Item-Wrap"> <img scr ={{ value}}> </div> </div> {% endfor %} I tried, and tried, but even passing a single value from a list with 1 value does not seem to work. There are no errors found, and i am able to view the page. However without any of the … -
polls_detail() takes exactly 2 arguments (1 given) issue
I'm trying to make a polls app in django and I'm making a detail page for the questions, however when opening my detail it opens in the browser, but I keep getting the "polls_detail() takes exactly 2 arguments (1 given)". Here is some of the code: models.py class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(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 __unicode__(self): return self.choice_text `````````````````````````````````````````````````````````````````````````` views.py ``````````````````````````````````````````````````````````````````````````` def polls(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'poll/polls.html', context) # Create your views here. def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/polls_detail.html', {'question': question}) ```````````````````````````````````````````````````````````````````````````` urls.py ````````````````````````````````````````````````````````````````````````````` urlpatterns = [ url(r'^polls/$',views.polls, name="polls"), url(r'^detail/$',views.detail, name="detail"), ```````````````````````````````````````````````````````````````````````````` It should return the page with the detail page with the question text on it. Thanks -
I want to delete models in the wagtail cms
I use wagtail CMS and i want to disable the models in the cms. I want to use them in the code, but the customer should could only use one of them -
Whenever debug=False in django, Heroku gives Server Error (500) and when debug=True no error
When I set debug = False I get error 500 but when it is set to True I don't get any error. I tried :- "heroku run python manage.py collectstatic" "commenting out whitenoise" "changing template and static and staticfiles locations" "COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)" "allowing everything in domain" """ Django settings for sites project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import whitenoise import dj_database_url import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #'' SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'blog', 'django_wysiwyg', 'ckeditor', 'widget_tweaks', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ] ROOT_URLCONF = 'sites.urls' SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', …