Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model - how to go about this concept
I have a product model with the following: class Product(models.Model): name = models.CharField(max_length=255) handle = models.CharField(max_length=55) summary = models.CharField(max_length=255, blank=True) category = models.ForeignKey(Category) Above is just the product detail, but there are 3 types of pricing: Standard - normal regular pricing by filling the price field Variant - pricing with product variants (size, colour, etc.) with their respective prices Combined - this is a combination of other saved products, with a custom price provided by user. For 1 and 2 I have the below model. If the product model has more than 1 price on StandardProduct model then I know it has variants. class StandardProduct(models.Model): variant_type = models.CharField(max_length=55) variant_name = models.CharField(max_lenght=55) product = models.ForeignKey(Product) sku = models.CharField(max_length=55, blank=True, null=True) barcode = models.CharField(max_length=55, blank=True, null=True) selling_price = models.DecimalField(max_length=15, decimal_places=2) How do I go about creating the CombinedProduct model? The combined product model can have different created products inside (with their quantities). The price is specified by the user. Below is what I have, but I don't know how to approach this. class CombinedProduct(models.Model): product = models.ForeignKey(Product) item = models.ForeignKey(StandardProduct) quantity = models.DecimalField(max_length=15, decimal_places=2) -
Only return the value instead of {'this' : 5} in Django
Sorry for the unclear title. Here is my joueur.py def vie_pourcentage_user (self): viepourcentageuser = (self.user.profile.vie * 100) / self.user.profile.vie_max return {'viepourcentageuser': int(viepourcentageuser)} def energie_pourcentage_user (self): energiepourcentageuser = (self.user.profile.energie * 100) / self.user.profile.energie_max return {'viepourcentageuser': int(energiepourcentageuser)} Here is my view.py def index(request): viepourcentageuser = joueur.vie_pourcentage_user(request) energiepourcentageuser = joueur.energie_pourcentage_user(request) return render(request, 'base.html', { 'viepourcentageuser': viepourcentageuser, 'energiepourcentageuser': energiepourcentageuser, }) Here is what I see : {'viepourcentageuser': 100} Here is what I would like to see : 100 Sorry I know this is basics but it seemed like I missed something. Thanks ! -
How eliminate selection in ManytoMany form field
I have this model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="buyer") smokers = models.ManyToManyField(UserProfile) price = models.FloatField(blank=True) And have this form: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ['smokers', 'price',] I would like to access smokers field and eliminate few options (that user won't be able to select it or even see it in HTML). Is that even possible? -
How to get prerequisites for gettingstartedwithdjango.com tutorial?
I'm following the tutorial "Getting Started With Django" on gettingstartedwithdjango.com. I'm at the prerequisites on a VM that runs Precise64. The maker supplies a shell script named postinstall.sh. Executing that, it tries to install, among others, ruby1.8.7 but fails to download it. After that it wants to install net-ssh-gateway, mime-types, chef and puppet, which all fail, because they need ruby2.0 or 2.2. So i've done "apt get install ruby", which got me ruby1.8. I've tried to get a newer version, but it couldn't be found. When I run the script again it still fails to install the apps, that need ruby. And installing them via "apt get install" only works for puppy, the others are unknown. I would love to do the tutorial, but I fear this applications or libraries are needed. So how do I get those libraries/applications installed? -
site-packages and organizing a multi-app django environment to make sense of templates
I am trying to figure out the best and most logical way to install multiple Django apps and have them organized. In actual fact, I am trying to make sure that my templates are inheriting in the right manner but first off I thought perhaps some Django gurus can let me know what is the best way to organize a multi-app Django site. Starting off, I have used Wagtail as my core installation first and then decided to install more apps from there. Basically, on top of Wagtail, I have decided to install puput following their instructions from https://puput.readthedocs.io/en/latest/setup.html#installation-on-top-of-wagtail pip install puput And at the same time in the same virtualenv I also installed the blog app thru python manage.py startapp blog from this very good tutorial from here. So basically I have both these apps in my INSTALLED_APPS settings but puput is in site-packages whereas the blog app resides in the folder beside where manage.py is. So I was wondering should I move puput to the same directory such that PROJECT_DIR |-blog/ |-puput/ |-mysite/ |--|-settings/ |--|-templates/ |--|-urls.py |--|-etc |-manage.py |-etc The main reason I am asking this is because I am trying to figure out the best way people … -
Displaying images in html - Django
I have a little problem, and I dont have idea why my project doesn't work how I want. I have a models.py class Strona(models.Model): title = models.CharField(max_length=250, verbose_name="Tytuł", help_text="Podaj tytuł artykułu") slug = models.SlugField(unique=True, verbose_name="Adres url SEO", help_text="Automatycznie tworzony przyjazny adres URL") content = HTMLField(verbose_name="Treść artykułu", help_text="Wypełnij treścią artykułu") image = models.FileField(upload_to='blog_images',verbose_name="Obrazek", help_text="Załącz obraz") and in view.py I have from django.shortcuts import render from .models import Strona def strona_glowna(request): strona_glowna = Strona.objects.all() context = {'strona_glowna': strona_glowna} return render(request, 'strona/index.html', context=context) After that I've create the html file and include inside a code : ... {% for strona in strona_glowna %} <strong>{{strona.title}}</strong><br> {% if strona.image == True %} <img src="{{strona.image.url}}"><br> {% else %} {% endif %} <p>{{strona.content|safe}}<p></p> {% endfor %} ... in setting.py I declared: STATIC_URL = '/static/' MEDIA_URL = '/media/' And the problem is, when I reload a website the images doesn't show. I think the routing for upload is ok, but I don't know why I can't display the images. Any ideas? -
Unknown field error in django
I am trying to follow a tutorial and i get this error when i run makemigrations, however in the tutorial, they dont get the error. here is the tutorial: https://www.codingforentrepreneurs.com/blog/how-to-create-a-custom-django-user-model/ This is the error i get at 24:59 in the video: django.core.exceptions.FieldError: Unknown field(s) (username) specified for CustomUser. Here is full traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 327, in execute self.check() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/importlib/__init … -
How to correctly run a form to both create and edit existing data models in Django, with file upload?
OK, I've had a lot of trouble getting this to work. I'm trying to design webform that people can use to submit an application, but also later edit the application. Ended up not using FormWizard, it just wasn't working for me. This function basically works, but I think I did something wrong that is triggering the validation script. All of my required fields have a "This field is required." I am also getting the same error when I try to upload a file (not on page load, on form submit), I'm not sure if these are related. Any suggestions how to get this functioning properly? Here is my view.py for the standard form def app1(request): if request.method == 'POST': form = ChildInfoForm(request.POST) if form.is_valid(): childinfo = form.save(commit=False) childinfo.user = request.user try: childinfoid = ChildInfo.objects.get(user=request.user).id except ObjectDoesNotExist: childinfoid = None if childinfoid: childinfo.id = childinfoid childinfo.save() return redirect('app2') else: try: childinfo = ChildInfo.objects.get(user=request.user) except ObjectDoesNotExist: childinfo = ChildInfo(user=request.user) #childinfo.save() form = ChildInfoForm(model_to_dict(childinfo)) return render(request, 'registration/step1.html', {'form': form}) Here's my view for the upload file function: def app7(request): if request.method == 'POST': form = MortgageUploadForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('upload_success') else: form = MortgageUploadForm() return … -
Django CBV - get url variable for use in class, error self s not defined
I am passing and trying to use site_id in my add form. I want to pre fill and hide the site_data field with the site ID in the url. and then use that variable to pass some more information to the context too. my CBV is as such: class AddSubnet(CreateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'site_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] site_id = self.kwargs['site_id'] site = get_object_or_404(SiteData, pk=site_id) @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (site_id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=site_id context['SiteName']=site.location context['active_subnets']='class="active"' # return context this currently yields with: File "/itapp/itapp/sites/urls.py", line 2, in <module> from . import views File "/itapp/itapp/sites/views.py", line 984, in <module> class AddSubnet(CreateView): File "/itapp/itapp/sites/views.py", line 988, in AddSubnet site_id = self.kwargs['site_id'] NameError: name 'self' is not defined -
Django: set foreignkey to model of which `abstract` True...?
I've designed some model structures in django: class Symbol(BaseModel): field1 = models.CharField(max_length=50) class Meta: abstract = True class DetailSymbol1(Symbol): field2 = models.CharField(max_length=50) class DailyData(BaseModel): symbol = models.ForeignKey(DetailSymbol1) field3 = models.CharField(max_length=50) After makemigrations and migrate done, I created some model objects: In [1]: a = DetailSymbol1.objects.create(field1="a", field2="b") In [2]: a.dailydata_set.create(field3="c") Out[2]: <DailyData: DailyData object> In [3]: a.dailydata_set.create(field3="d") Out[3]: <DailyData: DailyData object> In [4]: DailyData.objects.count() Out[4]: 2 Now, What I want to do is to make Symbol model NOT abstract model and make DailyData have ForeignKey to Symbol, not DetailSymbol1. Here is the final code: class Symbol(BaseModel): field1 = models.CharField(max_length=50) class DetailSymbol1(Symbol): field2 = models.CharField(max_length=50) class DailyData(BaseModel): symbol = models.ForeignKey(Symbol) field3 = models.CharField(max_length=50) When I tried to migration, this prompt occured: You are trying to add a non-nullable field 'symbol_ptr' to detailsymbol1 without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: I have no idea what should I do with this message. How can I deal with it without … -
Response a json type longitude and latitude using Google geocoding API in django using Python
I am a newcomer to Django programming. Here I am working on the server side. The thing I want to do is when client-side type a location in a string, the server will response a longitude and latitude using the geocoding API. But the problem is I can't even successfully import 'google maps' or 'django_google_maps' API in the visual studio How can I import them successfully and apply them to my server-side code? Thank you for answering -
How to build an array of dictionaries in python using generators( which are consumed by StreamingHttpResponse)
I am trying to stream a large json response with django's StreamingHttpResponse. class Annotations(APIView): """ """ def content_generator(self,request): imageObjs = Image.objects.all().values("id","name","path") for imageObj in imageObjs.iterator(): imageData = { "name":imageObj["name"], "path":imageObj["path"] } yield json.dumps(imageData) def get(self,request): try: response = StreamingHttpResponse(self.content_generator(request), content_type = 'application/json') response['Content-Disposition'] = 'attachment;filename="annotations.json"' return response except Exception as e: logger.exception("Error in getting annotations") return Response({'detail':str(e)},status = status.HTTP_500_INTERNAL_SERVER_ERROR) The problem with the above code is that the response is of the form : {"name":"a","path":"xyz"}{"name":"b","path":"abc}...... which is an invalid JSON. What i want to generate is: [{"name":"a","path":"xyz"},{"name":"b","path":"abc}, ...] (*notice the array brackets and comma separators) Is there a way this could be achieved while using generators.? -
Django CBV - Update, filter a foreign key field?
I am trying to filter foreign key fields in a CBV but am unsure on how to achieve this. my view is as per the below: class EditSubnet(UpdateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'site_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_subnet'))) def dispatch(self, *args, **kwargs): return super(EditSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (self.object.id,)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.object.site_data.id context['SiteName']=self.object.site_data.location context['active_subnets']='class="active"' # return context the model is as such: class SiteSubnets(models.Model): device_data = models.ForeignKey(DeviceData, verbose_name="Device", \ blank=True, null=True) site_data = models.ForeignKey(SiteData, verbose_name="Location") subnet = models.GenericIPAddressField(protocol='IPv4', \ verbose_name="Subnet", blank=True, null=True) subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") circuit = models.ForeignKey(Circuits, verbose_name="Link to circuit?", \ blank=True, null=True) vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True) peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" what I would like to do on the update view is filter pre filter the circuits by the site_data.pk. currently it shows all circuits which I only need the related sites circuits. I would like to prefetch these too. is this possible in a CBV? Thanks -
How could i get over NoReverseMatch at /polls/reset-password/ error to continue in making password resetting?
My urls.py is this and even though i have created the password-reset-done url from django.conf.urls import url from .import views from django.conf.urls import url from django.contrib.auth.views import login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_complete urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P<question_id>[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P<question_id>[0-9]+)/results$', views.results, name="results"), #127.0.0.1/polls/1/results url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name="vote"), #127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}), url(r'^logout/$', logout, {'template_name': 'polls/logout.html'}), url(r'^register/$', views.register, name= 'register'), url(r'^profile/$', views.view_profile, name= 'profile'), url(r'^edit_profile/$', views.edit_profile, name= 'edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', password_reset, name='reset_password'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), ] I am getting the following error. -
Django - cannot import name path
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run python manage.py runserver but i got this error: Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Davide\Desktop\django-proj\mysite\mysite\urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path Is it because i have two versions installed? -
Django stuck on login page
I'm very new to Django and I am trying to create an Inventory app. The front page should be a login page and after login it should get data from the Model that I created through admin, But after running server it keeps heading back to login page all the time. My Inventory(Project)- urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls')), url(r'^home/', include('myapp.urls')), ] My myapp urls.py- from django.conf.urls import url from . import views from django.contrib.auth.views import login urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^$', login, {'template_name': 'myapp/login.html'}), ] and in my setting.py of Project- LOGIN_REDIRECT_URL = 'home/' After logging in it keeps going back to login page only! -
What is the best way to implement persistent data model in Django?
What I need is basically a database model with version control. So that every time a record is modified/deleted, the data isn't lost, and the change can be undone. I've been trying to implement it myself with something like this: from django.db import models class AbstractPersistentModel(models.Model): time_created = models.DateTimeField(auto_now_add=True) time_changed = models.DateTimeField(null=True, default=None) time_deleted = models.DateTimeField(null=True, default=None) class Meta: abstract = True Then every model would inherit from AbstractPersistentModel. Problem is, if I override save() and delete() to make sure they don't actually touch the existing data, I'll still be left with the original object, and not the new version. After trying to come up with a clean, safe and easy-to-use solution for some hours, I gave up. Is there some way to implement this functionality that isn't overwhelming? It seems common enough problem that I thought it would be built into Django itself, or at least there'd be a well documented package for this, but I couldn't find any. -
Tensorflow error while restoring multiple models on a parallel thread
I needed to consume TensorFlow models via an API. For that I wrote the API on Django. This API was supposed to receive parallel requests so I looked around and hosted it with Apache. When I consume the API one request at a time for any model, it works as expected with respect to classification tasks. However, when the requests are made to different models in a parallel manner, it starts throwing errors. Going through the error logs I believe the cause is that, the session for one of the model is loading while the session of other model is still active. Is there any way to resolve the conflict amongst these sessions? DISCLAIMER: I am a novice when it comes to web technologies(something I am learning). :) Error Logs: NotFoundError at /nlc/classify/ Key rnn/gru_cell/gates/kernel/Adam_1 not found in checkpoint [[Node: save/RestoreV2_31 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2_31/tensor_names, save/RestoreV2_31/shape_and_slices)]] Caused by op 'save/RestoreV2_31', defined at: File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/utils/deprecation.py", line 95, in __call__ response = self.get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/utils/deprecation.py", line … -
How can i register an admin class without any model?
I want to create a class in django admin from where, i can redirect to a perticular url. I dont want to display any django admin form or any list display and so i dont want to register it with any model. Is there any way to create a class in django admin without any model. thanks in advance -
Offline installation of Django
As in: Can I install Django as offline in Windows 7? ... I am trying to install Django from a file. My RHEL 7 is in a closed network. From another computer I have fetched version 2.0.1 from https://github.com/django/django/releases. running install-command results in: pip3.6 install django-2.0.1.tar.gz Processing ./django-2.0.1.tar.gz Collecting pytz (from Django==2.0.1) Could not fetch URL https://pypi.python.org/simple/pytz/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping Could not find a version that satisfies the requirement pytz (from Django==2.0.1) (from versions: ) No matching distribution found for pytz (from Django==2.0.1) The error corresponds to the fact, that my system does not have access through the proxy. How can I do the install without the need of access to outside world? -
How to make django database such that the new objects will get id (last object's id +1) rather than (last deleted object's id+1)?
I'm writing a django website with a sqlite database, I have a model in my website like this : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Suppose I create Question object "What's up" and delete it and now create another Question object "HI" then "Hi" will get the id 2 not 1.But I want it to be 1 only.Is this possible? I m using django 1.8.7 and can't change the version as whole database is written in django 1.8.7. >> f = Question(question_text="What's up",pub_date=timezone.now()) >> f.id 1 >> f.delete() >> g = Question(question_text="Hi",pub_date=timezone.now()) >> g.id 2 Any help will be appreciated.Thanks in advance -
Count elements of list from queryset
I get a queryset from a model that saves the data to a charfield. The charfield is displayed on a form as MultipleChoiceField with a CheckboxSelectMultiple widget. The max amount of choices is 5. I want to count the number of elements in the queryset. Each queryset can vary in the amount of the elements in the list. Now, when I get len of the list, the value is 5 times the amount of elements. Is the list in the dict not a list but something else? When I create a list manually without the queryset and get len of said list, the value is correct. E.g. list with 3 elements returns 3. query = MyModel.objects.all().values('myvalue') print(query[0]) {'myvalue': "['3']"} print(query[1]) {'myvalue': "['1', '4']"} print(query[0]['myvalue'] ['3'] print(query[1]['myvalue'] ['1', '4'] print(len(query[0]['myvalue'])) 5 print(len(query[1]['myvalue'])) 10 -
Rollbar and celery causing crash onrunning django project
I'm trying to debug a problematic error which occurs when I'm trying to launch django project in which I'm using (among others) celery and rollbar. The problem occurs when I change logging level for mail_admins from ERROR to WARNING. Complete traceback is below: (env)root@test:/var/www/papukurier_test# ./manage.py migrate 2018-01-30 13:30:52 [16517] [WARNING] pathname=/var/www/papukurier_test/env/local/lib/python2.7/site-packages/rollbar/__init__.py lineno=292 funcname=init Rollbar already initialized. Ignoring re-init. Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/papukurier_test/courier/apps.py", line 4, in <module> from courier.api.consumers import INIT_COURIERS_CONSUMERS_SIGNATURE File "/var/www/papukurier_test/courier/api/consumers.py", line 10, in <module> from papukurier.celery import celery_app File "/var/www/papukurier_test/papukurier/celery.py", line 23, in <module> rollbar.init(**settings.ROLLBAR) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/rollbar/__init__.py", line 292, in init log.warning('Rollbar already initialized. Ignoring re-init.') File "/usr/lib/python2.7/logging/__init__.py", line 1164, in warning self._log(WARNING, msg, args, **kwargs) File "/usr/lib/python2.7/logging/__init__.py", line 1271, in _log self.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 1281, in handle self.callHandlers(record) File "/usr/lib/python2.7/logging/__init__.py", line 1321, in callHandlers hdlr.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 749, in handle self.emit(record) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/utils/log.py", line 119, in emit message = … -
Django filtering relationship table
I'm trying to do a for loop that displays the items in one of the foreign key fields after using another foreign key filter. I'm getting this message: One matching query does not exist. Models.py class One(models.Model): description = models.TextField(blank=True) function = models.ForeignKey(Function, related_name='program', blank=True) program = models.ForeignKey(Program, related_name='function', blank=True) def __unicode__(self): return "description{}, function{}, program{}".format(self.description,self.function,self.program) class Program(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return "title{}".format(self.title) Views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) func_programs = One.objects.get(function=Function_id).program.all( context = { 'func_programs' : func_programs } return render (request, 'project/function.html', context) HTML <select id=options name="func_programs"> <option>Choose From List</option> {% for func_program in func_programs %} <option value="{{func_program.function.id}}"> {{func_program.program.title}}</option> {% endfor %} </select><br> How can I filter this so that my scroll down shows the program title of all the programs under one particular function? Thanks in advance. -
Django - DB existing field add to model
I have a model SomeObject without field type, but data is already in DB. How can I insert type ForeignKey to SomeObjectType model into SomeObject to get as the result the field type. type field is not nullable and has no default value.