Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How hold data after submit admin site form
Here is the screenshot of my project with model.py. when i click the "save and add another button" then the values of "Lev name:" "Sem name:" "SType:" changed to its default value. what should i do? so that the given value will not change to default values. Thanks in advance. :) picture 1:before submitted to database picture 2:after submitted to database picture 3:Model.py -
Extend Admin template CSS in django
On my django site I tried unsuccesfully to change the color and a little of CSS of the header bar in the django admin site. I don't want to change anything else. The template I currently have: {% extends "admin/base_site.html" %} {% block extrastyle %} <style> #header{ background-color: #a67d3d; border-bottom: solid 3px #f5deb3; } </style> {% endblock %} This modifies the colors but makes the rest of the content blank. Navigating through the urls I managed to go beyond the main screen only to find the base colors (the blue I'm trying to change) and everything else working. I also tried using: {% extends "admin/base.html" %} to no avail. Is there a way to do this without creating a completly new Admin instance? -
Django displaying model on web page
I'm not sure where I'm going wrong. I'm creating a web store using Django/HTML/Foundations and I can't get the products that are in the database to display on the web page. I know they're in the database because when i go to admin page, they show up. Here's the HTML piece: {% for products in Product %} <div class="column"> <h5>Title: {{products.product_name}}</h5> <h5>Type: {{products.product_type}}</h5> <h5>Price: {{products.sales_price}}</h5> <img class="thumbnail" src="http://placehold.it/550x550"> </div> {% endfor %} Here's the Model: class Product(models.Model): product_name = models.CharField(max_length=255) product_type = models.CharField(max_length=100) sales_price = models.CharField(max_length=10)g def __str__(self): return self.product_name + " " + self.product_type + " " + self.sales_price The only thing in my views.py for products page is: (might be where my problem lies) def products(request): return render(request,"products.html") I'm new to django and python. Could someone please explain what's happening? Thanks -
Why is my form.cleaned_data different when I try to access in in a form.clean_field method?
Something's wrong with my data cleaning in my form. Half the data is missing from the cleaned version when I call the debugger in my individual field cleaning method. Here's a simplified version of the code: class FooBarForm(forms.Form): def __init__(self, *args, **kwargs): # call super(), do some stuff, then declare some fields: self.fields['text'] = forms.CharField(required=False, max_length=255) self.fields['foobar'] = forms.CharField(required=False, max_length=255) def clean_foobar(self): pdb.set_trace() # insert a breakpoint to inspect self.cleaned_data.keys() and self.data.keys() foobar_value = self.cleaned_data['foobar'] # dict of all the various utility functions because python doesn't have 'switch' process_foobar_type = { 'fizz': self.process_fizz, 'buzz': self.process_buzz, } try: process_foobar_type[foobar_value]() except KeyError: raise forms.ValidationError( "Incorrect foobar type: " + str(foobar_value) ) return foobar_value If I comment out clean_foobar and put a breakpoint in clean, I note that self.cleaned_data is as expected: all form fields present and accounted for. What's going on? -
Why can't I import urlpatterns from urls.py?
I am trying to create a simple Django view that will render a list of links to all of the other views in my app. my plan was to simply import my list of urlpatterns from urls.py like this from urls import urlpatterns and then generate a list of names like this def get(self, request, *args, **kwargs): context={"urlnames":[]} for up in urlpatterns: context["urlnames"].append(up.name) return render_to_response('api_list.html', context) and then render them like this {% for urlname in urlnames %} <div> <a href='{% url urlname %}' > {{urlname}} </a> </div> {% endfor %} But python cant import urlpatterns at import time. If I try to do it later, by putting the import statement in my get request, then it works fine, but why doesn't it work at import time? -
django: updating models in the background
I have a model called booking. It has a start_time and an end_time field. It also has a is_active field. Now, suppose a booking has start_time = 2017/Nov/22 12:00:00 and end_time = 2017/Nov/22 14:00:00. Now, when the server is ruuning, 1- If current time is between start_time and end_time, then is_active should be True. 2 - current time gets greater than end_time OR less than start_time of a booking, I want to set is_active = False. I want this to continuously run in the background so that it must keep the booking is_active status real time in the database. How can I do this in django? -
Save comment.id to another object
I want to save in my database the comment id which has been commented. For that I have two models: Comentario and Pregunta. Look below: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) def __str__(self): return (self.titulo) class Pregunta (models.Model): descripcion = models.CharField(max_length=150) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_pregunta = models.DateTimeField(auto_now_add=True) comentario_preguntado = models.ForeignKey(Comentario, null=True, blank=True, related_name="pregunta_set") def __str__(self): return (self.descripcion) When a comment is commented I want to save the 'comentario' id as 'comentario_preguntado' id. For that I have created the next view: views.py def ComentarioListar2 (request, Comentario_id): aa=Puesto.objects.filter(nombre_puesto=request.user.nom_puesto).values_list('etiquetas') bb=Tags.objects.filter(id__in=aa) objects=Comentario.objects.filter(tag__in=bb).exclude(autor__id=request.user.id) form = preguntaform(request.POST or None) form.instance.autor=request.user if request.method == 'POST' and form.is_valid(): form.instance.comentario_preguntado=Comentario.objects.get(pk=Comentario_id) form.save() print('id_comentario') return render(request, 'home/comentario_listar.html', {'objects': objects, 'form': form}) But I obtain this error "ComentarioListar2() missing 1 required positional argument: 'Comentario_id'" I do not know how to save in the comentario_preguntado id the id of the comment it is commented (comentario_id). thank you for your help -
Models not showing up in django admin
I've already read all the questions here, but mine is special. I've moved my admin.py file to a folder named "admin": admin +-- __init__.py | +-- generic.py | +-- admin.py and __init__.py is empty. in admin.py I have this declaration which seems not to be called: class MyAdminSite(AdminSite): site_header = _("Battlesoop's administration") admin.site.register(Game, GameAdmin) admin.site.register(Personne) admin.site.register(PersonGameStats) admin.site.register(PersonGame, PersonGameAdmin) I say it seems not to be called because when I log in as a super user, I have access to Group and User models... What am I missing? -
Django ManyToMany field as json format
I'm trying to get data as json format. I've one ManyToMany field which is returning just id. But I need that contents too. Here is my models.py class Pricing(models.Model): name = models.CharField(max_length = 100) price = models.CharField(max_length = 100) def __str__(self): return self.name+' and '+self.price class Service(models.Model): name = models.CharField(max_length=100) price = models.ManyToManyField(Pricing, blank=True) def __str__(self): return self.name And also the views.py which is returning json format data def all_service_json(request, name): data = serializers.serialize("json", Service.objects.filter(name__icontains=name)) return HttpResponse(data) Now Getting the output like below [ { "model": "myapp.service", "pk": 2, "fields": { "name": "Service name", "price": [1, 2] } } ] But want like below [ { "model": "myapp.service", "pk": 2, "fields": { "name": "Service name", "price": { 1: "Price 1", 2: "Price 2" } } } ] -
How to save an encoded pdf in a zip file using django?
I've read some posts about this problem, but most of them didn't help my case, I'm trying to save an encoded pdf in a zip file (I'm using Docraptor API for the pdf generation, which return the encoded pdf). def toZip(request, ...): ... response = docraptor_api_call() #api call to generate pdf (encoded pdf) with open('creation.pdf', 'wb') as f: f.write(response) #decode pdf with open(f.name, 'rb') as pdf: # this will download the pdf to the user # doc = HttpResponse(pdf.read(), content_type='application/pdf') # doc['Content-Disposition'] = "attachment; filename=filename.pdf" # return doc zip_io = io.BytesIO() # create zipFile zf = zipfile.ZipFile(zip_io, mode='w') # write PDF in ZIP ? save_zf = zf.write(pdf.read()) # save zip to FileField zip = ZipStore.objects.create(zip=save_zf) While trying the code on top I get this error : UnicodeEncodeError: 'charmap' codec can't encode character '\u2019' in position 43: character maps to I'm don't really get what am I doing wrong and how I should fix it, any suggestion ? -
How to create views where superuser can view and edit other user's passwords in Django?
I'm creating a control panel where the superuser can view a table of all users along with their info. I want to add the users passwords to a column, and a link to an edit form to change the password. -
Why do frameworks like RESTful Django use class-wide variables like they do?
I was looking at some Python code for the RESTful Django package/tools. Much like the class-based views, they have code that often looks like this: from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance What throws me is that, at the top, they don't define/declare vars like id, title, code as values of an instance: i.e., self.id, self.title, etc. Usually, I think of such variables as going in the init(), so they are unique to an instance. The way this is being done would seem to share the same variable across all instances of the class. But then, for example, in the update() function, we don't see validated_data.get('title', self.title) but validated_data.get('title', instance.title) where 'instance' needs to … -
Django + Factory Boy: Use Trait to create other factory objects
Is it possible to use Traits (or anything else in Factory Boy) to trigger the creation of other factory objects? For example: In a User-Purchase-Product situation, I want to create a user and inform that this user has a product purchased with something simple like that: UserFactory.create(with_purchased_product=True) Because it feels like too much trouble to call UserFactory, ProductFactory and PurchaseFactory, then crate the relationship between them. There has to be a simpler way to do that. Any help would be appreciated. -
UnicodeDecodeError: 'utf-8' codec can't decode - Python3
Im writing a django site which grabs json data from several URLS (i'm using python3). Im getting "UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 0: invalid start byte" I've looked around and it seems to be because of one or more illegal characters. I tried encoding to something else then decoding. But i'm very new to all this and i just cant get it to work. r = urlopen("http://api.electromine.fr/stats") data = json.loads(r.read()) print(data) Any help would be appreciated. Thanks! -
Website using django,haystack,whoosh. loading the search page even without search takes up to a min.
Website using django,haystack,whoosh. loading the search page even without search takes up to a min. for example, if it open 127.0.0.1/swpdocs --> it is the search page, it takes upto a min. if i try 127.0.0.1/otherpage not using haystack. it is much faster. Any idea ? really need help with this. -
Django Rest Framework: Saving ForeignKey inside OneToOne model
I have 2 models that are OneToOne related and model that is FK to 2nd model models.py class Legal(TimeStampedModel): name = models.CharField('Name', max_length=255, blank=True) class LegalCard(TimeStampedModel): legal = models.OneToOneField('Legal', related_name='legal_card', on_delete=models.CASCADE) branch = models.ForeignKey('Branch', related_name='branch', null=True) post_address = models.CharField('Post address', max_length=255, blank=True) class Branch(TimeStampedModel): name = models.CharField('Name',max_length=511) code = models.CharField('Code', max_length=6) Using DRF I made them to behave as single model so I can create or update both: serializer.py class LegalSerializer(serializers.ModelSerializer): branch = serializers.IntegerField(source='legal_card.branch', allow_null=True, required=False) post_address = serializers.CharField(source='legal_card.post_address', allow_blank=True, required=False) class Meta: model = Legal fields = ('id', 'name', 'branch', 'post_address', ) depth = 2 def create(self, validated_data): legal_card_data = validated_data.pop('legal_card', None) legal = super(LegalSerializer, self).create(validated_data) self.update_or_create_legal_card(legal, legal_card_data) return legal def update(self, instance, validated_data): legal_card_data = validated_data.pop('legal_card', None) self.update_or_create_legal_card(instance, legal_card_data) return super(LegalSerializer, self).update(instance, validated_data) def update_or_create_legal_card(self, legal, legal_card_data): LegalCard.objects.update_or_create(legal=legal, defaults=legal_card_data) views.py class LegalDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Legal.objects.all() serializer_class = LegalSerializer I'm trying to save this by sending FK as integer (I just want to post id of the branch), but I receive error ValueError: Cannot assign "2": "LegalCard.branch" must be a "Branch" instance. Is there any way to pass over only ID of the branch? Thank you -
Displaying data from tweepy python file within django
I have been playing around with the tweepy package all day. I have it working in a .py file however I would like to display twitter data I get from tweepy in a view to show information in a table. I'm fairly new to this and I amn't exactly sure what the architecture for for mapping my testingtweepy.py file live in my django environment looks like. Here is the code I am trying to show in Django as testingtweepy.py: import tweepy from tweepy.auth import OAuthHandler auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweets = api.home_timeline() for tweet in public_tweets: print(tweet.text) The goal is to grab the data from public_tweets and store it in the Django database so I can furthermore display the data at a future time. Thanks for the help! -
Django {% include %} tag displays hardcorded string but not variable
I want one template to inherit a variable from another template using the Django {% include %} tag. But it's not happening. section.html, the template to inherit from: {% block section1 %} <p>My cows are home.</p> --> {{ word_in_template }} <-- {% endblock %} index.html, which should inherit word_in_template from section.html: {% include "section.html" with word_in_template=word_in_template %} I've also tried {% include "section.html" with word_in_template=word %}. My view: def myblog(request): return render_to_response('index.html') def section(request): word = "frisky things." return render_to_response('section.html', {'word_in_template':word}) Output for section.html in Chrome: My cows are home. --> frisky things. <-- Output for index.html in Chrome: My cows are home. --> <-- I'm following this solution but it doesn't work for me. "frisky things" shows if I load section.html but it doesn't show on index.html. However, the hardcoded string My cows are home shows up on index.html. I think I'm following the documentation right too. But I'm new so maybe I'm not reading things right or something. What am I doing wrong? -
I can't get OpenID to work (openid.consumer.consumer.ProtocolError: Parameter next not in return_to URL)
I'm using Django-Allauth in my Django project. I added some Social Providers (Facebook, Google) and it works perfectly! But I'm facing a problem when trying to use OpenID providers. I've been testing it with Yahoo and AOL so far, and both end up with the same error: openid.consumer.consumer.ProtocolError: Parameter next not in return_to URL. Configuration settings.py Some relevant info of my project's setting.py file: INSTALLED_APPS = [ # Django apps 'django.contrib.auth', 'django.contrib.sites', # Allauth apps 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', # Project apps 'frontoffice.apps.FrontofficeConfig', 'middleoffice.apps.MiddleofficeConfig', ] SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) # Email sending EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'secret' EMAIL_PORT = 587 EMAIL_USE_TLS = True # Auth and allauth settings ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USERNAME_MIN_LENGTH = 3 # Redirections ACCOUNT_LOGOUT_REDIRECT_URL = '/front-office' LOGIN_REDIRECT_URL = '/front-office' # Email verification ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 # in days ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN = 30 # in seconds # Account signup ACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = True ACCOUNT_SIGNUP_FORM_CLASS = 'frontoffice.forms.UserAccountForm' # Social Accounts SOCIALACCOUNT_AUTO_SIGNUP = False SOCIALACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'openid': { 'SERVERS': [ dict(id='yahoo', name='Yahoo OpenID', openid_url='http://me.yahoo.com'), ] }, 'facebook': { 'SCOPE': ['email', ], 'METHOD': … -
How to make sure backend requests are only sent from the frontend of an app
I am using django with react native to create an iphone app and would like to ensure that all POST and GET requests to the backend can only be sent from the frontend. I am using Django-Rest with JWT authentication currently, and I do not see a need for csrf tokens if I am already using JWT. -
drop down list in django shows object for foreign key field
I am using models to auto generate a form in Django. Here is my code class Dependent(models.Model): primarystudentid = models.ForeignKey('Students', models.DO_NOTHING, db_column='PrimaryStudentID') # Field name made lowercase. dependentname = models.CharField(db_column='DependentName', max_length=100) # Field name made lowercase. relation = models.CharField(db_column='Relation', max_length=50) # Field name made lowercase. def __str__(self): return "{0}".format(self.primarystudentid) primarystudentid is an auto generated field in Students table. I have tried unicode and str. But i am still getting the value of primarystudentid in dropdown as Students object. I tried a lot of things from stack overflow and other sites but it doesn't seem to be working. Python version Python 2.7.13 Django version 1.9.13 Any help is appreciated! -
Mixin for changing the behaviour of a get method in Django class based view
I'm attempting to write a mixin for setting a translation language based on the language set in the user Profile model. When a get request comes in, the mixin should set a language to user language, get response from the view that adds the mixin, and then set the language back to what it was before. I wrote the following mixin, which is invoked, but it's get method is not invoked. What am I doing wrong? class SetUserLanguageMixin(object): def get(self, request): current_language = translation.get_language() try: translation.activate(request.user.profile.language) response = super(SetUserLanguageMixin, self).get(request) finally: translation.activate(current_language) return response class SomeView(LoggingMixin, APIView, SetUserLanguageMixin): def get(self, request): ... return Response(data, status=status.HTTP_200_OK) -
Calculation sum of two fields to filter entries
I have a model class called Foo, with the following fields start and duration. class Foo(models.Model): start = models.DateTimeField() duration = models.DurationField() I want to filter all the entries from the Foo table by checking that the start plus duration is less than a certain time. -
'NoneType' object has no attribute 'has_header'
I use Django 1.11.3 and I try to redirect user after "Save" button is pressed on some model in admin. So, in my admin.py file I have to following code (part of it): from django.contrib import admin from django.db.models.signals import post_save from django.dispatch import receiver from django.http import HttpResponseRedirect from .models import Info class InfoAdmin(admin.ModelAdmin): def response_change(self, request, object, form_url=''): if(object.type == 1): return HttpResponseRedirect('/admin/pict/data/add/?info=' + str(object.info)) else: return HttpResponseRedirect('/admin/pict/article/') admin.site.register(Info, InfoAdmin) but I get the following error after I press the button: AttributeError at /admin/pict/info/58/change/ 'NoneType' object has no attribute 'has_header' I tried also with redirect and HttpResponse, but the error persists. Full traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/pict/info/58/change/ Django Version: 1.11.3 Python Version: 3.5.2 Installed Applications: ['pict.apps.PictConfig', 'suit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'massadmin'] Installed 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'] Traceback: File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 58. add_never_cache_headers(response) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/utils/cache.py" in add_never_cache_headers 274. patch_response_headers(response, cache_timeout=-1) File "/Users/mick/.virtualenvs/gbs/lib/python3.5/site-packages/django/utils/cache.py" … -
Cron job to remove empty folders with a Python virtual environment
I have a script which when called from the command line to remove empty folders, works with no problem. When on the server (Ubuntu) I activate the virtual environment, and navigate to the project something like cd djangoprojects/some_project and then run python core/remove_empty_folders.py media False All works fine. Then I wanted to implement the same script using cron. I have made the above script executable first. This is what I think should work (have tried many variants!) (all on one line!) /home/username/virtualenvs/some_project_env/bin/python /home/username/djangoprojects/some_project python core/remove_empty_folders.py media False Ownership of the media folder is www-data However, it's just not working, and I am not sure why? I can't get any feedback from cron as to what the problem may be so hoping someone can help on this. Many thanks