Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict users to upload only doc and pdf formats in FileField in django?
I am working on a tutors website so tutors have to upload their resumes So I want to restrict them to upload only doc or pdf format resume through FieleField in DJango Models. -
baffling python datetime.strptime() "does not match format" error
I have a Django project that is running on a live CentOS production server. I last updated code about 9 days ago, and everything had been working fine until today. Suddenly, I started getting a baffling error that makes no sense. Here is my traceback: [Fri Nov 04 18:43:00 2016] [error] File "/usr/lib/tethys/src/tethys_apps/tethysapp/hydroshare_gis/utilities.py", line 1196, in res_has_been_updated [Fri Nov 04 18:43:00 2016] [error] db_date_obj = datetime.strptime(db_date.split('+')[0], '%Y-%m-%dT%X.%f') [Fri Nov 04 18:43:00 2016] [error] File "/usr/local/lib/python2.7/_strptime.py", line 325, in _strptime [Fri Nov 04 18:43:00 2016] [error] (data_string, format)) [Fri Nov 04 18:43:00 2016] [error] ValueError: time data '2016-10-15T15:12:41.787370' does not match format '%Y-%m-%dT%X.%f' Here is the function that throws the error, pretty straight forward: def res_has_been_updated(db_date, res_date): db_date_obj = datetime.strptime(db_date.split('+')[0], '%Y-%m-%dT%X.%f') res_date_obj = datetime.strptime(res_date.split('+')[0], '%Y-%m-%dT%X.%f') if db_date_obj < res_date_obj: return True return False I temporarily added a few print statements to double-check the dates coming in, and this is what they look like: 2016-06-14T13:30:42.735448+00:00 Now call me crazy, but I must disagree with this python interpreter... That time data does match the format. How am I so sure? 1) I have eyes. 2) This was working fine before today (I have not modified the code and the inputs have not changed). … -
Arabic text show up in Django incorrectly but show up n terminal correctly
I have a mysql database that has a table with arabic text. When I query it in terminal it shows correctly but when I want to see it in Django admin panel it shows messed up text like "ÙŠ ÙŠÙÙˆÙŽØ³ÙˆÙØ³Ù ÙÙŠ ØµÙØ¯ÙˆØ±Ù النّاØ" I am using Django 1.10 mysql Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using EditLine wrappermy and nginx. My configurations and table are as follow: CREATE DATABASE `q` /*!40100 DEFAULT CHARACTER SET utf8 */ CREATE TABLE `main_qsimplemin` ( `id` int(11) NOT NULL AUTO_INCREMENT, `SID` smallint(6) NOT NULL, `VID` smallint(6) NOT NULL, `AText` longtext COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `main_quransimplemin_SID_8789f31f_uniq` (`SID`,`VID`) ) ENGINE=InnoDB AUTO_INCREMENT=6238 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci Mysql configuration: [mysqld] #init_connect=‘SET collation_connection = utf8_unicode_ci’ #init_connect=‘SET NAMES utf8’ #character-set-server=utf8 #collation-server=utf8_unicode_ci #skip-character-set-client-handshake #default-character-set=utf8 character-set-server = utf8 [client] port = 3306 socket = /var/run/mysqld/mysqld.sock #character-set-client = utf8 [mysqld_safe] pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp lc-messages-dir = /usr/share/mysql explicit_defaults_for_timestamp collation-server = utf8_unicode_ci init-connect='SET NAMES utf8' character-set-server = utf8 sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES symbolic-links=0 !includedir /etc/mysql/conf.d/ Django configuration: # -*- coding: utf-8 -*- """ Django settings for … -
Django, Celery: task does not asynchronous?
I tried to send slack message asynchronously when order model be made in my django project. All thing works good and send slack notification perfectly except asynchronization. I run this test my local laptop and run four servers in each terminal: postgreSQL server Django web server Redis server Celery(Worker) server Here is what I did for checking asynchronization. tasks.py @shared_task def send_message(text, channel, username="spacegraphy"): # Python Object data = { "text": text, "channel": channel, "username": username, } # dump시켜서 string으로! requests.post( SLACK_WEBHOOK_URL, data=json.dumps(data) ) signals.py @receiver(post_save, sender=Order) def post_save_order(sender, instance, created, **kwargs): if created: print("signal is called!!!") slack.send_message.delay('new order!', '#order_web') forms.py class OrderForm(forms.ModelForm): def save(self): order = super(OrderForm, self).save(commit=False) # do something other order.save() print("save() is called!") import time time.sleep(10) return order Notice : time.sleep(10) exists for checking async. and then, I create an order in my views through POST request. (I am not gonna showing view part because all process works correctly except asynchronization) In terminal, it shows like this when I create and order, signal is called!!! save() is called! The problem is that task also stop for 10 secs, which means it operate as synchronous, not asynchronous. After 10 secs, slack message comes in. What's wrong with … -
Django filter error in GraphQL cookbook example
I am currently learning GraphQL via the tutorial on graphene. however I am encountered with this error when I tried to run python3 manage.py graphql_schema Error: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 355, in create_parser self.add_arguments(parser) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/management/commands/graphql_schema.py", line 39, in add_arguments default=graphene_settings.SCHEMA, File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/settings.py", line 110, in __getattr__ val = perform_import(val, attr) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/settings.py", line 54, in perform_import return import_from_string(val, setting_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/settings.py", line 68, in import_from_string module = importlib.import_module(module_path) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/lebeier/Documents/cookbook/schema.py", line 3, in <module> import ingredients.schema File "/Users/lebeier/Documents/cookbook/ingredients/schema.py", line 33, in <module> class Query(AbstractType): File "/Users/lebeier/Documents/cookbook/ingredients/schema.py", line 38, in Query all_ingredients = DjangoFilterConnectionField(IngredientNode) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/filter/fields.py", line 20, in __init__ self.filterset_class = get_filterset_class(filterset_class, **meta) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/graphene_django/filter/utils.py", line 32, in get_filterset_class return custom_filterset_factory(**meta) File … -
Django rest api in serializer
Model: class Timings(models.Model): Timings_to = models.TimeField(blank=True) Timings_from = models.TimeField(blank=True) def __str__(self): return str(self.Timings_to) + '' + str(self.Timings_from) class Temple(models.Model): history = models.TextField(blank=False) timings = models.ManyToManyField(Timings, blank=False, related_name='temple_timing') establishment = models.CharField(max_length=20, choices=ESTABLISHMENT_CHOICE, blank=True, default=None ) My question How i can write serializer for these class. I am very new in django and rest. Seiralizer: class TimingsCreateUpdateSerializer(serializers.ModelSerializer): """ Timing Serializer for create """ Timings_to = serializers.TimeField(format="%I:%M%p") Timings_from = serializers.TimeField(format="%I:%M%p") class Meta: model = Timings fields = ('id', 'Timings_to', 'Timings_from',) read_only = ('id',) class TempleSerializer(serializers.ModelSerializer): timings = TimingsCreateUpdateSerializer(many=True) class Meta: model = Temple fields = '__all__' I try to override create method according to documention of restfull api. but it not works, please tell me the correct way t write serializer class for this model. def create(self, validated_data): timings_data = validated_data.pop('timings') temple = Temple.objects.create(**validated_data) for time_data in timings_data: Timings.objects.create(temple=temple, **time_data) return temple temple object is created but in "Timings.objects.create(temple=temple, **time_data)" shows this error >>> serializer = TempleSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\aryan\prabhat\anakonda\envs\sarvam\lib\site-packages\rest_framework\serializers.py", line 192, in save self.instance = self.create(validated_data) File "C:\Users\aryan\prabhat\sarvam_src\institute\serializers.py", line 103, in create Timings.objects.create(temple=temple, **time_data) File "C:\Users\aryan\prabhat\anakonda\envs\sarvam\lib\site-packages\django\db\models\manager.py", line 122, in manager _method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\aryan\prabhat\anakonda\envs\sarvam\lib\site-packages\django\db\models\query.py", … -
How to create auto-generated Django notification?
Hi I have this problem: My web app is for tracking goals of the user, every goal has reminders, so when a reminder has expired the app must alert the user. Example, Mark has a goal: "Run a marathon on december" and this goal has a reminder in every saturday at 15:00. So If Mark is using the app at 15:00 on a saturday, the browser must alert him. This is for my university so if the solution is simple, better ! I dont't know wich way try, all the examples or tutorials functions with notifications of actions of users.. Here the actor is the server, I'm very lost. What should I learn ? https://docs.djangoproject.com/en/dev/ref/contrib/messages/ https://pypi.python.org/pypi/django-notifications-hq/ https://github.com/peterbe/django-sockjs-tornado https://github.com/pinax/pinax-notifications https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=django%20notification%20node If you can avoid me of using Nodes better ! Thanks -
How do I get my request data in the django-paypal IPN function?
I am building an online store. My order data are stored in the request. My views have the following general structure: payment.py def payment(request): order = request.order # Getting the order instance # do some stuff return render_to_response("payment.html") I use django-paypal. I am following this tutorial. The following function is called by PayPal and it signals me that the payment has been successful. payment_paypal_ipn_signal_handler.py # Almost entirely copied from the django-paypal tutorial from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def payment_paypal_ipn_signal_handler(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the business field request. (The user could tamper # with those fields on payment form before send it to PayPal) if ipn_obj.receiver_email != "receiver_email@example.com": # Not a valid payment return # ALSO: for the same reason, you need to check the amount # received etc. are all what you expect. # Undertake some action depending upon `ipn_obj`. if ipn_obj.custom == "Upgrade all users!": Users.objects.update(paid=True) # Here I should add the code that handles a successful payment request.order.paid = True # How do I get my 'request' here? else: #... valid_ipn_received.connect(show_me_the_money) But, I still … -
Django registration - redirect from login/register agter successfule login
I'm using django-registration and I need prevent access to login, register etc when user is logged. Now, when user is logged I can acces /accounts/register/. How to prevent this? I think to overwrite this view but I don;t know how. -
Django.contrib.auth and post_migrate
I am currently extending django.contrib.auth. One of the features I need is generating Groups and associated Permissions based on some rules defined in project settings. The perfect place to do so would be the post_migrate signal. However, django.contrib.auth has a post_migrate receiver (connected here) that runs create_permissions (here). Since I rely on permissions generated by django.contrib.auth, I need to ensure that my create_groups always runs after the permissions were created by django.contrib.auth create_permissions. What would be the best approach to do so? -
QuillJS doesn't work with textarea
I am trying to use QuillJS on a specific form field in my Django 1.10 template as follows: <link href="https://cdn.quilljs.com/1.1.3/quill.snow.css" rel="stylesheet"> <script src="https://cdn.quilljs.com/1.1.3/quill.js"></script> <!-- Initialize Quill editor --> <script> var quill = new Quill('#id_text', { theme: 'snow' }); </script> The problem is that Django renders the form field I want to use Quill on as a textarea instead of a div, and Quill doesn't seem to work on it: any effects applied to text don't register either visually or in the resulting output, and when I try to edit an existing record the initial text doesn't show up in the editor, even though it is there in the source HTML between the textarea tags. Is it a known issue that Quill doesn't work with textarea or is there something else that could be wrong? -
Django Selenium SetUp function not storing data in db using factoryboy
I am trying to create an automated test using Selenium/Django 1.7.7 The tests are structured to inherit from SeleniumTestCase (which is custom webdriver) When I try to create doctors and then log in to their portal, their user is not being created, thus my test fails from apps.practice.tests.factories import ( DoctorFactory) from ..helpers import SeleniumTestCase ### SeleniumTestCase inherits from LiveServerTestCase class PatientCandidacy(SeleniumTestCase): def setUp(self): self.doctor = DoctorFactory(email=EMAIL, password=make_password(PASSWORD)) self.doctor2 = DoctorFactory(email=EMAIL2, password=make_password(PASSWORD2), practice=self.doctor.practice) self.doctor.save() self.doctor2.save() self.wd = CustomWebDriver(command_executor='http://192.168.99.100:4444/wd/hub/', desired_capabilities=settings.SELENIUM_DESIRED, browser_profile=settings.SELENIUM_PROFILE, keep_alive=False, proxy=settings.SELENIUM_PROXY) def tearDown(self): self.wd.quit() def test_patient(self): self.open(settings.WEB_URL + '/login/?next=/') # Assert login page using doctor1 self.page_loaded() self.is_login_page() self.login(EMAIL, PASSWORD) If I create the doctor outside the class as a global variable, the test works, but this way I can't use the helpers within my SeleniumTestCase. What am I doing wrong that is not storing the doctors in the blank DB? -
django_filters picking up %(app_label)s_related_name as field name
So I have one model, which uses a ContentType to point to a collections of models across separate apps. I want to be able to "plug in" the functionality linking that model to the other models in the separate app. So we have the follwing: class MyModelMixin(models.Model): """ Mixin to get the TheModel data into a MyModel """ updated_date = models.DateTimeField(null=True, blank=True) submission = GenericRelation( TheModel, related_query_name='%(app_label)s_the_related_name') class Meta: abstract = True The main model model looks like this: class TheModel(models.Model): """ This tracks a specific submission of an SAQ by a specific site """ updated = models.DateTimeField() status = models.CharField(max_length=32, blank=True, null=True) final_score = models.DecimalField( decimal_places=2, max_digits=30, default=-1, ) config = models.ForeignKey(Config, blank=True, null=True) content_type = models.ForeignKey( ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) my_model_instance = GenericForeignKey() And the mixin is included in the MyModel models, which are available in many different apps. When using a filter for this, using django filters, there is an issue. I have a filter that's supposed to be instantiated to each app when it's used. However when I instantiate, for example, with class MyFilterSet(Filterset): def __init__(self, *args, **kwargs): self.config_pk = kwargs.pop('config_pk', None) if not self.config_pk: return self.config = models.Config.objects.get(pk=self.config_pk) self.custom_ordering["c_name"] =\ "field_one__{}_the_related_name__name".format( self.config.app_model.app_label, … -
changing the initial value in SelectDateWidget based on the current year
I have a form with a DateTimeField that has a list of MY_YEARS that is just 1950-2050. #forms.py my_date = forms.DateTimeField(widget=forms.SelectDateWidget(years=MY_YEARS), initial=datetime.datetime.now()) Could I set the initial to just change the year so that it is 5 years before the current year? -
How can I make my django app use sqlite in the development server but not on to production server
I am using PostresSQL on my production server, not that it should matter to the question. I hear there is an easy way to set it up so even though my project is pulling from the same repo I can set it to use the correct DB for the environment that it is in. -
Django 'module has no attirbute' for Form
I am currently working on trying to make a basic form that inputs the information to a MySQL database so that I can later query it for future use. I am trying to setup a test webapp and I am running into an issue. I have tried following a bunch of different tutorials but seem to stay stuck. Essentially, I have put bellow all of my various parts of the django setup. When I try to run the server, I run into this. File "/home/ec2-user/testapp/testapp/urls.py", line 22, in <module> url(r'^questionnaire/$', views.questionnaire, name='questionnaire'), AttributeError: 'module' object has no attribute 'questionnaire' Which is confusing, because based on these two tutorials, I did the urls.py right. So I am not sure if I am missing something, or if these are outdated and not properly explaining something. https://tutorial.djangogirls.org/en/django_forms/ https://hellowebapp.com/news/tutorial-setting-up-a-contact-form-with-django/ Here is my forms.py from django import forms class QuestionnaireForm(forms.Form): service_team = forms.CharField(label='Team Name', max_length=256, strip=True) team_email = forms.CharField(label='Team Email', max_length=100) other_info = forms.CharField(label='Addition/Other Info') Here is my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import QuestionnaireForm def get_details(request): if request.method == 'POST': form = QuestionnaireForm() else: # A POST request: Handle Form Upload form = QuestionnaireForm(request.POST) # Bind data from … -
Using this method to create dynamic django forms. How would I pass in a dictionary of dictionaries and loop over them?
Citing the link where I found the information. http://avilpage.com/2015/03/django-form-gotchas-dynamic-initial.html Taking this form. In [21]: from django import forms In [22]: class AdvancedForm(forms.Form): ....: ....: def __init__(self, *args, **kwargs): ....: super().__init__(*args, **kwargs) ....: self.initial['name'] = 'override' # aha!!!! ....: ....: name=forms.CharField(max_length=10) ....: In [23]: f4 = AdvancedForm(initial={'name': 'precedence'}) In [24]: f4.as_p() Out[24]: '<p>Name: <input maxlength="10" name="name" type="text" value="override" /></p>' and instead of In [23]: f4 = AdvancedForm(initial={'name': 'precedence'}) How to pass in more than one dictionary (that is a dictionary of dictionaries) at a time, as the context? AND have the same dynamic behavior as noted in the link? -
edit style of django-tinymce
Hi everyone I create a page extension in django-cms I create a text area using django-tinymce so in my model I have this content = HTMLField() and in my setting.py file I have this TINYMCE_DEFAULT_CONFIG = { 'width': '100%', 'height': '300' } the extension work but the django-tinymce field is so ugly and I try to change de css style but, I don't the way. Right now my field looks like this. I want to reduce the space between the buttons, any idea how to do that? thanks in advance! -
django template href external file
I use this template to list links: {{ oLink.text }} oLink.link could be something like: 'http://www.google.com' or '\shared_files\GMO-M0960\GMO-M0960_01.pdf' oLink.text is just a simple text to be used. Links reference to another webpage work correctly, but links reference to files inside a shared directory don't (new window never opens) It works only if I right click on the link and then copy its url in a new window. Do I need to configure something? This seems to be so simple. -
Enable browser to go back to page with filters
I have a website like this: http://google.com On the page there's a search box and some filters, which when we do search the URL will become: http://google.com/?search=Stuff&type=Books On the results page there will be books that we can click on, which will take us into a URL like this: http://google.com/book_info/harry-potter I want to put a back button that will take the user back to the search page, but with the filters etc already selected so they can continue on. This works if they access the book info directly from the same tab as the search (so they access the search with filters, then click on the book), but if they access the book by opening a new tab, I can't just simply have javascript redirect the user back 1 page in their history. Is there a way for me to do this? Thanks :) -
Android Server connection refused error (works in browser)
I am making an Android app, and I am trying to access a web-service call I make from localhost inside a virtual machine(VM) on my app. I have a windows machine with a Linux VM. Inside this VM, I make a Django-REST GET request through localhost. I enabled port forwarding in my VM also so that I can access the URL corresponding to the GET request inside the windows component. When I go to the URL in my browser in the windows box, it works, however, if I try to access it in my Android device emulator, it gives me the error below. I have already tried using the IP address "10.0.2.2". Any guidance on this would be greatly appreciated! My Java code for accessing this rest call is below the error. W/System.err: java.net.ConnectException: Connection refused W/System.err: at java.net.PlainSocketImpl.socketConnect(Native Method) W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334) W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196) W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178) W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) W/System.err: at java.net.Socket.connect(Socket.java:586) W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113) W/System.err: at com.android.okhttp.Connection.connectSocket(Connection.java:196) W/System.err: at com.android.okhttp.Connection.connect(Connection.java:172) W/System.err: at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367) W/System.err: at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130) W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246) W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457) W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126) W/System.err: at com.example.schadtj.portalapp.fragments.FragmentHiddenUserInfoRest$InfoRest.doInBackground(FragmentHiddenUserInfoRest.java:300) W/System.err: at com.example.schadtj.portalapp.fragments.FragmentHiddenUserInfoRest$InfoRest.doInBackground(FragmentHiddenUserInfoRest.java:104) W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:304) W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) … -
Django insert or update in one table should reflect in another table
I am trying to create a cart using django-carton App. I have two models: Halls and Caterer. I want to add either of these Halls or Caterer object in cart when I will call add() method. While using this API, I need to register my model in settings.py as below CART_PRODUCT_MODEL = 'marriage_halls.models.Hall' I can register only one model at a time. So I can't add Caterer object in the cart.To resolve this issue, I'm planning to create new 'product' model which will contain 3 columns viz. {name, price, city}. These are the columns which are common in both Hall and Caterer and I want to display them when I'll call show() method. My first question is, is it a correct way to do it? If its a correct approach, What I want to do is, whenever I will add new Hall or Caterer in their respective tables through Django's admin interface, only these 3 column values should get inserted to Product table (INSERT new row in product table). How can I achieve this? -
How to filter objects in ManyToMany field back reference?
I want to list all published tags and published posts like this: Tag1 ├── first-post └── second-post Tag2 ├── third-post └── fourth-post I have Tag and Post models like this: class Tag(models.Model): name = models.CharField(max_length=16) is_published = models.BooleanField(default=True) class Post(models.Model): title = models.CharField(max_length=192) tags = models.ManyToManyField(Tag, related_name='posts') is_published = models.BooleanField(default=True) I have a context processor which is passing tags to templates: def tags(request): published_tags = Tag.objects\ .filter(is_published=True)\ .exclude(posts=None)\ .order_by('name') return {'tags': published_tags} I'm listing Tags and Posts in template like this: {% for tag in tags %} <h1>{{ tag.name }}</h1> {% for post in tag.posts.all %} <li> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </li> {% endfor %} {% endfor %} I can filter tags by is_published. How I can filter the posts by is_published within back reference in the Tags (Tag.posts)? I don't want to return two query sets named tags and `posts'. -
Don't understand how Django's CSRF protection works
Reading this section of the Django docs they recommend setting a csrftoken in a cookie and then having the client-side framework put this in a header which will be validated on a server-side request. However, doesn't having the token in a cookie defeat the purpose because the cookies are sent on every user's request? Or is the "security" here that Django checks for that value in a header rather than checking the cookie value itself? I do understand why this works for synchronous submissions, but in that case the csrftoken is written directly to the page rather than stored in a cookie, which seems more secure. From the OWASP page on reviewing code for CSRF: Checking if the request has a valid session cookie is not enough, we need check if a unique identifier is sent with every HTTP request sent to the application. CSRF requests WON'T have this valid unique identifier. The reason CSRF requests won't have this unique request identifier is the unique ID is rendered as a hidden field on the page and is appended to the HTTP request once a link/button press is selected. The attacker will have no knowledge of this unique ID, as it … -
How to make my models follow DRY principles
I have a model in which I need to represent different jobs for a labor application, for example: from django.db import models class PostFirstJobAd(models.Model): fist_job_ad_title = models.CharField(max_length=225) first_job_ad_description = models.TextField() created_at = models.DateTimeField(auto_now=True) class PostSecondJobAd(models.Model): second_job_ad_title = models.CharField(max_length=225) second_job_ad_description = models.TextField() created_at = models.DateTimeField(auto_now=True) class PostThirdJobAd(models.Model): third_job_ad_title = models.CharField(max_length=225) third_job_ad_description = models.TextField() created_at = models.DateTimeField(auto_now=True) Instantly you can see that I'm repeating title, description and created_at, I'm just changing field's name, it's not DRY and code is starting to smell. The reason for this is because I want to register every job separately inside django admin, so I will have clear situation inside site administration. One way to make them DRY is to use Abstract base classes but I have a problem because from the docs: This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class. What will be the right approach in this case, can someone help me understand this.