Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.8. Can't show an image in form
I'm using this package https://github.com/tomwalker/django_quiz to make a web quiz app. I need to add images to the multiplechoice answers. So, I added to the Answers model: image = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Image")) Images are uploading and saving into the DB. The part that shows choosable answers are shown in template like this: {% for answer in form.answers %} <li class="list-group-item"> {{ answer }} </li> {% endfor %} I changed it to: {% for answer in form.answers %} <li class="list-group-item"> {{ answer }} <img src="{{ answer.image.url }}" alt="" /> </li> {% endfor %} But it's doesn't work. It renders This is forms.py: class QuestionForm(forms.Form): def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) choice_list = [x for x in question.get_answers_list()] self.fields["answers"] = forms.ChoiceField(choices=choice_list, widget=RadioSelect) And this is model: def get_answers_list(self): return [(answer.id, answer.content) for answer in self.order_answers(Answer.objects.filter(question=self))] -
Django migration sql for conditional triggers
I want to create a trigger that only inserts into table when the condition is met. I've tried using various combinations of IF/BEGIN/END and WHERE, but Django returns me an SQL syntax error each time. Here, type_user_id refers to the person who triggers the like, and user_id refers to the person who receives the notification. It should only trigger when they are not the same person. operations = [ migrations.RunSQL( "DROP TRIGGER like_notification", """ CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article FOR EACH ROW IF (select user_id from channel WHERE channel_id IN (SELECT channel_id FROM article WHERE article_id = NEW.article_id)) <> NEW.user_id BEGIN INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id) VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, (SELECT user_id from channel WHERE channel_id IN (SELECT channel_id FROM article WHERE article_id = NEW.article_id) ) ) END; """ ) ] and CREATE TRIGGER like_notification AFTER INSERT ON user_likes_article FOR EACH ROW BEGIN DECLARE @user_same Boolean; SELECT 1 into @user_same FROM channel WHERE channel_id IN (select channel_id FROM article where article_id = NEW.article_id) AND user_id = NEW.user_id; IF @user_same <> 1 THEN INSERT INTO notification (type, type_id, article_id, is_read, type_user_id, user_id,) VALUES ('like', NEW.article_id, NEW.article_id, false, NEW.user_id, ( SELECT user_id from channel … -
what is the use of django DRF Mixins, where i can use it in my django projects
What is the best use case for Django Rest Framework(DRF) Mixins?DRF documentation. This Documentation is giving just an overview. So please give me a code snippet or an example where Mixins plays a Major role to solve the problem. -
How access a context value from a variable in django template
I have a Question model that I am passing as a context to the template class Question(models.Model): possible_answer1 = models.TextField( 'Possible Answer 1', max_length=1000, default='none' ) possible_answer2 = models.TextField( 'Possible Answer 2', max_length=1000, default='none', blank=True ) possible_answer3 = models.TextField( 'Possible Answer 3', max_length=1000, default='none', blank=True ) possible_answer4 = models.TextField( 'Possible Answer 4', max_length=1000, default='none', blank=True ) possible_answer5 = models.TextField( 'Possible Answer 5', max_length=1000, default='none', blank=True ) possible_answer6 = models.TextField( 'Possible Answer 6', max_length=1000, default='none', blank=True ) I can access all the answer object no problem if I use {{ context.this_question.question.possible_answer1 }} {{ context.this_question.question.possible_answer2 }} . . {{ context.this_question.question.possible_answer6 }} The problem is that I don't need all 6 answers to be displayed all the time so I was trying to build for loop that would only dispay what I need at a certain time based on the following thread using the with tag How to concatenate strings in django templates?1 . In the example below mylist contain four elements so I tried this {% for x in mylist %} {% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %} {{ possible_answer }} {% endwith %} {% endfor %} In the hope that it would generate {{ context.this_question.question.possible_answer1 }} {{ context.this_question.question.possible_answer2 }} {{ context.this_question.question.possible_answer3 }} {{ context.this_question.question.possible_answer4 … -
Is there a way to elegantly "swap" rows in all foreign key and many to many fields in django?
I have a class let's call it Entity it's a container for a label and a type and then I have many other models like Store, Purchase... And they have a relationship like so: class Store(Model): store_name = TextField() entities = ManyToManyField(Entity) class Purchase(Model): datetime = DatetimeField(auto=True) entity = ForeignKeyField(Entity) In this case, say that I have an entity that I end up wanting to "swap" for instance, at some time I had "CocaCola" and then I have "Coca Cola", the user decides hey these two are the same, let's "merge them", effectively what I need to do is delete CocaCola or Coca Cola and swap all the keys out so.... for p in Purchase.objects.filter(entity=cocacola_entity): p.entity = coca_cola_entity p.save() for s in Purchase.objects.filter(entities=cocacola_entity): s.entities.remove(cocacola_entity) s.entities.add(coca_cola_entity) s.save() cocacola_entity.delete() Is there a better way to handle this in a global context? I.e. "Django magically fetch me EVERYTHING with this row as a foreign key and swap it with the other one) -
what is the point of 'timeline' in array or param for get_news_feed?
I went through all tutorials and docs which stream-django provided. And there was one thing that I could't understand. I can't find the differences between these feed_manager methods. # (1) feed = feed_manager.get_news_feed('timeline’, request.id) # (2) feed = feed_manager.get_news_feed(request.id)[‘timeline’] # (3) feed = feed_manager.get_news_feed(request.id) Could you explain the difference? Are they doing exactly same thing? timeline means flat feed, then why do we put timeline in param? Thank you -
Gcloud app deploy. Stopping Master
I am trying to deploy my app to the app engine but for some reason, I can't do so. My logs says Shutting down master Reason: worker failed to boot I think it has something to do with gunicorn. How do I go about this? -
Django writing view with sudomain
With my (Django v 1.17) project I am using django-subdomains. I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html. My issue that I wrote a new view called example for the sub-domain but when I open the url https://subdomain.domain.com/exmaple I will get error Page not found (404). Hete is my code: settings.py INSTALLED_APPS = [ 'subdomain' ] SUBDOMAIN_URLCONFS = { 'subdomain': 'subdomain.urls', } subdomain/urls.py from django.conf.urls import url, include from . import views from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$example', views.example, name='example'), ] subdomain/views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse def index(request): template = loader.get_template('subdomain/index.html') return HttpResponse(template.render()) def example(request): template = loader.get_template('subdomain/example.html') return HttpResponse(template.render()) Error: Page not found (404) Request Method: GET Request URL: https://subdomain.domain.com/example Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order: 1. ^$ [name='index'] 2. ^$example [name='example'] The current path, econ, didn't match any of these. Please Advice how to fix this issue and write view for sub-domain. Here is the documents for the django-subdomains library django-subdomains -
Get error in django project?
Get this error. NoReverseMatch at /account/login/ Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name This is my github project https://github.com/Loctarogar/Django-by-Example -
Configuration Logging in Django for print in console
I am following these instructions from https://docs.djangoproject.com/en/1.11/topics/logging/ In view.py I added: import logging logger = logging.getLogger(__name__) def update(request): if request.method == 'POST': logger.info('test') and settings.py (because I want to print info in console) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': sys.stdout }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } -
unable to upload image via ModelForm in django
when i try to submit my form it said "This field is required." for an image even though i provide the image and other details to it. forms.py file from django.forms import ModelForm from .models import Status class CreatePost(ModelForm): class Meta: model=Status fields = ["username","text","privacy","image"] models.py file class Status(models.Model): title=models.CharField(max_length=20,default="updated status") username = models.ForeignKey('User',on_delete=models.CASCADE) #username = models.CharField(max_length=20) text = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="media/image",null=True) time = models.DateTimeField(auto_now=True) privacy = models.CharField(max_length=5, blank=True, null=True) gid = models.IntegerField(blank=True, null=True) dp = models.SmallIntegerField(blank=True, null=True) class Meta: #unique_together = (('username', 'dp'),) #managed = False db_table = 'status' view.py def create_post(request): form=CreatePost(request.POST or None) if request.method=="POST": if form.is_valid(): instance=form.save(commit=False) instance.time=time.time() instance.save() return redirect('post',) return render(request,"uposts/createpost.html",{'form':form}) createpost.html {% extends "friendsbook/structure.html" %} {% block content %} <form action="" method="post"> {%csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> {% endblock %} look what it said after clicking on save button enter image description here i am only taking 4 fields in form because all other fields can be null.For time field i took care of that in views.py by giving the time there. Please help me.I tried everything by myself but nothing helped !. -
Django doesnt show media
Production server doesn't show media. settings.py: MEDIA_URL = '/media/' MEDIA_ROOT= os.path.join(os.path.dirname(BASE_DIR), "media_root") ways (venv) split@ubuntu:~$ ls logs media_root mysite requirements.txt static_root venv (venv) split@ubuntu:~$ cd media_root/ (venv) split@ubuntu:~/media_root$ ls 1 2 None (venv) split@ubuntu:~/media_root$ inside None there are pictures I go to ip/media/None/dd.jpg and got Not Found The requested URL /media/None/dd.jpg was not found on this server. All work good on the local machine. -
I dont know what is wrong with my django
I dont know what is wrong, and I am desperates with no sleep int two days because of this error. I dont know where does it come from, and it wouldn let me know what did i do wrong. for your information I am learning using django with python, my version of django is 1.11 and my version of python is 2.7 . Please help me, this is what i got from my code Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/commands/check.py", line 68, in handle fail_level=getattr(checks, options['fail_level']), File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 30, in check_resolver warnings.extend(check_pattern_name(pattern)) File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 120, in check_pattern_name if pattern.name is not None and ":" in pattern.name: TypeError: argument of type 'function' is not iterable See? it would not let … -
how constantly run a script beside django
I have a Django website running and i am looking for a way to run a script that constantly fetch some data from the Internet and insert them into my Django app database. how can i keep script running as long as server is up ? (no need to start it manually - and don't want to stop it at all!!) i guess celery is not what i want !?! ,and how can i use Django ORM in this script for inserting data into db? i tried threading but think its should be started by calling the script or .. -
ValueError while making db migrations in django
I am new to django and i tried changing tag field from char field to TaggableManager() models.py class UserBookmark(models.Model): user = models.ForeignKey(User) bookmark = models.URLField() tag = TaggableManager() def __str__(self): return '%i %s %s'%(self.id,self.user,self.bookmark) when i run python manage.py migrate, i get this error: ValueError: Cannot alter field bookmark.UserBookmark.tags into bookmark.UserBookmark.tags - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) How can i remove this error? -
Django Generic Model Formsets
So I have a site where users are capable of registering devices and then registering commands to those devices. These commands have an associated widget (button, slider, etc) that determine the unique properties that the command has. I am trying to figure out the most generic way to use the model formsets in my application. I have things working, where I create a model_formset for each ModelForm, and get data from each model to place in the formset, and then show it in my template. What I would really like to do is something like this: command_formset = modelformset_factory(Command, extra=0, fields='__all__') formset = command_formset(queryset=Command.objects.filter(device_id=device_id)) Where I get all of my commands (which returns both buttons and sliders) and then make a single command_formset, which has all command objects. In this case it does part of what I am looking for, where I can query my model and get all button and slider commands, but the formset only includes the fields from command - so the min and max value for the slider are lost. Is something like this possible? Here is my more complete code: Models class Command(models.Model): command_name = models.CharField(max_length=100) command = models.CharField(max_length=100) command_url = models.CharField(max_length=100) command_type = models.CharField(max_length=100) … -
22003 8115 error with overflow bigint id
My code runs good in a single test. The id starts with 1 and increment with 1. However when I test the whole run in django, I've got this error. For example an id 601193234094856941 that was inserted. In the whole run I have not more than 10000 inserts. We only have this problem in our development environment. We have an work around but we want to understand how it works and a solution. ('22003', '[22003] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Arithmetic overflow error converting expression to data type int. (8115) (SQLExecDirectW)')", -
Handling many admins in django?
If a company has departments A, B, C, D ...and each have to have a admin different . Only admins of the particular department can create, update and delete the information of their respective departments. My question is how to implement to create API ? -
Check for duplicates in pandas df from Django db
I have a Django db that I want to only add to if it the new input is different from the data already in there. I have a function to check for duplicate rows that should: read the current db put the current db into a pandas dataframe current_df if that dataframe is empty, it should just return the whole of the new input weatherstats_df that was passed to the function for checking without changing it if the df current_df is not empty, try an inner merge with weatherstats_df and return that if that doesn't work, return an empty df I'm getting a problem where my function is changing the data at the first stage, when it should just pass back an unaltered df. The function add_to_db(weatherstats_df) should be calling checkforduplicates(weatherstats_df), but when there's nothing in my db it should be returning the unaltered db. def checkforduplicates(weatherstats_df): qs = WeatherStatistics.objects.all() current_df = read_frame(qs) if current_df.empty: return weatherstats_df else: current_df = current_df.drop(current_df.columns[0], axis=1) print(current_df) try: weatherstats_df = pd.merge(current_df,weatherstats_df, how='inner') return weatherstats_df except: weatherstats_df = pd.DataFrame() return weatherstats_df def add_to_db(weatherstats_df): print(weatherstats_df) weatherstats_df = checkforduplicates(weatherstats_df) if not weatherstats_df.empty:... What am I doing wrong? -
Django does not redirect from one view/url to another
I will start with explanation of what I want to achieve. Basically I want to display in my view(prefs) an array items on a page that each item looks like button and if clicked it redirects to a view(results) and passes an argument(i.e itself) My views.py look like this def prefs(request): if request.method == 'POST': for i in user_queryset(request): #this function returns an array if i in request.POST.values(): return redirect(reverse('results',kwargs={'UserChoice':i})) elif not request.user.is_authenticated(): return HttpResponse('Please login or sign-up to use this feature') else: uid = request.user return render(request,'test.html',{'form':user_queryset(request,uid)}) def results(request,UserChoice): if request.method =='GET': return render(request,'test2.html',{'objects':request_places(request,UserChoice)}) else: return HttpResponse('Hello, World!') my urls.py url(r'places/$',views.prefs,name='prefs'), url(r'^places/results/(?P<UserChoice>[^\/]*)/$', views.results, name='results') and my templates <ul> <li> <form role="form" action="" method="post"> {% for obj in form %} <!--<input type="text" name="{{ obj }} ">--> <input type="submit" value="{{ obj }}"> </form> </li> {% endfor %} </ul> -
django template white page
Help me after add my {% extends "menu.html" %> the rest of my page is white I can not see my content anymore resultat -
Issue with Django logout URL redirection
I have configured login and logout redirect setting in Django settings as below - LOGOUT_REDIRECT_URL = '/login/' LOGIN_REDIRECT_URL = '/locations/' However, after logging out the redirection is done on the next= parameter, ie., the url is redirected to the same page from where logout is clicked. For the reference, here is login/logout URL from my urls.py - url(r'^', include('rest_framework.urls', namespace='rest_framework')), PS: I am using Django 1.11 & DRF 3.7.3 -
Django testing form with modelchoicefield
I amended a form to make a ModelChoiceField so that users can only select categories that they have set up. This is working correctly when I run my app in the browser but fails the test (in that it says the form is not valid), which passes if you remove the ModelChoiceField and allow it to display all categories from the model. I am happy that the code for the form works as expected and required in the browser; it is the test case that I would like to fix. I imagine there is something obvious I can't see because I have looked at it too many times. Can anyone help please? Extract from test case def setUp(self): user = User.objects.create(username='user', password='') self.category = Category.objects.create(id=1, user=user, title='category1') self.myitem = MyModel.objects.create(id=1, user=user, title='title1', amount=10, category=self.category) def test_form_validation_with_valid_data(self): user = User.objects.get(username='user') now = timezone.now() form = MyModelForm({'title': 'title1', 'category': 1, 'amount': 100, 'date': now,}, user) self.assertTrue(form.is_valid()) Extract from forms.py class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ('title', 'category', 'amount', 'date',) category = forms.ModelChoiceField(queryset=None) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(MyModelForm, self).__init__(*args, **kwargs) self.fields['category'].queryset = Category.objects.filter(user=self.user) -
Django-carousel bootstrap
Since i am new in django stuff i finally manage to add carousel slider in my website but my slider is not working. It stucks in first image and doesn't slides to another image. However viewing source in my local port shows all image path but in red text. Please help Here is my code base.html <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data- ride="carousel"> <!-- Indicators--> <ol class="carousel-indicators"> {% for item in slider %} <li data-target="" data-slide-to="{{item.id|add:-1}}" {%if forloop.first %}class="active"{%endif%}></li> {% endfor %} </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for item in slider %} {%if forloop.first %} <div class="carousel-item active">{%else %}<div class="carousel-item">{%endif%} <img class="d-block w-100"src="media/{{item.slider_image}}" alt="{{item.display_title}"> <div class="carousel-caption d-none d-md-block"> <h3>{{item.display_title}}</h3> </div> </div> {%endfor%} </div> <!--left and right Controls --> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> source view code in my local port <div class="container"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <!-- Indicators--> <ol class="carousel-indicators"> <li data-target="" data-slide-to="3" class="active"></li> <li data-target="" data-slide-to="4" ></li> <li data-target="" data-slide-to="5" ></li> <li data-target="" data-slide-to="6" ></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100"src="media/slider/2017/12/04/DAKU.png" alt="{{item.display_title}"> <div class="carousel-caption d-none … -
Optimal project organization and querysets
I have 2 models Company and Product with FK on Product: class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) In case of a View that will gather company products what is the optimal approach(use infor form both models): 1) add the View in companies app and as queryset use: Company.objects.prefetch_related('products').get(pk=company_pk) 2) add the View in products app and as queryset use: Product.objects.select_related('company').filter(company=company_pk) What about ordering can be chained with prefetch or select ?