Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating field from values of a model and literal values
I am trying the following but open to alternative solutions: modelA(): name=models.CharField(max_length = 200) modelB(): TYPES = ModelA.objects.all() BUNDLE_FOR = list( ( (x.id, x.name) for x in TYPES ) ) # ADD A LITERARL VALUE BUNDLE_FOR.append((0,'Unregistered')) bundle_for = models.IntegerField(choices = BUNDLE_FOR, default=0) Currently, the migration doesn't work on fresh database because ModelA doesn't exist yet. One way of working with it is to migrate with TYPES declare to an empty list then return it to ModelA.objects.all() but it is troubling. The basic idea is if bundle_for is greater than 0, we check ModelA for certain validation-oriented values/data. It will be used in admin of django and not -
Django Template not rendering from database
I am using Class Based Views and so far it's going good. Recently I came across something logical or code related, which I'm unable to understand. I have an html file, where I want to pass or display my two models. PhotographyData Pictures I am successfully able to pass the models through using two different ListView. But the Pictures ListView is not showing any data but it's showing me the object id. Similarly I tried creating a PicturesDetailView to check if the database isn't causing any error, and even in that DetailView there isn't any data or any id getting passed. I am using Django forms to save data in the db and it's working. There isn't any error occurring as well. View.py class PhotographyListView(ListView): model = PhotographyData template_name = "projectfiles/PhotographyView.html" def get_queryset(self): return PhotographyData.objects.all() class PicturesListView(ListView): model = Pictures template_name = "projectfiles/PhotographyView.html" # context_object_name = "Pics" queryset = Pictures.objects.all() # def get_queryset(self): # return Pictures.objects.all() class PicturesDetail(DetailView): model = Pictures template_name = 'projectfiles/View.html' Models.py class PhotographyData(models.Model): photography_pkg_name = models.CharField( "Photography package", max_length=50) photography_pic = models.ImageField( upload_to='images', blank=False, null=False) photography_price = models.SmallIntegerField(blank=False, null=False) class Pictures(models.Model): pic_name = models.CharField(max_length=50) pic_caption = models.TextField() date = models.DateTimeField(auto_now=False, auto_now_add=False) location = models.CharField(max_length=50) pic = … -
“Is there an projects for doing best practices?” [on hold]
please help me how can i found the best projects at intermediate level to do. -
How to pass a product download link inside the django template
how do i pass the link to download a product if the particular product is downloadable models.py protected_loc = settings.PROTECTED_UPLOADS def download_loc(instance,filename): return "%s/%s" %(instance.slug, filename) # if instance.user.username: # return "%s/download/%s" %(instance.user.username,filename) # else: # return "%s/download/%s" %("default",filename) class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) name = models.CharField(max_length=120) description = models.CharField(max_length=500,null=True,blank=True) download = models.FileField(upload_to=download_loc,storage=FileSystemStorage(location=protected_loc),null=True,blank=True) price = models.DecimalField(max_digits=60,decimal_places=2) sale_price = models.DecimalField(max_digits=60,decimal_places=2,null=True,blank=True) slug= models.SlugField() def __str__(self): return self.name template {% for order in my_orders %} <tr> <td>{{ order.date_ordered }}</td> <td>{{ order.ref_code }}</td> <td> {% for item in order.items.all %} {{ item.product.name }} {% endfor %} </td> <td>${{ order.get_cart_total }}</td> {% if product.download %} <td><a href='{{ product.download|filename }}'>Download</a></td> {% endif %} </tr> {% empty %} <tr> <td colspan= 4> You have no orders.</td> </tr> {% endfor %} Am i missing something here i Cant get the download link to work though the download function is fine . What am intending is that if the product is purchased-----> go to my userprofile where in the profile user can be able to download it if it is a downlodable product. help out. -
I need to understand the meaning of code lines
I am trying to understand the meaning of this code, but I find it challenging class Diposit(models.Model): user = models.ForeignKey( User, related_name='deposits', on_delete=models.CASCADE, ) -
Checking email if already exists?
Here i have two forms for adding and updating user.The Register form is working fine to check if the email already exists but while updating the user it is not working properly.The problem is When i do update the username only it also says the email address already exists.What i want is while updating the user if only the user change the email address and the changed email address is already in use then i want to raise validation error.How can i do that ? forms.py class RegisterForm(UserCreationForm): def check_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError('Email Already Exists') return email class Meta: model = User fields = ['username', "email", "password1", "password2", 'is_superuser', 'is_staff', 'is_active'] class EditRegisterForm(forms.ModelForm): def check_email(self): email = self.cleaned_data['email'] email_exists = User.objects.filter(email=email) if self.instance and self.instance.pk and not email_exists: return email else: raise ValidationError('Email already Exists') class Meta: model = User fields = ['username', "email", 'is_superuser','is_staff', 'is_active'] -
CreateModelMixin TypeError: __init__() takes 1 positional argument but 2 were given
I'm trying to insert a new row into a 2 column table where one column references the authenticated user (model references user model via a FK) and the other being a variable passed through the url. urls.py url('^(?P<update>-?\d+.?\d+)/$', views.UpdateViewSet) views.py class UpdateViewSet(mixins.CreateModelMixin,viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.UpdateSerializer def create(self,request,*args, **kwargs): update = self.kwargs['update'] return self.create(user=self.request.user,update=update) Traceback File "\Backend\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "\Backend\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "\Backend\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given -
Software As Service Built in Django. Should I use Django or say Wordpress for the content (main) website?
I am a one person company. I built a software a service product in Django, including user sign up and login pages in Django. That being said, I am not an expert developer, and think it may be more manageable to have the content website www.mywebsite.com in Wordpress. While the app itself app.mywebsite.com will still remain in Django. Do you recommend this strategy, or should both www.mywebsite.com and app.mywebsite.com both be in Django. -
Where do I store images permanently so that heroku app can access them, even though after the dynos cycling I need the images to be shown
I cannot buy AWS s3 or any other sort of storage spaces because I'm a student, so could you please give me any other solution for storing images permanently so that my heroku app can access them till my app stays alive. -
Is it possible to not use the static tag and still apply and display static files in Django?
What should be done to allow relative paths inside the static files to work without using the static tag? I want to add HTML, CSS, and JavaScript files from a front-end developer and have them work with Django without modifying them. As the front-end developer doesn't know django template language and it would be a lot of work to modify them myself. -
Django: Post-Save Signal TransactionManagementError
I am using post-save signal for a model to start a celery task. It was working before but suddenly, it is giving me a TransactionManagementError. Model class FieldSightXF(models.Model): xf = models.ForeignKey(XForm, related_name="field_sight_form") site = models.ForeignKey(Site, related_name="site_forms", null=True, blank=True) project = models.ForeignKey(Project, related_name="project_forms", null=True, blank=True) is_staged = models.BooleanField(default=False) is_scheduled = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now=True) date_modified = models.DateTimeField(auto_now=True) schedule = models.OneToOneField(Schedule, blank=True, null=True, related_name="schedule_forms") stage = models.OneToOneField(Stage, blank=True, null=True, related_name="stage_forms") shared_level = models.IntegerField(default=2, choices=SHARED_LEVEL) form_status = models.IntegerField(default=0, choices=FORM_STATUS) fsform = models.ForeignKey('self', blank=True, null=True, related_name="parent") is_deployed = models.BooleanField(default=False) is_deleted = models.BooleanField(default=False) is_survey = models.BooleanField(default=False) from_project = models.BooleanField(default=True) default_submission_status = models.IntegerField(default=0, choices=FORM_STATUS) logs = GenericRelation('eventlog.FieldSightLog') class Meta: db_table = 'fieldsight_forms_data' # unique_together = (("xf", "site"), ("xf", "is_staged", "stage"),("xf", "is_scheduled", "schedule")) verbose_name = _("XForm") verbose_name_plural = _("XForms") ordering = ("-date_created",) Post-save signal @receiver(post_save, sender=FieldSightXF) def share_form(sender, instance, created, **kwargs): if instance.project is not None and created: from onadata.apps.fsforms.tasks import share_form_managers task_obj = CeleryTaskProgress.objects.create(user=instance.xf.user, description="Share Forms", task_type=17, content_object=instance) if task_obj: try: share_form_managers.delay(instance.id, task_obj.id) except: pass post_save.connect(create_messages, sender=FieldSightXF) The CeleryTaskProgress is used to track the progress of the celery tasks. Task @shared_task(max_retires=5) def share_form_managers(fxf, task_id): fxf = FieldSightXF.objects.get(pk=fxf) userrole = UserRole.objects.filter(project=fxf.project, group__name='Project Manager') users = User.objects.filter(user_roles__in=userrole) shared = share_form(users, fxf.xf) if shared: CeleryTaskProgress.objects.filter(id=task_id).update(status=2) else: CeleryTaskProgress.objects.filter(id=task_id).update(status=3) share_form method … -
Cannot save django staticfiles to AWS S3
I ran into a strange problem while deploying staticfiles to S3. I installed boto3 and django-storages. Django: 2.1.2 Python: 3.6.7 When running locally, my staticfiles settings were following, BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') When I want to save staticfiles to S3 bucket, I changed settings to STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] AWS_ACCESS_KEY_ID = 'key' AWS_SECRET_ACCESS_KEY = 'key' AWS_STORAGE_BUCKET_NAME = 'name' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_STATIC_LOCATION = 'static' AWS_MEDIA_LOCATION = 'media' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) STATIC_ROOT = STATIC_URL MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA_LOCATION) MEDIA_ROOT = MEDIA_URL STATICFILES_STORAGE = 'main.storage_backends.StaticRootS3BotoStorage' DEFAULT_FILE_STORAGE = 'main.storage_backends.MediaStorage' storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False After running, python manage.py collectstatic I still get the following prompt, You have requested to collect static files at the destination location as specified in your settings: /home/drogon/Crowdsocial_project/staticfiles This will overwrite existing files! Are you sure you want to do this? It still saves to staticfiles directory locally, not on s3. What am I doing … -
How to use phone number instead username in django rest ftamework authetication?
I am using Django rest framework for authentication which is working fine and url for registration and login is given below: path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')) There are following fiels in registration: Username Email Password1 Password2 However I want phone number to work as unique mobile number for registration with some validation i.e. length 10? I have found other answer and documentation but that seems confusing. How to use the phone number in registration? -
Django generate group by different than id
I want to count amount of Users for same Product models.py class Product(models.Model): pass class User(models.Model): product = models.ForeignKey(Product) User.objects.annotate(product_count=Count('product_id')) output sql SELECT COUNT("user"."product_id") AS "product_count" FROM "user" GROUP BY "user"."id"; desired sql: SELECT COUNT("user"."product_id") AS "product_count" FROM "user" GROUP BY "user"."product_id"; -
How to define mapper for phonenumber-field in Django + Spyne
I'm trying to develop a soap service in Django using Spyne. Some models in my project use django-phonenumber-field. Where I run server I get the error: spyne.util.django.DjangoModelMapper.UnknownFieldMapperException: No mapper for field type PhoneNumberField ImageFile raises same error. I need make a mapper for the PhoneNumberField. But how? -
Connection refused error with djang-elasticsearch-dsl
I'm trying to integrate ElasticSearch with my Django project using the package django-elasticsearch-dsl, and I am getting this error: >> $ curl -X GET http://localhost:9200 curl: (7) Failed to connect to localhost port 9200: Connection refused I downloaded django-elasticsearch-dsl using the commands: pip install https://github.com/sabricot/django-elasticsearch-dsl/archive/6.4.0.tar.gz and pip install django-elasticsearch-dsl, but they both caused the same results. I don't believe this is a duplicate question because every other question I have read pertaining to this error has dealt with only the ElasticSearch library, not the django-elasticsearch-dsl library. The latter is built on top of the former, but I can't seem to find a elasticsearch.yml file as detailed in all other posts. Here is what is installed in my virtual environment: >> pip freeze Django==2.2.2 django-elasticsearch-dsl==6.4.0 elasticsearch==7.0.2 elasticsearch-dsl==7.0.0 lazy-object-proxy==1.4.1 mccabe==0.6.1 pylint==2.3.1 python-dateutil==2.8.0 pytz==2019.1 requests==2.22.0 typed-ast==1.4.0 urllib3==1.25.3 According to this tutorial, the command http://127.0.0.1:9200 should return what looks like a JSON response, but instead I get the error: curl: (7) Failed to connect to localhost port 9200: Connection refused -
fix Twisted long running process using django 1.9.13 mysql has gone away?
I have a long running process that is a twisted process, it just listens for network connection and does some processing. I am upgraded my django to 1.9.13 and when nothing happens in the process for a long time mysql gone away occrurs. How can i make it so it doesn't go away? its possible that nothing occurs for a long time. -
translate the SQL query to django model
I have a SQL query : Select * From Order a Where Date = (Select Max(b.Date) From Order b Where a.ID = b.ID) How to translate it into django ? -
Why does BeautifulSoup not find the tags containing text but I can run a "find" and see the text in the HTML?
I'm using Python 3.7 and BeautifulSoup 4. What's the right way to search for tags that contain specific text? I thought I could do this soup = BeautifulSoup(code, features="lxml") ... no_images_msgs = ["No very similar images were found.", "No similar images were found."] for no_images_msg in no_images_msgs: elts = soup.body.findAll(text=re.compile("^.*" + no_images_msg + ".*$")) print("index:" + str(code.find(no_images_msg))) print("searched for " + no_images_msg + " found:" + str(len(elts))) but interestingly, even though the "find" call returns a positive number indicating the specified string can be found in the HTML code, the "findAll" call fails to find anything. What am I doing wrong? -
Triggering download of csv file with django [duplicate]
This question already has an answer here: Django generate csv file on view and download 1 answer Currently my django application takes in a csv file and process it. How could I trigger the download of the processed csv file? Preferably the file manager should automatically pop up asking the user to select the folder in which the new csv file will be saved in. Thanks! -
How do you make a simple POST request using urllib.request?
I'm using Python 3.7 and DJango. How do I make a POST request using urllib.request? I tried this import urllib.request as urllib2 ... data = {"MAX_FILE_SIZE": "10485760", 'url': image_url, 'search': 'search', 'nsfwfilter': 'on'} req = urllib2.Request(SEARCH_URL, data=bytes(json.dumps(data)), headers=settings.HDR, encoding="utf-8") html = urllib2.urlopen(req).read() but this results in the error below ... Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/myproject_project/myproject/management/commands/check_duplicates.py", line 18, in handle original_url = MediaService.check_duplicate(article) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 28, in check_duplicate dup_links = MediaService.check_url(image_url) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 43, in check_url code = MediaService.doImageSearch(image_url) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 71, in doImageSearch req = urllib2.Request(SEARCH_URL, data=bytes(json.dumps(data)), headers=settings.HDR, encoding="utf-8") TypeError: string argument without an encoding -
In Python 3.7, how do you make POST request with urllib2?
I'm using Python 3.7 and DJango. How do I make a POST request using urllib2? I tried this data = {"MAX_FILE_SIZE": "10485760", 'url': image_url, 'search': 'search', 'nsfwfilter': 'on'} req = urllib2.Request(SEARCH_URL, data=bytes(json.dumps(data)), headers=settings.HDR, encoding="utf-8") html = urllib2.urlopen(req).read() but this results in the error below ... Traceback (most recent call last): File "manage.py", line 21, in <module> execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/myproject_project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/myproject_project/myproject/management/commands/check_duplicates.py", line 18, in handle original_url = MediaService.check_duplicate(article) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 28, in check_duplicate dup_links = MediaService.check_url(image_url) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 43, in check_url code = MediaService.doImageSearch(image_url) File "/Users/davea/Documents/workspace/myproject_project/myproject/services/media_service.py", line 71, in doImageSearch req = urllib2.Request(SEARCH_URL, data=bytes(json.dumps(data)), headers=settings.HDR, encoding="utf-8") TypeError: string argument without an encoding -
In Django, what would be the proper way to persist session information?
I am designing a REST app in django, which I intend people to use without a browser (just direct API calls with curl or whatnot). I have several different views where I want to pull in information about the session based on values that may have been a acquired from previous calls to other views. It seems that every time a view is called the "request" object passed in is an entirely new session, so I'm wondering how I can persist values the "correct" way? Example code: def login(request): ... ##I want to assign a token value to this session that is persisted to the entity requesting it request.session['token'] = response.json()['auth'] ... def grabSomeValues(request): ... ##I want to grab the session token value in here but of course the request object in the case is a completely new one that does not have that token value it seems print(request.session['token'] .... -
How to serialize a django model with several self referenceing fields with a depth of 1
How do I serialize my model without an endless recursion? I only want to replace foreign keys with one row deep of information. Currently I have this: class Client(models.Model): my_id = models.CharField(max_length=500, unique=True) name = models.CharField(max_length=500) last_update = models.DateField(null=True, blank=True) friend_1 = models.ForeignKey( "self", related_name="friend_1a", on_delete=models.CASCADE, to_field="my_id", null=True, blank=True, ) friend_2 = models.ForeignKey( "self", related_name="friend_2a", on_delete=models.CASCADE, to_field="my_id", null=True, blank=True, ) friend_3 = models.ForeignKey( "self", related_name="friend_3a", on_delete=models.CASCADE, to_field="my_id", null=True, blank=True, ) def _get_days_since_last_review(self): today = date.today() if self.last_update is None: self.last_update = today return str((today - self.last_update).days) days_since_last_review = property(_get_days_since_last_review) def __str__(self): return self.name class ClientSerializer(serializers.Serializer): my_id = serializers.CharField(max_length=500) name = serializers.CharField(max_length=500) days_since_last_review = serializers.CharField(max_length=500) friend_1 = serializers.CharField() friend_2 = serializers.CharField() friend_3 = serializers.CharField() class ClientSerializerWithFriends(serializers.ModelSerializer): """ this is a recursive infinite loop. TODO: Fix Me! """ friend_1 = RecursiveField(allow_null=True) friend_2 = RecursiveField(allow_null=True) friend_3 = RecursiveField(allow_null=True) class Meta: model = Client fields = ( "my_id", "name", "days_since_last_review", "competitor_1", "competitor_2", "competitor_3", ) but I can't seem to find a way to limit the RecursiveField() to one level of depth. Currently it reaches the max depth of recursion because friends are reciprocal. Basically JSON of it would be: [{ "my_id": "LH7K_T", "name": "Jack", "last_update": "2019-06-03", "days_since_last_review": "9", "friend_1": { "id": 6, "my_id": "4YR0_T", … -
Error handling for checked fields Django multiselectfield
I have a conditional check where I need to look at a certain checkbox, and depending on that, a multiselect field becomes required. I have something similar in place: {% for value, text in form.customfield.field.choices %} <div class="checkbox custom-control custom-checkbox list-inline-item" style="display:inline-flex;"> <input type="checkbox" name="{{customfield.name}}" value="{{value}}" class="list-inline-item custom-control-input" title="" id="id_{{value}}" {% if value in customfield.data %} checked="checked"{% endif %}> <label for="id_{{value}}" class="form-check-label custom-control-label mr-3">{{text}}</label> </div> {% endfor %} Is there a way to do error handling for this? I verified that my form.is_valid() returns false, but the error message does not get displayed, like it does for inputs/textboxes. I'm assuming I need to print the specific error out in the template explicitly, as I am not using defaults like {{ form.customfield }} or {{ bootstrap_field }} form.is_valid() returns False. form._errors gives me: <ul class="errorlist"><li>customfield<ul class="errorlist"><li>This field is required when the other field is checked.</li></ul>