Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom serializer response
Is there a way of getting django API response as {"1":"country1", "2":"country2"} instead of [{"id":1,"country":"country1"},{"id":2,"country":"country2"}] -
How to resolve the Migration Errors?
I have two models ie; Model1 and Model2. One field in Model2 acted as a foreign key of Model1. Here Primary Key of Model1 is 'id'. But now i modified the primary key field, removed id and added field called demo_num as primary key.Now my models looke like class Model1(models.Model): dem_num = models.IntegerField(primary_key=True) class Model2(models.Model): dem_fk = models.Foreignkey('Model1') but when i am doing migrate it is showing error like, django.db.utils.OperationalError: (1829, "Cannot drop column 'id': needed in a foreign key constraint of table Model2) How to solve this problem? Note: Without deleting migrations file I want to do it -
changin from function based view to class based view - Django
This is my function based view def reset(request): return password_reset(request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) TO change this view to the class based view I have to written this class ResetPassword(View): def get(self, request): return password_reset(self.request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) def post(self, request): return password_reset(self.request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) Anything wrong here? Thank you. Code works perfectly -
Failing to connect Facebook with Django using AllAuth library
After trying to connect the ALLAUTH library with Django suing the post: https://medium.com/@jinkwon711/django-allauth-facebook-login-b536444cbc6b I went for the documentation and for the information, it was of no use to me. I want to know the simplest way to connect my facebook profile with AllAuth and Django 1.11.5 Kindly, let me know as I am struggling to get the connect with Facebook and Django 1.11.5. -
How do you put data from one form as a default for another in the same view in django?
Basically, I am new to Django. I am attempting to create a timesheet website where the user would select a task for the week and then add the hours they worked for each day that week. However, each day is intended to be stored in an individual record. How would you create a form that would take only take one task input, but loop through and create 5 records, one for each day? -
I get no log message from django running heroku
I'm running a Django site on Heroku, and the server returns a 500 error, but no reason why. All I get from heroku logs is this message: heroku[router]: at=info method=GET path="/accounts/login/" host=dagenssalg.herokuapp.com request_id=02ec11bf-ea26-4f98- ab5a-270147167d42 fwd="87.57.162.154" dyno=web.1 connect=0ms service=29ms status=500 bytes=234 protocol=https DEBUG is set to false: DEBUG = False Is there any way to display the detail of the error? Best regards Kresten -
Customize django_admin_log change message
I am trying to make the best use of the django_admin_log for our project. In short, we want (on the ADMIN side) the user to be FORCED to input a detailed CHANGE MESSAGE that overrides the existing change log entry. For example, when I add a new record to a table/model, the change message just reads "added" / "deleted" etc... but what I am wanting is for this to be much more detailed.. does anyone have any experience or an idea for a solution here? We're at a loss as to the best way to approach it. More specifically - is there a way to re-direct when a user clicks "save" to the latest django_admin_log entry?? -
Can I pass the data to base template ?
I have a base template, and every other template extends from it. but the base.html, how can I set the data in it? This is code snippet of base.html: ... <li class="dropdown bell"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class=" fa fa-user-circle"></i>191457****@qq.com</a> <ul class="dropdown-menu nav-menu"> ... I want to change the 191457****@qq.com to the passed data, it should be flexible, variable, that is take out from database. There is static html now. I tried in every template to set it, but you know this is a lot of repetition operation, if there is a simple method, I think python will be worthy of the name. -
Localization doesn't work
I created a Django site with localization built in, using python manage.py runserver to test it. But after setting it live with Apache/WSGI, the localization doesn't work correctly. I can see dates being translated (so somehow it knows the current language), but all my site-specific strings are untranslated. I have no idea where to look though on where to fix this. -
ValueError: Cannot query "": Must be "User" instance
I am trying to create a follower system where user can get to follow investor not between user and user but between user and investor. However I am getting an error. I am still not sure if i have to create a different table for follow or not but here is the code. Please share your idea for better modelling of follow system between user and investor class Investor(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False, help_text='Full Name') followers = models.ManyToManyField( User, related_name='followers', blank=True) @classmethod def follow_investor(cls, investor, follower): investor, created = cls.objects.get_or_create(investor=investor) investor.followers.add(follower) @classmethod def unfollow_investor(cls, investor, follower): investor, created = cls.objects.get_or_create(investor=investor) investor.followers.remove(follower) url(r'^investor/(?P<action>.+)/(?P<slug>[-\w]+)$', views.follow_unfollow_investor, name="follow-unfollow-investor"), def follow_unfollow_investor(request, action, slug=None): follower = request.user investor = Investor.objects.get(slug=slug) if action == "add": Investor.follow_investor(investor, follower) elif action == "remove": Investor.unfollow_investor(user, follower) return redirect('/') -
Django file sharing application (issues providing link to user)
i am creating file sharing app. I am able to upload files but unable to provide its download link to user. Please find below view, def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) #instance=form_new.save(commit=False) #instance.save() if form_new.is_valid(): instance = form_new.save(commit=False) instance.user_uploaded=request.user instance.save() return redirect('in') else: form_new = Fileupload() data = user_files.objects.filter(user_uploaded=request.user) args = {'form_new': form_new, 'data': data}#, 'url': form_new.get_absolute_url()} return render(request, 'accounts/in.html', args) and model.py is, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) template is , <form action="." method="POST" enctype="multipart/form-data" > <h3>Welcome to DropBox<br><br></h3> {% csrf_token %} {{form_new.as_p}} <p><input type="submit" value="Save" ></p> <br> <a href="{% url 'logout' %}">Logout</a> {%else%} <p>You must login first</p> <a href="{% url 'login' %}">Logout</a> {% endif %} <br><br> S <a href="{% url 'share' %}">Share Files</a> <br><br> User is : {{request.user}} {% for da in data %} <h3>{{da.Filename}} {{da.Browse}} </h3> {% endfor %} </form> Requesting you to please guide me how to provide download link for uploaded link, i am stuck at this point. thanks in advance. -
IO error after I change my template settings
Im new to django, I am trying to make an e-commerce site. Since I always received errors each time I try to do makemigrations I have removed TEMPLATE_DIRS and included it to TEMPLATES settings are stated below: #TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", 'templates', ), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ (os.path.join(os.path.dirname(BASE_DIR), "static", 'templates',), ) after I change it my site returned to this kind of error, what could be the problem Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.11.6 Exception Type: IOError Exception Value: [Errno 22] Invalid argument: u"C:\\trydjango\\src\\ ('C:\\trydjango\\static\\templates',)\\admin\\index.html" -
How to limit field choices related to another table in database?
I'm working on simple expenses manager. Every user is able to add/remove/edit an Operation, which represents expense or earning. However I have noticed a bug - while adding new Operation it is possible to choose other users Accounts and Categories. Here is my Operation model: class Operation(models.Model): def get_category_color(self): return Category.objects.get(name=self.category).color types_tuples = ((-1, 'expense'), (1, 'earning')) user = models.ForeignKey(User) account = models.ForeignKey(Account) category = models.ForeignKey(Category) date = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2) type = models.IntegerField(choices=types_tuples) currency = models.CharField(max_length=3) color = property(get_category_color) OperationCreate view: class OperationCreate(CreateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def form_valid(self, form): operation = form.save(commit=False) operation.currency = Account.objects.get(pk=form.instance.account_id).currency self.update_account_balance(form) form.instance.user = self.request.user return super(OperationCreate, self).form_valid(form) and OperationForm: class OperationForm(ModelForm): class Meta: model = Operation fields = ['account', 'type', 'category', 'date', 'amount'] The question is how can I limit choices for Account and Category that are available during posting new Operation? I would like user to see only those which are related to his/her account. I tried limit_choices_to as a parameter for models.ForeignKey(Account) and models.ForeignKey(Category) in Operation model but couldn't make it work that way. I assume I need to use a query which will return only Accounts and Categories related to the current … -
How django save method works? Sometimes it creates new record and sometimes update, why?
I want to ask why this code: object(group_id=group_id, sr=11).save() updates all records with particular group_id and set its sr to 11, whereas the following code creates a new record in the database instead of updating existing records. g = object(group_id=group_id, sr=11).save() g.save() The code above creates new record in the database whereas the first code update existing records, why? What is the difference? Thanks for your answers. -
Saving django form inside for loop
This question is related to this. I'm planning to save values from my form fields. Below is my code for loop code: def form_valid(self, form): tooth = [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38] tooth.reverse() mytooth = {} pt = self.kwargs['pk'] for t in tooth: mytooth = self.request.POST.getlist('tooth_' + str(t), []) mytooth = " ".join(mytooth) form.instance.status = me form.instance.position = t form.instance.patient = PatientInfo.objects.get(pk=pt) return super(DentalRecordCreateView, self).form_valid(form) The problem is that I can see values using show = str(t) + mytooth messages.success(self.request, show) # display values but only the field form.instance.patient has value in my db. What am I missing here? -
Django save user as inactive
Why is doing something so simple seem so complicated in Django? It started with setting up a user model where email is used to login, a pain... Now I am trying to save a user as user.is_active = False but it is saved as active. Any tips very welcome or any other guidance as Django has been quite a painful experience so far compared to Flask. Note, I have also tried @receiver(pre_save, sender=get_user_model()) below. views.py ... from .models import Story, MyUser from .forms import SignupForm, LoginForm from django.dispatch import receiver from django.db.models.signals import pre_save @receiver(pre_save, sender=MyUser) def set_new_user_inactive(sender, instance, **kwargs): if instance._state.adding is True: print("Creating Inactive User") instance.is_active = False else: print("Updating User Record") ... def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = get_user_model() user.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'], ) return HttpResponseRedirect(reverse('index')) else: form = SignupForm() return render(request, 'drillapp/signup.html', {'form': form}) ... models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager ... class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) self.username = username user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): user = self.create_user( email, password=password, ) user.is_admin = True … -
Django Error: invalid literal for int() with base 10: after inserting {% providers_media_js %}
I m preparing a Django Application where I need to have a Facebook Auth and process various data from the facebook posts. So I am first trying to authorize using the AllAuth library of Django. I have followed the process from the blog: https://medium.com/@jinkwon711/django-allauth-facebook-login-b536444cbc6b. Now I after running I am getting the following error: ValueError at / invalid literal for int() with base 10: 'WebsiteIP:port' Request Method: GET Request URL: http://WebsiteIP:port/ Django Version: 1.11.5 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'WebsiteIP:port' Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py in get_prep_value, line 966 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/ubuntu/PersonalityWithFacebook', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Mon, 9 Oct 2017 08:19:13 +0000 This problem started when I have inserted the code: {% load socialaccount %} {% providers_media_js %} If I remove just this single line the website is up but not function-able: {% providers_media_js %} So kindly, let me know what I am missing. Here is the complete trace of teh error: https://gist.github.com/JafferWilson/a053e133474472c02f7507c634f7387c -
I am using django-oauth2-provider to generate token. But i want to keep one session at a time
I am using django-oauth2-provider to generate token. But i want to keep one session at a time. Like if a user login at one device and request another login from other device then the initial token should be expired. Can I handle this thing with django-oauth2-privder package -
Compare user related objects in Django templates
I'm working on a Django project in which I have an article model, form, view. The article has user field in its model and related_name as 'tagging'. Now, i want to hide the article which is already created by user in Django templates, How can I achieve this? Something like: {% if tag in articles %} Help, me, please! Thanks in advance! -
'Table doesn't exist' on django makemigrations
On a django 1.11 application which uses mysql , I have 3 apps and in one of them I have a 'Country' model: class Country(models.Model): countryId = models.AutoField(primary_key=True, db_column='country_id') name = models.CharField(max_length=100) code = models.CharField(max_length=3) class Meta: db_table = 'country' Whaen I try to makemigrations I get this error: django.db.utils.ProgrammingError: (1146, "Table 'dbname.country' doesn't exist") If I run making migration for another app which is not related to this model and its database table using ./manage.py makemigrations another_app, I still get this error. -
How to test Django Form ImageField
I want to test my imageform, I provide all required data, still it giving me an error. Does anyone know, how to test form's ImageField? my model is class Image(CustomModel): path = models.ImageField(_('Path'), upload_to=get_file_path, help_text=_('Represents a path of an image.')) caption = models.CharField(_('Caption'), max_length=128, null=False, blank=False, db_column='caption', help_text=_('128 characters max.') meta_info = models.TextField(_("Image MetaInfo"), null=False, blank=False, help_text=_('Image meta info'), default='{}', db_column='meta_info') created_at = models.DateTimeField(_('Created At'), null=False, db_column='created_at', blank=False, help_text=_('Date time at which image was created.'), default=datetime.now()) My form: class ImageForm(forms.ModelForm): class Meta: """ Meta class for Image form """ model = Image fields = ('caption', 'path', 'status','meta_info') widgets = { 'meta_info': forms.HiddenInput(), } class ImageForm(forms.ModelForm): My test method: def test_form_valid(self): """ """ self.tmp_dir = tempfile.mkdtemp() path = os.path.join(self.tmp_dir,"a376140b-054f-4329-82e1-f271af5cfcaf.png") form = ImageForm({'caption':'image', 'path':path, 'status':'A', "created_at":timezone.now(), 'meta_info':"{\"id\":2,\"type\":\"Q\",\"lang_id\":1}"}) print(form.is_valid()) print(form.errors) assert form.is_valid(), 'should be valid' Traceback: def test_form_valid(self): """ """ self.tmp_dir = tempfile.mkdtemp() path = os.path.join(self.tmp_dir,"a376140b-054f-4329-82e1-f271af5cfcaf.png") form = ImageForm({'caption':'image', 'path':path, 'status':'A', "created_at":timezone.now(), 'meta_info':"{\"id\":2,\"type\":\"Q\",\"lang_id\":1}"}) print(form.is_valid()) print(form.errors) > assert form.is_valid(), 'should be valid' E AssertionError: should be valid E assert False E + where False = <bound method BaseForm.is_valid of <ImageForm bound=True, valid=False, fields=(caption;path;status;meta_info)>>() E + where <bound method BaseForm.is_valid of <ImageForm bound=True, valid=False, fields=(caption;path;status;meta_info)>> = <ImageForm bound=True, valid=False, fields=(caption;path;status;meta_info)>.is_valid droana/apps/test_manager/test/test_views.py:269: AssertionError ---------------------------- Captured stdout … -
Extending Templates from project root Django
In my root folder I have a templates folder, with a base.html file inside of it. I have an app with some html, and I want it to extend base.html. Here's the code inside base.html: <header><h3>Header here</h3></header> {% block content %} {% endblock %} <footer><h3>Footer here</h3></footer> The code inside app is: {% extends base.html %} {% block content %} <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> {% endblock %} For some reason I'm getting an Invalid template name in 'extends' tag error and I don't know why. I've updated my settings.py file to this from searching online but still doesn't work: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Db_index for a char field where existence of arbitrary words will be sought
Django==1.11.5 I have created a search form to check whether a title contains words, doesn't contain words, is empty or is not empty. Partially I show these queries here. Could you help me understand whether I should organize db_index=True for the title field? models.py class Frame(models.Model): title = models.CharField(max_length=250, blank=True, null=False, default="", verbose_name=_('title')) views.py def _chain_title(self, input_data, queryset): title_and_absent = input_data.get("title_and_absent") if title_and_absent: queryset = queryset.filter(title="") title_not_absent = input_data.get("title_not_absent") if title_not_absent: queryset = queryset.exclude(title="") title_and = input_data.get("title_and_input") if title_and: title_and = title_and.split() for title_str in title_and: queryset = queryset.filter(title__icontains=title_str) -
exclusion of two different querysets
I am making a GK test interface with django. In this, the questions once submitted to a user should not appear again. This table stores all the questions once submitted, and all other data related to that. class UserLog(models.Model): session = models.ForeignKey(to = UserTestSession, default = None) question = models.OneToOneField(to = MCQuestion) user = models.ForeignKey(to = User) selected_option = models.IntegerField(blank=True,null=True) answer_status = models.BooleanField(default = True) quest_submit_time = models.DateTimeField(blank=False) ans_submit_time = models.DateTimeField(blank = True,null=True) def getDiff(self): diff = self.quest_submit_time - self.ans_submit_time return divmod(diff.days * 86400 + diff.seconds, 60) time_elapsed = property(getDiff) def __str__(self): return str(self.user) + " " + str(self.question) class Meta: unique_together = ('question','user',) I tried this line to exclude. unsubmitted_questions = list(all_questions.exclude(question__in = submitted_questions)) -
Shall I delete unused files created automatically?
Django==1.11.5 In the project there are unused files. For example, I use Django login/logout function's but I have created a special login template. I don't use: models.py, views.py, tests.py. But I did register the app for Django to find templates. Could you tell me whether I should delete these unused files? Django style guide keeps silent on this matter. Deleteing seems logical. But I decided to ask you just to be on the safe side.